gawk-2.11/ 755 11660 0 0 4527633727 10505 5ustar hackwheelgawk-2.11/awk.h 644 11660 0 40407 4527633562 11542 0ustar hackwheel/* * awk.h -- Definitions for gawk. */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ /* ------------------------------ Includes ------------------------------ */ #include #include #include #include #include #include #include #include "regex.h" /* ------------------- System Functions, Variables, etc ------------------- */ /* nasty nasty SunOS-ism */ #ifdef sparc #include #ifdef lint extern char *alloca(); #endif #else extern char *alloca(); #endif #ifdef SPRINTF_INT extern int sprintf(); #else /* not USG */ /* nasty nasty berkelixm */ #define setjmp _setjmp #define longjmp _longjmp extern char *sprintf(); #endif /* * if you don't have vprintf, but you are BSD, the version defined in * vprintf.c should do the trick. Otherwise, use this and cross your fingers. */ #if defined(VPRINTF_MISSING) && !defined(DOPRNT_MISSING) && !defined(BSDSTDIO) #define vfprintf(fp,fmt,arg) _doprnt((fmt), (arg), (fp)) #endif #ifdef __STDC__ extern void *malloc(unsigned), *realloc(void *, unsigned); extern void free(char *); extern char *getenv(char *); extern char *strcpy(char *, char *), *strcat(char *, char *), *strncpy(char *, char *, int); extern int strcmp(char *, char *); extern int strncmp(char *, char *, int); extern int strncasecmp(char *, char *, int); extern char *strerror(int); extern char *strchr(char *, int); extern int strlen(char *); extern char *memcpy(char *, char *, int); extern int memcmp(char *, char *, int); extern char *memset(char *, int, int); /* extern int fprintf(FILE *, char *, ...); */ extern int fprintf(); extern int vfprintf(); #ifndef MSDOS extern int fwrite(char *, int, int, FILE *); #endif extern int fflush(FILE *); extern int fclose(FILE *); extern int pclose(FILE *); #ifndef MSDOS extern int fputs(char *, FILE *); #endif extern void abort(); extern int isatty(int); extern void exit(int); extern int system(char *); extern int sscanf(/* char *, char *, ... */); extern double atof(char *); extern int fstat(int, struct stat *); extern off_t lseek(int, off_t, int); extern int fseek(FILE *, long, int); extern int close(int); extern int open(); extern int pipe(int *); extern int dup2(int, int); #ifndef MSDOS extern int unlink(char *); #endif extern int fork(); extern int execl(/* char *, char *, ... */); extern int read(int, char *, int); extern int wait(int *); extern void _exit(int); #else extern void _exit(); extern int wait(); extern int read(); extern int execl(); extern int fork(); extern int unlink(); extern int dup2(); extern int pipe(); extern int open(); extern int close(); extern int fseek(); extern off_t lseek(); extern int fstat(); extern void exit(); extern int system(); extern int isatty(); extern void abort(); extern int fputs(); extern int fclose(); extern int pclose(); extern int fflush(); extern int fwrite(); extern int fprintf(); extern int vfprintf(); extern int sscanf(); extern char *malloc(), *realloc(); extern void free(); extern char *getenv(); extern int strcmp(); extern int strncmp(); extern int strncasecmp(); extern int strlen(); extern char *strcpy(), *strcat(), *strncpy(); extern char *memset(); extern int memcmp(); extern char *memcpy(); extern char *strerror(); extern char *strchr(); extern double atof(); #endif #ifndef MSDOS extern int errno; #endif /* MSDOS */ /* ------------------ Constants, Structures, Typedefs ------------------ */ #define AWKNUM double typedef enum { /* illegal entry == 0 */ Node_illegal, /* binary operators lnode and rnode are the expressions to work on */ Node_times, Node_quotient, Node_mod, Node_plus, Node_minus, Node_cond_pair, /* conditional pair (see Node_line_range) */ Node_subscript, Node_concat, Node_exp, /* unary operators subnode is the expression to work on */ /*10*/ Node_preincrement, Node_predecrement, Node_postincrement, Node_postdecrement, Node_unary_minus, Node_field_spec, /* assignments lnode is the var to assign to, rnode is the exp */ Node_assign, Node_assign_times, Node_assign_quotient, Node_assign_mod, /*20*/ Node_assign_plus, Node_assign_minus, Node_assign_exp, /* boolean binaries lnode and rnode are expressions */ Node_and, Node_or, /* binary relationals compares lnode and rnode */ Node_equal, Node_notequal, Node_less, Node_greater, Node_leq, /*30*/ Node_geq, Node_match, Node_nomatch, /* unary relationals works on subnode */ Node_not, /* program structures */ Node_rule_list, /* lnode is a rule, rnode is rest of list */ Node_rule_node, /* lnode is pattern, rnode is statement */ Node_statement_list, /* lnode is statement, rnode is more list */ Node_if_branches, /* lnode is to run on true, rnode on false */ Node_expression_list, /* lnode is an exp, rnode is more list */ Node_param_list, /* lnode is a variable, rnode is more list */ /* keywords */ /*40*/ Node_K_if, /* lnode is conditonal, rnode is if_branches */ Node_K_while, /* lnode is condtional, rnode is stuff to run */ Node_K_for, /* lnode is for_struct, rnode is stuff to run */ Node_K_arrayfor, /* lnode is for_struct, rnode is stuff to run */ Node_K_break, /* no subs */ Node_K_continue, /* no stuff */ Node_K_print, /* lnode is exp_list, rnode is redirect */ Node_K_printf, /* lnode is exp_list, rnode is redirect */ Node_K_next, /* no subs */ Node_K_exit, /* subnode is return value, or NULL */ Node_K_do, /* lnode is conditional, rnode stuff to run */ Node_K_return, Node_K_delete, Node_K_getline, Node_K_function, /* lnode is statement list, rnode is params */ /* I/O redirection for print statements */ Node_redirect_output, /* subnode is where to redirect */ Node_redirect_append, /* subnode is where to redirect */ Node_redirect_pipe, /* subnode is where to redirect */ Node_redirect_pipein, /* subnode is where to redirect */ Node_redirect_input, /* subnode is where to redirect */ /* Variables */ Node_var, /* rnode is value, lnode is array stuff */ Node_var_array, /* array is ptr to elements, asize num of * eles */ Node_val, /* node is a value - type in flags */ /* Builtins subnode is explist to work on, proc is func to call */ Node_builtin, /* * pattern: conditional ',' conditional ; lnode of Node_line_range * is the two conditionals (Node_cond_pair), other word (rnode place) * is a flag indicating whether or not this range has been entered. */ Node_line_range, /* * boolean test of membership in array lnode is string-valued * expression rnode is array name */ Node_in_array, Node_func, /* lnode is param. list, rnode is body */ Node_func_call, /* lnode is name, rnode is argument list */ Node_cond_exp, /* lnode is conditonal, rnode is if_branches */ Node_regex, Node_hashnode, Node_ahash, } NODETYPE; /* * NOTE - this struct is a rather kludgey -- it is packed to minimize * space usage, at the expense of cleanliness. Alter at own risk. */ typedef struct exp_node { union { struct { union { struct exp_node *lptr; char *param_name; char *retext; struct exp_node *nextnode; } l; union { struct exp_node *rptr; struct exp_node *(*pptr) (); struct re_pattern_buffer *preg; struct for_loop_header *hd; struct exp_node **av; int r_ent; /* range entered */ } r; char *name; short number; unsigned char recase; } nodep; struct { AWKNUM fltnum; /* this is here for optimal packing of * the structure on many machines */ char *sp; short slen; unsigned char sref; } val; struct { struct exp_node *next; char *name; int length; struct exp_node *value; } hash; #define hnext sub.hash.next #define hname sub.hash.name #define hlength sub.hash.length #define hvalue sub.hash.value struct { struct exp_node *next; struct exp_node *name; struct exp_node *value; } ahash; #define ahnext sub.ahash.next #define ahname sub.ahash.name #define ahvalue sub.ahash.value } sub; NODETYPE type; unsigned char flags; # define MEM 0x7 # define MALLOC 1 /* can be free'd */ # define TEMP 2 /* should be free'd */ # define PERM 4 /* can't be free'd */ # define VAL 0x18 # define NUM 8 /* numeric value is valid */ # define STR 16 /* string value is valid */ # define NUMERIC 32 /* entire field is numeric */ } NODE; #define lnode sub.nodep.l.lptr #define nextp sub.nodep.l.nextnode #define rnode sub.nodep.r.rptr #define source_file sub.nodep.name #define source_line sub.nodep.number #define param_cnt sub.nodep.number #define param sub.nodep.l.param_name #define subnode lnode #define proc sub.nodep.r.pptr #define reexp lnode #define rereg sub.nodep.r.preg #define re_case sub.nodep.recase #define re_text sub.nodep.l.retext #define forsub lnode #define forloop rnode->sub.nodep.r.hd #define stptr sub.val.sp #define stlen sub.val.slen #define stref sub.val.sref #define valstat flags #define numbr sub.val.fltnum #define var_value lnode #define var_array sub.nodep.r.av #define condpair lnode #define triggered sub.nodep.r.r_ent #define HASHSIZE 101 typedef struct for_loop_header { NODE *init; NODE *cond; NODE *incr; } FOR_LOOP_HEADER; /* for "for(iggy in foo) {" */ struct search { int numleft; NODE **arr_ptr; NODE *bucket; NODE *retval; }; /* for faster input, bypass stdio */ typedef struct iobuf { int fd; char *buf; char *off; int size; /* this will be determined by an fstat() call */ int cnt; char *secbuf; int secsiz; int flag; # define IOP_IS_TTY 1 } IOBUF; /* * structure used to dynamically maintain a linked-list of open files/pipes */ struct redirect { int flag; # define RED_FILE 1 # define RED_PIPE 2 # define RED_READ 4 # define RED_WRITE 8 # define RED_APPEND 16 # define RED_NOBUF 32 char *value; FILE *fp; IOBUF *iop; int pid; int status; long offset; /* used for dynamic management of open files */ struct redirect *prev; struct redirect *next; }; /* longjmp return codes, must be nonzero */ /* Continue means either for loop/while continue, or next input record */ #define TAG_CONTINUE 1 /* Break means either for/while break, or stop reading input */ #define TAG_BREAK 2 /* Return means return from a function call; leave value in ret_node */ #define TAG_RETURN 3 #ifdef MSDOS #define HUGE 0x7fff #else #define HUGE 0x7fffffff #endif /* -------------------------- External variables -------------------------- */ /* gawk builtin variables */ extern NODE *FS_node, *NF_node, *RS_node, *NR_node; extern NODE *FILENAME_node, *OFS_node, *ORS_node, *OFMT_node; extern NODE *FNR_node, *RLENGTH_node, *RSTART_node, *SUBSEP_node; extern NODE *IGNORECASE_node; extern NODE **stack_ptr; extern NODE *Nnull_string; extern NODE *deref; extern NODE **fields_arr; extern int sourceline; extern char *source; extern NODE *expression_value; extern NODE *variables[]; extern NODE *_t; /* used as temporary in tree_eval */ extern char *myname; extern int node0_valid; extern int field_num; extern int strict; /* ------------------------- Pseudo-functions ------------------------- */ #define is_identchar(c) (isalnum(c) || (c) == '_') #define free_temp(n) if ((n)->flags&TEMP) { deref = (n); do_deref(); } else #define tree_eval(t) (_t = (t),(_t) == NULL ? Nnull_string : \ ((_t)->type == Node_val ? (_t) : r_tree_eval((_t)))) #define make_string(s,l) make_str_node((s),(l),0) #define cant_happen() fatal("line %d, file: %s; bailing out", \ __LINE__, __FILE__); #ifdef MEMDEBUG #define memmsg(x,y,z,zz) fprintf(stderr, "malloc: %s: %s: %d %0x\n", z, x, y, zz) #define free(s) fprintf(stderr, "free: s: %0x\n", s), do_free(s) #else #define memmsg(x,y,z,zz) #endif #define emalloc(var,ty,x,str) if ((var = (ty) malloc((unsigned)(x))) == NULL)\ fatal("%s: %s: can't allocate memory (%s)",\ (str), "var", strerror(errno)); else\ memmsg("var", x, str, var) #define erealloc(var,ty,x,str) if((var=(ty)realloc((char *)var,\ (unsigned)(x)))==NULL)\ fatal("%s: %s: can't allocate memory (%s)",\ (str), "var", strerror(errno)); else\ memmsg("re: var", x, str, var) #ifdef DEBUG #define force_number r_force_number #define force_string r_force_string #else #ifdef lint extern AWKNUM force_number(); #endif #ifdef MSDOS extern double _msc51bug; #define force_number(n) (_msc51bug=(_t = (n),(_t->flags & NUM) ? _t->numbr : r_force_number(_t))) #else #define force_number(n) (_t = (n),(_t->flags & NUM) ? _t->numbr : r_force_number(_t)) #endif #define force_string(s) (_t = (s),(_t->flags & STR) ? _t : r_force_string(_t)) #endif #define STREQ(a,b) (*(a) == *(b) && strcmp((a), (b)) == 0) #define STREQN(a,b,n) ((n) && *(a) == *(b) && strncmp((a), (b), (n)) == 0) #define WHOLELINE (node0_valid ? fields_arr[0] : *get_field(0,0)) /* ------------- Function prototypes or defs (as appropriate) ------------- */ #ifdef __STDC__ extern int parse_escape(char **); extern int devopen(char *, char *); extern struct re_pattern_buffer *make_regexp(NODE *, int); extern struct re_pattern_buffer *mk_re_parse(char *, int); extern NODE *variable(char *); extern NODE *install(NODE **, char *, NODE *); extern NODE *lookup(NODE **, char *); extern NODE *make_name(char *, NODETYPE); extern int interpret(NODE *); extern NODE *r_tree_eval(NODE *); extern void assign_number(NODE **, double); extern int cmp_nodes(NODE *, NODE *); extern struct redirect *redirect(NODE *, int *); extern int flush_io(void); extern void print_simple(NODE *, FILE *); /* extern void warning(char *,...); */ extern void warning(); /* extern void fatal(char *,...); */ extern void fatal(); extern void set_record(char *, int); extern NODE **get_field(int, int); extern NODE **get_lhs(NODE *, int); extern void do_deref(void ); extern struct search *assoc_scan(NODE *); extern struct search *assoc_next(struct search *); extern NODE **assoc_lookup(NODE *, NODE *); extern double r_force_number(NODE *); extern NODE *r_force_string(NODE *); extern NODE *newnode(NODETYPE); extern NODE *dupnode(NODE *); extern NODE *make_number(double); extern NODE *tmp_number(double); extern NODE *make_str_node(char *, int, int); extern NODE *tmp_string(char *, int); extern char *re_compile_pattern(char *, int, struct re_pattern_buffer *); extern int re_search(struct re_pattern_buffer *, char *, int, int, int, struct re_registers *); extern void freenode(NODE *); #else extern int parse_escape(); extern void freenode(); extern int devopen(); extern struct re_pattern_buffer *make_regexp(); extern struct re_pattern_buffer *mk_re_parse(); extern NODE *variable(); extern NODE *install(); extern NODE *lookup(); extern int interpret(); extern NODE *r_tree_eval(); extern void assign_number(); extern int cmp_nodes(); extern struct redirect *redirect(); extern int flush_io(); extern void print_simple(); extern void warning(); extern void fatal(); extern void set_record(); extern NODE **get_field(); extern NODE **get_lhs(); extern void do_deref(); extern struct search *assoc_scan(); extern struct search *assoc_next(); extern NODE **assoc_lookup(); extern double r_force_number(); extern NODE *r_force_string(); extern NODE *newnode(); extern NODE *dupnode(); extern NODE *make_number(); extern NODE *tmp_number(); extern NODE *make_str_node(); extern NODE *tmp_string(); extern char *re_compile_pattern(); extern int re_search(); #endif #if !defined(__STDC__) || __STDC__ <= 0 #define volatile #endif /* Figure out what '\a' really is. */ #ifdef __STDC__ #define BELL '\a' /* sure makes life easy, don't it? */ #else # if 'z' - 'a' == 25 /* ascii */ # if 'a' != 97 /* machine is dumb enough to use mark parity */ # define BELL '\207' # else # define BELL '\07' # endif # else # define BELL '\057' # endif #endif #ifndef SIGTYPE #define SIGTYPE void #endif extern char casetable[]; /* for case-independent regexp matching */ gawk-2.11/awk.y 644 11660 0 110231 4527633564 11576 0ustar hackwheel/* * awk.y --- yacc/bison parser */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ %{ #ifdef DEBUG #define YYDEBUG 12 #endif #include "awk.h" /* * This line is necessary since the Bison parser skeleton uses bcopy. * Systems without memcpy should use -DMEMCPY_MISSING, per the Makefile. * It should not hurt anything if Yacc is being used instead of Bison. */ #define bcopy(s,d,n) memcpy((d),(s),(n)) extern void msg(); extern struct re_pattern_buffer *mk_re_parse(); NODE *node(); NODE *lookup(); NODE *install(); static NODE *snode(); static NODE *mkrangenode(); static FILE *pathopen(); static NODE *make_for_loop(); static NODE *append_right(); static void func_install(); static NODE *make_param(); static int hashf(); static void pop_params(); static void pop_var(); static int yylex (); static void yyerror(); static int want_regexp; /* lexical scanning kludge */ static int want_assign; /* lexical scanning kludge */ static int can_return; /* lexical scanning kludge */ static int io_allowed = 1; /* lexical scanning kludge */ static int lineno = 1; /* for error msgs */ static char *lexptr; /* pointer to next char during parsing */ static char *lexptr_begin; /* keep track of where we were for error msgs */ static int curinfile = -1; /* index into sourcefiles[] */ static int param_counter; NODE *variables[HASHSIZE]; extern int errcount; extern NODE *begin_block; extern NODE *end_block; %} %union { long lval; AWKNUM fval; NODE *nodeval; NODETYPE nodetypeval; char *sval; NODE *(*ptrval)(); } %type function_prologue function_body %type rexp exp start program rule simp_exp %type pattern %type action variable param_list %type rexpression_list opt_rexpression_list %type expression_list opt_expression_list %type statements statement if_statement opt_param_list %type opt_exp opt_variable regexp %type input_redir output_redir %type r_paren comma nls opt_nls print %type func_name %token FUNC_CALL NAME REGEXP %token ERROR %token NUMBER YSTRING %token RELOP APPEND_OP %token ASSIGNOP MATCHOP NEWLINE CONCAT_OP %token LEX_BEGIN LEX_END LEX_IF LEX_ELSE LEX_RETURN LEX_DELETE %token LEX_WHILE LEX_DO LEX_FOR LEX_BREAK LEX_CONTINUE %token LEX_PRINT LEX_PRINTF LEX_NEXT LEX_EXIT LEX_FUNCTION %token LEX_GETLINE %token LEX_IN %token LEX_AND LEX_OR INCREMENT DECREMENT %token LEX_BUILTIN LEX_LENGTH /* these are just yylval numbers */ /* Lowest to highest */ %right ASSIGNOP %right '?' ':' %left LEX_OR %left LEX_AND %left LEX_GETLINE %nonassoc LEX_IN %left FUNC_CALL LEX_BUILTIN LEX_LENGTH %nonassoc MATCHOP %nonassoc RELOP '<' '>' '|' APPEND_OP %left CONCAT_OP %left YSTRING NUMBER %left '+' '-' %left '*' '/' '%' %right '!' UNARY %right '^' %left INCREMENT DECREMENT %left '$' %left '(' ')' %% start : opt_nls program opt_nls { expression_value = $2; } ; program : rule { if ($1 != NULL) $$ = $1; else $$ = NULL; yyerrok; } | program rule /* add the rule to the tail of list */ { if ($2 == NULL) $$ = $1; else if ($1 == NULL) $$ = $2; else { if ($1->type != Node_rule_list) $1 = node($1, Node_rule_list, (NODE*)NULL); $$ = append_right ($1, node($2, Node_rule_list,(NODE *) NULL)); } yyerrok; } | error { $$ = NULL; } | program error { $$ = NULL; } ; rule : LEX_BEGIN { io_allowed = 0; } action { if (begin_block) { if (begin_block->type != Node_rule_list) begin_block = node(begin_block, Node_rule_list, (NODE *)NULL); append_right (begin_block, node( node((NODE *)NULL, Node_rule_node, $3), Node_rule_list, (NODE *)NULL) ); } else begin_block = node((NODE *)NULL, Node_rule_node, $3); $$ = NULL; io_allowed = 1; yyerrok; } | LEX_END { io_allowed = 0; } action { if (end_block) { if (end_block->type != Node_rule_list) end_block = node(end_block, Node_rule_list, (NODE *)NULL); append_right (end_block, node( node((NODE *)NULL, Node_rule_node, $3), Node_rule_list, (NODE *)NULL)); } else end_block = node((NODE *)NULL, Node_rule_node, $3); $$ = NULL; io_allowed = 1; yyerrok; } | LEX_BEGIN statement_term { msg ("error near line %d: BEGIN blocks must have an action part", lineno); errcount++; yyerrok; } | LEX_END statement_term { msg ("error near line %d: END blocks must have an action part", lineno); errcount++; yyerrok; } | pattern action { $$ = node ($1, Node_rule_node, $2); yyerrok; } | action { $$ = node ((NODE *)NULL, Node_rule_node, $1); yyerrok; } | pattern statement_term { if($1) $$ = node ($1, Node_rule_node, (NODE *)NULL); yyerrok; } | function_prologue function_body { func_install($1, $2); $$ = NULL; yyerrok; } ; func_name : NAME { $$ = $1; } | FUNC_CALL { $$ = $1; } ; function_prologue : LEX_FUNCTION { param_counter = 0; } func_name '(' opt_param_list r_paren opt_nls { $$ = append_right(make_param($3), $5); can_return = 1; } ; function_body : l_brace statements r_brace { $$ = $2; can_return = 0; } ; pattern : exp { $$ = $1; } | exp comma exp { $$ = mkrangenode ( node($1, Node_cond_pair, $3) ); } ; regexp /* * In this rule, want_regexp tells yylex that the next thing * is a regexp so it should read up to the closing slash. */ : '/' { ++want_regexp; } REGEXP '/' { want_regexp = 0; $$ = node((NODE *)NULL,Node_regex,(NODE *)mk_re_parse($3, 0)); $$ -> re_case = 0; emalloc ($$ -> re_text, char *, strlen($3)+1, "regexp"); strcpy ($$ -> re_text, $3); } ; action : l_brace r_brace opt_semi { /* empty actions are different from missing actions */ $$ = node ((NODE *) NULL, Node_illegal, (NODE *) NULL); } | l_brace statements r_brace opt_semi { $$ = $2 ; } ; statements : statement { $$ = $1; } | statements statement { if ($1 == NULL || $1->type != Node_statement_list) $1 = node($1, Node_statement_list,(NODE *)NULL); $$ = append_right($1, node( $2, Node_statement_list, (NODE *)NULL)); yyerrok; } | error { $$ = NULL; } | statements error { $$ = NULL; } ; statement_term : nls { $$ = Node_illegal; } | semi opt_nls { $$ = Node_illegal; } ; statement : semi opt_nls { $$ = NULL; } | l_brace r_brace { $$ = NULL; } | l_brace statements r_brace { $$ = $2; } | if_statement { $$ = $1; } | LEX_WHILE '(' exp r_paren opt_nls statement { $$ = node ($3, Node_K_while, $6); } | LEX_DO opt_nls statement LEX_WHILE '(' exp r_paren opt_nls { $$ = node ($6, Node_K_do, $3); } | LEX_FOR '(' NAME LEX_IN NAME r_paren opt_nls statement { $$ = node ($8, Node_K_arrayfor, make_for_loop(variable($3), (NODE *)NULL, variable($5))); } | LEX_FOR '(' opt_exp semi exp semi opt_exp r_paren opt_nls statement { $$ = node($10, Node_K_for, (NODE *)make_for_loop($3, $5, $7)); } | LEX_FOR '(' opt_exp semi semi opt_exp r_paren opt_nls statement { $$ = node ($9, Node_K_for, (NODE *)make_for_loop($3, (NODE *)NULL, $6)); } | LEX_BREAK statement_term /* for break, maybe we'll have to remember where to break to */ { $$ = node ((NODE *)NULL, Node_K_break, (NODE *)NULL); } | LEX_CONTINUE statement_term /* similarly */ { $$ = node ((NODE *)NULL, Node_K_continue, (NODE *)NULL); } | print '(' expression_list r_paren output_redir statement_term { $$ = node ($3, $1, $5); } | print opt_rexpression_list output_redir statement_term { $$ = node ($2, $1, $3); } | LEX_NEXT { if (! io_allowed) yyerror("next used in BEGIN or END action"); } statement_term { $$ = node ((NODE *)NULL, Node_K_next, (NODE *)NULL); } | LEX_EXIT opt_exp statement_term { $$ = node ($2, Node_K_exit, (NODE *)NULL); } | LEX_RETURN { if (! can_return) yyerror("return used outside function context"); } opt_exp statement_term { $$ = node ($3, Node_K_return, (NODE *)NULL); } | LEX_DELETE NAME '[' expression_list ']' statement_term { $$ = node (variable($2), Node_K_delete, $4); } | exp statement_term { $$ = $1; } ; print : LEX_PRINT { $$ = $1; } | LEX_PRINTF { $$ = $1; } ; if_statement : LEX_IF '(' exp r_paren opt_nls statement { $$ = node($3, Node_K_if, node($6, Node_if_branches, (NODE *)NULL)); } | LEX_IF '(' exp r_paren opt_nls statement LEX_ELSE opt_nls statement { $$ = node ($3, Node_K_if, node ($6, Node_if_branches, $9)); } ; nls : NEWLINE { $$ = NULL; } | nls NEWLINE { $$ = NULL; } ; opt_nls : /* empty */ { $$ = NULL; } | nls { $$ = NULL; } ; input_redir : /* empty */ { $$ = NULL; } | '<' simp_exp { $$ = node ($2, Node_redirect_input, (NODE *)NULL); } ; output_redir : /* empty */ { $$ = NULL; } | '>' exp { $$ = node ($2, Node_redirect_output, (NODE *)NULL); } | APPEND_OP exp { $$ = node ($2, Node_redirect_append, (NODE *)NULL); } | '|' exp { $$ = node ($2, Node_redirect_pipe, (NODE *)NULL); } ; opt_param_list : /* empty */ { $$ = NULL; } | param_list { $$ = $1; } ; param_list : NAME { $$ = make_param($1); } | param_list comma NAME { $$ = append_right($1, make_param($3)); yyerrok; } | error { $$ = NULL; } | param_list error { $$ = NULL; } | param_list comma error { $$ = NULL; } ; /* optional expression, as in for loop */ opt_exp : /* empty */ { $$ = NULL; } | exp { $$ = $1; } ; opt_rexpression_list : /* empty */ { $$ = NULL; } | rexpression_list { $$ = $1; } ; rexpression_list : rexp { $$ = node ($1, Node_expression_list, (NODE *)NULL); } | rexpression_list comma rexp { $$ = append_right($1, node( $3, Node_expression_list, (NODE *)NULL)); yyerrok; } | error { $$ = NULL; } | rexpression_list error { $$ = NULL; } | rexpression_list error rexp { $$ = NULL; } | rexpression_list comma error { $$ = NULL; } ; opt_expression_list : /* empty */ { $$ = NULL; } | expression_list { $$ = $1; } ; expression_list : exp { $$ = node ($1, Node_expression_list, (NODE *)NULL); } | expression_list comma exp { $$ = append_right($1, node( $3, Node_expression_list, (NODE *)NULL)); yyerrok; } | error { $$ = NULL; } | expression_list error { $$ = NULL; } | expression_list error exp { $$ = NULL; } | expression_list comma error { $$ = NULL; } ; /* Expressions, not including the comma operator. */ exp : variable ASSIGNOP { want_assign = 0; } exp { $$ = node ($1, $2, $4); } | '(' expression_list r_paren LEX_IN NAME { $$ = node (variable($5), Node_in_array, $2); } | exp '|' LEX_GETLINE opt_variable { $$ = node ($4, Node_K_getline, node ($1, Node_redirect_pipein, (NODE *)NULL)); } | LEX_GETLINE opt_variable input_redir { /* "too painful to do right" */ /* if (! io_allowed && $3 == NULL) yyerror("non-redirected getline illegal inside BEGIN or END action"); */ $$ = node ($2, Node_K_getline, $3); } | exp LEX_AND exp { $$ = node ($1, Node_and, $3); } | exp LEX_OR exp { $$ = node ($1, Node_or, $3); } | exp MATCHOP exp { $$ = node ($1, $2, $3); } | regexp { $$ = $1; } | '!' regexp %prec UNARY { $$ = node((NODE *) NULL, Node_nomatch, $2); } | exp LEX_IN NAME { $$ = node (variable($3), Node_in_array, $1); } | exp RELOP exp { $$ = node ($1, $2, $3); } | exp '<' exp { $$ = node ($1, Node_less, $3); } | exp '>' exp { $$ = node ($1, Node_greater, $3); } | exp '?' exp ':' exp { $$ = node($1, Node_cond_exp, node($3, Node_if_branches, $5));} | simp_exp { $$ = $1; } | exp exp %prec CONCAT_OP { $$ = node ($1, Node_concat, $2); } ; rexp : variable ASSIGNOP { want_assign = 0; } rexp { $$ = node ($1, $2, $4); } | rexp LEX_AND rexp { $$ = node ($1, Node_and, $3); } | rexp LEX_OR rexp { $$ = node ($1, Node_or, $3); } | LEX_GETLINE opt_variable input_redir { /* "too painful to do right" */ /* if (! io_allowed && $3 == NULL) yyerror("non-redirected getline illegal inside BEGIN or END action"); */ $$ = node ($2, Node_K_getline, $3); } | regexp { $$ = $1; } | '!' regexp %prec UNARY { $$ = node((NODE *) NULL, Node_nomatch, $2); } | rexp MATCHOP rexp { $$ = node ($1, $2, $3); } | rexp LEX_IN NAME { $$ = node (variable($3), Node_in_array, $1); } | rexp RELOP rexp { $$ = node ($1, $2, $3); } | rexp '?' rexp ':' rexp { $$ = node($1, Node_cond_exp, node($3, Node_if_branches, $5));} | simp_exp { $$ = $1; } | rexp rexp %prec CONCAT_OP { $$ = node ($1, Node_concat, $2); } ; simp_exp : '!' simp_exp %prec UNARY { $$ = node ($2, Node_not,(NODE *) NULL); } | '(' exp r_paren { $$ = $2; } | LEX_BUILTIN '(' opt_expression_list r_paren { $$ = snode ($3, Node_builtin, $1); } | LEX_LENGTH '(' opt_expression_list r_paren { $$ = snode ($3, Node_builtin, $1); } | LEX_LENGTH { $$ = snode ((NODE *)NULL, Node_builtin, $1); } | FUNC_CALL '(' opt_expression_list r_paren { $$ = node ($3, Node_func_call, make_string($1, strlen($1))); } | INCREMENT variable { $$ = node ($2, Node_preincrement, (NODE *)NULL); } | DECREMENT variable { $$ = node ($2, Node_predecrement, (NODE *)NULL); } | variable INCREMENT { $$ = node ($1, Node_postincrement, (NODE *)NULL); } | variable DECREMENT { $$ = node ($1, Node_postdecrement, (NODE *)NULL); } | variable { $$ = $1; } | NUMBER { $$ = $1; } | YSTRING { $$ = $1; } /* Binary operators in order of decreasing precedence. */ | simp_exp '^' simp_exp { $$ = node ($1, Node_exp, $3); } | simp_exp '*' simp_exp { $$ = node ($1, Node_times, $3); } | simp_exp '/' simp_exp { $$ = node ($1, Node_quotient, $3); } | simp_exp '%' simp_exp { $$ = node ($1, Node_mod, $3); } | simp_exp '+' simp_exp { $$ = node ($1, Node_plus, $3); } | simp_exp '-' simp_exp { $$ = node ($1, Node_minus, $3); } | '-' simp_exp %prec UNARY { $$ = node ($2, Node_unary_minus, (NODE *)NULL); } | '+' simp_exp %prec UNARY { $$ = $2; } ; opt_variable : /* empty */ { $$ = NULL; } | variable { $$ = $1; } ; variable : NAME { want_assign = 1; $$ = variable ($1); } | NAME '[' expression_list ']' { want_assign = 1; $$ = node (variable($1), Node_subscript, $3); } | '$' simp_exp { want_assign = 1; $$ = node ($2, Node_field_spec, (NODE *)NULL); } ; l_brace : '{' opt_nls ; r_brace : '}' opt_nls { yyerrok; } ; r_paren : ')' { $$ = Node_illegal; yyerrok; } ; opt_semi : /* empty */ | semi ; semi : ';' { yyerrok; } ; comma : ',' opt_nls { $$ = Node_illegal; yyerrok; } ; %% struct token { char *operator; /* text to match */ NODETYPE value; /* node type */ int class; /* lexical class */ short nostrict; /* ignore if in strict compatibility mode */ NODE *(*ptr) (); /* function that implements this keyword */ }; extern NODE *do_exp(), *do_getline(), *do_index(), *do_length(), *do_sqrt(), *do_log(), *do_sprintf(), *do_substr(), *do_split(), *do_system(), *do_int(), *do_close(), *do_atan2(), *do_sin(), *do_cos(), *do_rand(), *do_srand(), *do_match(), *do_tolower(), *do_toupper(), *do_sub(), *do_gsub(); /* Special functions for debugging */ #ifdef DEBUG NODE *do_prvars(), *do_bp(); #endif /* Tokentab is sorted ascii ascending order, so it can be binary searched. */ static struct token tokentab[] = { { "BEGIN", Node_illegal, LEX_BEGIN, 0, 0 }, { "END", Node_illegal, LEX_END, 0, 0 }, { "atan2", Node_builtin, LEX_BUILTIN, 0, do_atan2 }, #ifdef DEBUG { "bp", Node_builtin, LEX_BUILTIN, 0, do_bp }, #endif { "break", Node_K_break, LEX_BREAK, 0, 0 }, { "close", Node_builtin, LEX_BUILTIN, 0, do_close }, { "continue", Node_K_continue, LEX_CONTINUE, 0, 0 }, { "cos", Node_builtin, LEX_BUILTIN, 0, do_cos }, { "delete", Node_K_delete, LEX_DELETE, 0, 0 }, { "do", Node_K_do, LEX_DO, 0, 0 }, { "else", Node_illegal, LEX_ELSE, 0, 0 }, { "exit", Node_K_exit, LEX_EXIT, 0, 0 }, { "exp", Node_builtin, LEX_BUILTIN, 0, do_exp }, { "for", Node_K_for, LEX_FOR, 0, 0 }, { "func", Node_K_function, LEX_FUNCTION, 0, 0 }, { "function", Node_K_function, LEX_FUNCTION, 0, 0 }, { "getline", Node_K_getline, LEX_GETLINE, 0, 0 }, { "gsub", Node_builtin, LEX_BUILTIN, 0, do_gsub }, { "if", Node_K_if, LEX_IF, 0, 0 }, { "in", Node_illegal, LEX_IN, 0, 0 }, { "index", Node_builtin, LEX_BUILTIN, 0, do_index }, { "int", Node_builtin, LEX_BUILTIN, 0, do_int }, { "length", Node_builtin, LEX_LENGTH, 0, do_length }, { "log", Node_builtin, LEX_BUILTIN, 0, do_log }, { "match", Node_builtin, LEX_BUILTIN, 0, do_match }, { "next", Node_K_next, LEX_NEXT, 0, 0 }, { "print", Node_K_print, LEX_PRINT, 0, 0 }, { "printf", Node_K_printf, LEX_PRINTF, 0, 0 }, #ifdef DEBUG { "prvars", Node_builtin, LEX_BUILTIN, 0, do_prvars }, #endif { "rand", Node_builtin, LEX_BUILTIN, 0, do_rand }, { "return", Node_K_return, LEX_RETURN, 0, 0 }, { "sin", Node_builtin, LEX_BUILTIN, 0, do_sin }, { "split", Node_builtin, LEX_BUILTIN, 0, do_split }, { "sprintf", Node_builtin, LEX_BUILTIN, 0, do_sprintf }, { "sqrt", Node_builtin, LEX_BUILTIN, 0, do_sqrt }, { "srand", Node_builtin, LEX_BUILTIN, 0, do_srand }, { "sub", Node_builtin, LEX_BUILTIN, 0, do_sub }, { "substr", Node_builtin, LEX_BUILTIN, 0, do_substr }, { "system", Node_builtin, LEX_BUILTIN, 0, do_system }, { "tolower", Node_builtin, LEX_BUILTIN, 0, do_tolower }, { "toupper", Node_builtin, LEX_BUILTIN, 0, do_toupper }, { "while", Node_K_while, LEX_WHILE, 0, 0 }, }; static char *token_start; /* VARARGS0 */ static void yyerror(va_alist) va_dcl { va_list args; char *mesg; register char *ptr, *beg; char *scan; errcount++; /* Find the current line in the input file */ if (! lexptr) { beg = "(END OF FILE)"; ptr = beg + 13; } else { if (*lexptr == '\n' && lexptr != lexptr_begin) --lexptr; for (beg = lexptr; beg != lexptr_begin && *beg != '\n'; --beg) ; /* NL isn't guaranteed */ for (ptr = lexptr; *ptr && *ptr != '\n'; ptr++) ; if (beg != lexptr_begin) beg++; } msg("syntax error near line %d:\n%.*s", lineno, ptr - beg, beg); scan = beg; while (scan < token_start) if (*scan++ == '\t') putc('\t', stderr); else putc(' ', stderr); putc('^', stderr); putc(' ', stderr); va_start(args); mesg = va_arg(args, char *); vfprintf(stderr, mesg, args); va_end(args); putc('\n', stderr); exit(1); } /* * Parse a C escape sequence. STRING_PTR points to a variable containing a * pointer to the string to parse. That pointer is updated past the * characters we use. The value of the escape sequence is returned. * * A negative value means the sequence \ newline was seen, which is supposed to * be equivalent to nothing at all. * * If \ is followed by a null character, we return a negative value and leave * the string pointer pointing at the null character. * * If \ is followed by 000, we return 0 and leave the string pointer after the * zeros. A value of 0 does not mean end of string. */ int parse_escape(string_ptr) char **string_ptr; { register int c = *(*string_ptr)++; register int i; register int count; switch (c) { case 'a': return BELL; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case '\n': return -2; case 0: (*string_ptr)--; return -1; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': i = c - '0'; count = 0; while (++count < 3) { if ((c = *(*string_ptr)++) >= '0' && c <= '7') { i *= 8; i += c - '0'; } else { (*string_ptr)--; break; } } return i; case 'x': i = 0; while (1) { if (isxdigit((c = *(*string_ptr)++))) { if (isdigit(c)) i += c - '0'; else if (isupper(c)) i += c - 'A' + 10; else i += c - 'a' + 10; } else { (*string_ptr)--; break; } } return i; default: return c; } } /* * Read the input and turn it into tokens. Input is now read from a file * instead of from malloc'ed memory. The main program takes a program * passed as a command line argument and writes it to a temp file. Otherwise * the file name is made available in an external variable. */ static int yylex() { register int c; register int namelen; register char *tokstart; char *tokkey; static did_newline = 0; /* the grammar insists that actions end * with newlines. This was easier than * hacking the grammar. */ int seen_e = 0; /* These are for numbers */ int seen_point = 0; int esc_seen; extern char **sourcefile; extern int tempsource, numfiles; static int file_opened = 0; static FILE *fin; static char cbuf[BUFSIZ]; int low, mid, high; #ifdef DEBUG extern int debugging; #endif if (! file_opened) { file_opened = 1; #ifdef DEBUG if (debugging) { int i; for (i = 0; i <= numfiles; i++) fprintf (stderr, "sourcefile[%d] = %s\n", i, sourcefile[i]); } #endif nextfile: if ((fin = pathopen (sourcefile[++curinfile])) == NULL) fatal("cannot open `%s' for reading (%s)", sourcefile[curinfile], strerror(errno)); *(lexptr = cbuf) = '\0'; /* * immediately unlink the tempfile so that it will * go away cleanly if we bomb. */ if (tempsource && curinfile == 0) (void) unlink (sourcefile[curinfile]); } retry: if (! *lexptr) if (fgets (cbuf, sizeof cbuf, fin) == NULL) { if (fin != NULL) fclose (fin); /* be neat and clean */ if (curinfile < numfiles) goto nextfile; return 0; } else lexptr = lexptr_begin = cbuf; if (want_regexp) { int in_brack = 0; want_regexp = 0; token_start = tokstart = lexptr; while (c = *lexptr++) { switch (c) { case '[': in_brack = 1; break; case ']': in_brack = 0; break; case '\\': if (*lexptr++ == '\0') { yyerror("unterminated regexp ends with \\"); return ERROR; } else if (lexptr[-1] == '\n') goto retry; break; case '/': /* end of the regexp */ if (in_brack) break; lexptr--; yylval.sval = tokstart; return REGEXP; case '\n': lineno++; case '\0': lexptr--; /* so error messages work */ yyerror("unterminated regexp"); return ERROR; } } } if (*lexptr == '\n') { lexptr++; lineno++; return NEWLINE; } while (*lexptr == ' ' || *lexptr == '\t') lexptr++; token_start = tokstart = lexptr; switch (c = *lexptr++) { case 0: return 0; case '\n': lineno++; return NEWLINE; case '#': /* it's a comment */ while (*lexptr != '\n' && *lexptr != '\0') lexptr++; goto retry; case '\\': if (*lexptr == '\n') { lineno++; lexptr++; goto retry; } else break; case ')': case ']': case '(': case '[': case '$': case ';': case ':': case '?': /* * set node type to ILLEGAL because the action should set it * to the right thing */ yylval.nodetypeval = Node_illegal; return c; case '{': case ',': yylval.nodetypeval = Node_illegal; return c; case '*': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_times; lexptr++; return ASSIGNOP; } else if (*lexptr == '*') { /* make ** and **= aliases * for ^ and ^= */ if (lexptr[1] == '=') { yylval.nodetypeval = Node_assign_exp; lexptr += 2; return ASSIGNOP; } else { yylval.nodetypeval = Node_illegal; lexptr++; return '^'; } } yylval.nodetypeval = Node_illegal; return c; case '/': if (want_assign && *lexptr == '=') { yylval.nodetypeval = Node_assign_quotient; lexptr++; return ASSIGNOP; } yylval.nodetypeval = Node_illegal; return c; case '%': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_mod; lexptr++; return ASSIGNOP; } yylval.nodetypeval = Node_illegal; return c; case '^': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_exp; lexptr++; return ASSIGNOP; } yylval.nodetypeval = Node_illegal; return c; case '+': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_plus; lexptr++; return ASSIGNOP; } if (*lexptr == '+') { yylval.nodetypeval = Node_illegal; lexptr++; return INCREMENT; } yylval.nodetypeval = Node_illegal; return c; case '!': if (*lexptr == '=') { yylval.nodetypeval = Node_notequal; lexptr++; return RELOP; } if (*lexptr == '~') { yylval.nodetypeval = Node_nomatch; lexptr++; return MATCHOP; } yylval.nodetypeval = Node_illegal; return c; case '<': if (*lexptr == '=') { yylval.nodetypeval = Node_leq; lexptr++; return RELOP; } yylval.nodetypeval = Node_less; return c; case '=': if (*lexptr == '=') { yylval.nodetypeval = Node_equal; lexptr++; return RELOP; } yylval.nodetypeval = Node_assign; return ASSIGNOP; case '>': if (*lexptr == '=') { yylval.nodetypeval = Node_geq; lexptr++; return RELOP; } else if (*lexptr == '>') { yylval.nodetypeval = Node_redirect_append; lexptr++; return APPEND_OP; } yylval.nodetypeval = Node_greater; return c; case '~': yylval.nodetypeval = Node_match; return MATCHOP; case '}': /* * Added did newline stuff. Easier than * hacking the grammar */ if (did_newline) { did_newline = 0; return c; } did_newline++; --lexptr; return NEWLINE; case '"': esc_seen = 0; while (*lexptr != '\0') { switch (*lexptr++) { case '\\': esc_seen = 1; if (*lexptr == '\n') yyerror("newline in string"); if (*lexptr++ != '\0') break; /* fall through */ case '\n': lexptr--; yyerror("unterminated string"); return ERROR; case '"': yylval.nodeval = make_str_node(tokstart + 1, lexptr-tokstart-2, esc_seen); yylval.nodeval->flags |= PERM; return YSTRING; } } return ERROR; case '-': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_minus; lexptr++; return ASSIGNOP; } if (*lexptr == '-') { yylval.nodetypeval = Node_illegal; lexptr++; return DECREMENT; } yylval.nodetypeval = Node_illegal; return c; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': /* It's a number */ for (namelen = 0; (c = tokstart[namelen]) != '\0'; namelen++) { switch (c) { case '.': if (seen_point) goto got_number; ++seen_point; break; case 'e': case 'E': if (seen_e) goto got_number; ++seen_e; if (tokstart[namelen + 1] == '-' || tokstart[namelen + 1] == '+') namelen++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: goto got_number; } } got_number: lexptr = tokstart + namelen; /* yylval.nodeval = make_string(tokstart, namelen); (void) force_number(yylval.nodeval); */ yylval.nodeval = make_number(atof(tokstart)); yylval.nodeval->flags |= PERM; return NUMBER; case '&': if (*lexptr == '&') { yylval.nodetypeval = Node_and; while (c = *++lexptr) { if (c == '#') while ((c = *++lexptr) != '\n' && c != '\0') ; if (c == '\n') lineno++; else if (! isspace(c)) break; } return LEX_AND; } return ERROR; case '|': if (*lexptr == '|') { yylval.nodetypeval = Node_or; while (c = *++lexptr) { if (c == '#') while ((c = *++lexptr) != '\n' && c != '\0') ; if (c == '\n') lineno++; else if (! isspace(c)) break; } return LEX_OR; } yylval.nodetypeval = Node_illegal; return c; } if (c != '_' && ! isalpha(c)) { yyerror("Invalid char '%c' in expression\n", c); return ERROR; } /* it's some type of name-type-thing. Find its length */ for (namelen = 0; is_identchar(tokstart[namelen]); namelen++) /* null */ ; emalloc(tokkey, char *, namelen+1, "yylex"); memcpy(tokkey, tokstart, namelen); tokkey[namelen] = '\0'; /* See if it is a special token. */ low = 0; high = (sizeof (tokentab) / sizeof (tokentab[0])) - 1; while (low <= high) { int i, c; mid = (low + high) / 2; c = *tokstart - tokentab[mid].operator[0]; i = c ? c : strcmp (tokkey, tokentab[mid].operator); if (i < 0) { /* token < mid */ high = mid - 1; } else if (i > 0) { /* token > mid */ low = mid + 1; } else { lexptr = tokstart + namelen; if (strict && tokentab[mid].nostrict) break; if (tokentab[mid].class == LEX_BUILTIN || tokentab[mid].class == LEX_LENGTH) yylval.ptrval = tokentab[mid].ptr; else yylval.nodetypeval = tokentab[mid].value; return tokentab[mid].class; } } /* It's a name. See how long it is. */ yylval.sval = tokkey; lexptr = tokstart + namelen; if (*lexptr == '(') return FUNC_CALL; else return NAME; } #ifndef DEFPATH #ifdef MSDOS #define DEFPATH "." #define ENVSEP ';' #else #define DEFPATH ".:/usr/lib/awk:/usr/local/lib/awk" #define ENVSEP ':' #endif #endif static FILE * pathopen (file) char *file; { static char *savepath = DEFPATH; static int first = 1; char *awkpath, *cp; char trypath[BUFSIZ]; FILE *fp; #ifdef DEBUG extern int debugging; #endif int fd; if (strcmp (file, "-") == 0) return (stdin); if (strict) return (fopen (file, "r")); if (first) { first = 0; if ((awkpath = getenv ("AWKPATH")) != NULL && *awkpath) savepath = awkpath; /* used for restarting */ } awkpath = savepath; /* some kind of path name, no search */ #ifndef MSDOS if (strchr (file, '/') != NULL) #else if (strchr (file, '/') != NULL || strchr (file, '\\') != NULL || strchr (file, ':') != NULL) #endif return ( (fd = devopen (file, "r")) >= 0 ? fdopen(fd, "r") : NULL); do { trypath[0] = '\0'; /* this should take into account limits on size of trypath */ for (cp = trypath; *awkpath && *awkpath != ENVSEP; ) *cp++ = *awkpath++; if (cp != trypath) { /* nun-null element in path */ *cp++ = '/'; strcpy (cp, file); } else strcpy (trypath, file); #ifdef DEBUG if (debugging) fprintf(stderr, "trying: %s\n", trypath); #endif if ((fd = devopen (trypath, "r")) >= 0 && (fp = fdopen(fd, "r")) != NULL) return (fp); /* no luck, keep going */ if(*awkpath == ENVSEP && awkpath[1] != '\0') awkpath++; /* skip colon */ } while (*awkpath); #ifdef MSDOS /* * Under DOS (and probably elsewhere) you might have one of the awk * paths defined, WITHOUT the current working directory in it. * Therefore you should try to open the file in the current directory. */ return ( (fd = devopen(file, "r")) >= 0 ? fdopen(fd, "r") : NULL); #else return (NULL); #endif } static NODE * node_common(op) NODETYPE op; { register NODE *r; extern int numfiles; extern int tempsource; extern char **sourcefile; r = newnode(op); r->source_line = lineno; if (numfiles > -1 && ! tempsource) r->source_file = sourcefile[curinfile]; else r->source_file = NULL; return r; } /* * This allocates a node with defined lnode and rnode. * This should only be used by yyparse+co while reading in the program */ NODE * node(left, op, right) NODE *left, *right; NODETYPE op; { register NODE *r; r = node_common(op); r->lnode = left; r->rnode = right; return r; } /* * This allocates a node with defined subnode and proc * Otherwise like node() */ static NODE * snode(subn, op, procp) NODETYPE op; NODE *(*procp) (); NODE *subn; { register NODE *r; r = node_common(op); r->subnode = subn; r->proc = procp; return r; } /* * This allocates a Node_line_range node with defined condpair and * zeroes the trigger word to avoid the temptation of assuming that calling * 'node( foo, Node_line_range, 0)' will properly initialize 'triggered'. */ /* Otherwise like node() */ static NODE * mkrangenode(cpair) NODE *cpair; { register NODE *r; r = newnode(Node_line_range); r->condpair = cpair; r->triggered = 0; return r; } /* Build a for loop */ static NODE * make_for_loop(init, cond, incr) NODE *init, *cond, *incr; { register FOR_LOOP_HEADER *r; NODE *n; emalloc(r, FOR_LOOP_HEADER *, sizeof(FOR_LOOP_HEADER), "make_for_loop"); n = newnode(Node_illegal); r->init = init; r->cond = cond; r->incr = incr; n->sub.nodep.r.hd = r; return n; } /* * Install a name in the hash table specified, even if it is already there. * Name stops with first non alphanumeric. Caller must check against * redefinition if that is desired. */ NODE * install(table, name, value) NODE **table; char *name; NODE *value; { register NODE *hp; register int len, bucket; register char *p; len = 0; p = name; while (is_identchar(*p)) p++; len = p - name; hp = newnode(Node_hashnode); bucket = hashf(name, len, HASHSIZE); hp->hnext = table[bucket]; table[bucket] = hp; hp->hlength = len; hp->hvalue = value; emalloc(hp->hname, char *, len + 1, "install"); memcpy(hp->hname, name, len); hp->hname[len] = '\0'; return hp->hvalue; } /* * find the most recent hash node for name name (ending with first * non-identifier char) installed by install */ NODE * lookup(table, name) NODE **table; char *name; { register char *bp; register NODE *bucket; register int len; for (bp = name; is_identchar(*bp); bp++) ; len = bp - name; bucket = table[hashf(name, len, HASHSIZE)]; while (bucket) { if (bucket->hlength == len && STREQN(bucket->hname, name, len)) return bucket->hvalue; bucket = bucket->hnext; } return NULL; } #define HASHSTEP(old, c) ((old << 1) + c) #define MAKE_POS(v) (v & ~0x80000000) /* make number positive */ /* * return hash function on name. */ static int hashf(name, len, hashsize) register char *name; register int len; int hashsize; { register int r = 0; while (len--) r = HASHSTEP(r, *name++); r = MAKE_POS(r) % hashsize; return r; } /* * Add new to the rightmost branch of LIST. This uses n^2 time, so we make * a simple attempt at optimizing it. */ static NODE * append_right(list, new) NODE *list, *new; { register NODE *oldlist; static NODE *savefront = NULL, *savetail = NULL; oldlist = list; if (savefront == oldlist) { savetail = savetail->rnode = new; return oldlist; } else savefront = oldlist; while (list->rnode != NULL) list = list->rnode; savetail = list->rnode = new; return oldlist; } /* * check if name is already installed; if so, it had better have Null value, * in which case def is added as the value. Otherwise, install name with def * as value. */ static void func_install(params, def) NODE *params; NODE *def; { NODE *r; pop_params(params->rnode); pop_var(params, 0); r = lookup(variables, params->param); if (r != NULL) { fatal("function name `%s' previously defined", params->param); } else (void) install(variables, params->param, node(params, Node_func, def)); } static void pop_var(np, freeit) NODE *np; int freeit; { register char *bp; register NODE *bucket, **save; register int len; char *name; name = np->param; for (bp = name; is_identchar(*bp); bp++) ; len = bp - name; save = &(variables[hashf(name, len, HASHSIZE)]); for (bucket = *save; bucket; bucket = bucket->hnext) { if (len == bucket->hlength && STREQN(bucket->hname, name, len)) { *save = bucket->hnext; freenode(bucket); free(bucket->hname); if (freeit) free(np->param); return; } save = &(bucket->hnext); } } static void pop_params(params) NODE *params; { register NODE *np; for (np = params; np != NULL; np = np->rnode) pop_var(np, 1); } static NODE * make_param(name) char *name; { NODE *r; r = newnode(Node_param_list); r->param = name; r->rnode = NULL; r->param_cnt = param_counter++; return (install(variables, name, r)); } /* Name points to a variable name. Make sure its in the symbol table */ NODE * variable(name) char *name; { register NODE *r; if ((r = lookup(variables, name)) == NULL) r = install(variables, name, node(Nnull_string, Node_var, (NODE *) NULL)); return r; } gawk-2.11/main.c 644 11660 0 30463 4527633610 11672 0ustar hackwheel/* * main.c -- Expression tree constructors and main program for gawk. */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" #include "patchlevel.h" #include extern int yyparse(); extern void do_input(); extern int close_io(); extern void init_fields(); extern int getopt(); extern int re_set_syntax(); extern NODE *node(); static void usage(); static void set_fs(); static void init_vars(); static void init_args(); static NODE *spc_var(); static void pre_assign(); static void copyleft(); /* These nodes store all the special variables AWK uses */ NODE *FS_node, *NF_node, *RS_node, *NR_node; NODE *FILENAME_node, *OFS_node, *ORS_node, *OFMT_node; NODE *FNR_node, *RLENGTH_node, *RSTART_node, *SUBSEP_node; NODE *ENVIRON_node, *IGNORECASE_node; NODE *ARGC_node, *ARGV_node; /* * The parse tree and field nodes are stored here. Parse_end is a dummy item * used to free up unneeded fields without freeing the program being run */ int errcount = 0; /* error counter, used by yyerror() */ /* The global null string */ NODE *Nnull_string; /* The name the program was invoked under, for error messages */ char *myname; /* A block of AWK code to be run before running the program */ NODE *begin_block = 0; /* A block of AWK code to be run after the last input file */ NODE *end_block = 0; int exiting = 0; /* Was an "exit" statement executed? */ int exit_val = 0; /* optional exit value */ #ifdef DEBUG /* non-zero means in debugging is enabled. Probably not very useful */ int debugging = 0; extern int yydebug; #endif int tempsource = 0; /* source is in a temp file */ char **sourcefile = NULL; /* source file name(s) */ int numfiles = -1; /* how many source files */ int strict = 0; /* turn off gnu extensions */ int output_is_tty = 0; /* control flushing of output */ NODE *expression_value; /* * for strict to work, legal options must be first * * Unfortunately, -a and -e are orthogonal to -c. */ #define EXTENSIONS 8 /* where to clear */ #ifdef DEBUG char awk_opts[] = "F:f:v:caeCVdD"; #else char awk_opts[] = "F:f:v:caeCV"; #endif int main(argc, argv) int argc; char **argv; { #ifdef DEBUG /* Print out the parse tree. For debugging */ register int dotree = 0; #endif extern char *version_string; FILE *fp; int c; extern int opterr, optind; extern char *optarg; extern char *strrchr(); extern char *tmpnam(); extern SIGTYPE catchsig(); int i; int nostalgia; #ifdef somtime_in_the_future int regex_mode = RE_SYNTAX_POSIX_EGREP; #else int regex_mode = RE_SYNTAX_AWK; #endif (void) signal(SIGFPE, catchsig); (void) signal(SIGSEGV, catchsig); if (strncmp(version_string, "@(#)", 4) == 0) version_string += 4; myname = strrchr(argv[0], '/'); if (myname == NULL) myname = argv[0]; else myname++; if (argc < 2) usage(); /* initialize the null string */ Nnull_string = make_string("", 0); Nnull_string->numbr = 0.0; Nnull_string->type = Node_val; Nnull_string->flags = (PERM|STR|NUM|NUMERIC); /* Set up the special variables */ /* * Note that this must be done BEFORE arg parsing else -F * breaks horribly */ init_vars(); /* worst case */ emalloc(sourcefile, char **, argc * sizeof(char *), "main"); #ifdef STRICT /* strict new awk compatibility */ strict = 1; awk_opts[EXTENSIONS] = '\0'; #endif #ifndef STRICT /* undocumented feature, inspired by nostalgia, and a T-shirt */ nostalgia = 0; for (i = 1; i < argc && argv[i][0] == '-'; i++) { if (argv[i][1] == '-') /* -- */ break; else if (argv[i][1] == 'c') { /* compatibility mode */ nostalgia = 0; break; } else if (STREQ(&argv[i][1], "nostalgia")) nostalgia = 1; /* keep looping, in case -c after -nostalgia */ } if (nostalgia) { fprintf (stderr, "awk: bailing out near line 1\n"); abort(); } #endif while ((c = getopt (argc, argv, awk_opts)) != EOF) { switch (c) { #ifdef DEBUG case 'd': debugging++; dotree++; break; case 'D': debugging++; yydebug = 2; break; #endif #ifndef STRICT case 'c': strict = 1; break; #endif case 'F': set_fs(optarg); break; case 'f': /* * a la MKS awk, allow multiple -f options. * this makes function libraries real easy. * most of the magic is in the scanner. */ sourcefile[++numfiles] = optarg; break; case 'v': pre_assign(optarg); break; case 'V': fprintf(stderr, "%s, patchlevel %d\n", version_string, PATCHLEVEL); break; case 'C': copyleft(); break; case 'a': /* use old fashioned awk regexps */ regex_mode = RE_SYNTAX_AWK; break; case 'e': /* use egrep style regexps, per Posix */ regex_mode = RE_SYNTAX_POSIX_EGREP; break; case '?': default: /* getopt will print a message for us */ /* S5R4 awk ignores bad options and keeps going */ break; } } /* Tell the regex routines how they should work. . . */ (void) re_set_syntax(regex_mode); #ifdef DEBUG setbuf(stdout, (char *) NULL); /* make debugging easier */ #endif if (isatty(fileno(stdout))) output_is_tty = 1; /* No -f option, use next arg */ /* write to temp file and save sourcefile name */ if (numfiles == -1) { int i; if (optind > argc - 1) /* no args left */ usage(); numfiles++; i = strlen (argv[optind]); if (i == 0) { /* sanity check */ fprintf(stderr, "%s: empty program text\n", myname); usage(); /* NOTREACHED */ } sourcefile[0] = tmpnam((char *) NULL); if ((fp = fopen (sourcefile[0], "w")) == NULL) fatal("could not save source prog in temp file (%s)", strerror(errno)); if (fwrite (argv[optind], 1, i, fp) == 0) fatal( "could not write source program to temp file (%s)", strerror(errno)); if (argv[optind][i-1] != '\n') putc ('\n', fp); (void) fclose (fp); tempsource++; optind++; } init_args(optind, argc, myname, argv); /* Read in the program */ if (yyparse() || errcount) exit(1); #ifdef DEBUG if (dotree) print_parse_tree(expression_value); #endif /* Set up the field variables */ init_fields(); if (begin_block) (void) interpret(begin_block); if (!exiting && (expression_value || end_block)) do_input(); if (end_block) (void) interpret(end_block); if (close_io() != 0 && exit_val == 0) exit_val = 1; exit(exit_val); /* NOTREACHED */ return exit_val; } static void usage() { char *opt1 = " -f progfile [--]"; char *opt2 = " [--] 'program'"; #ifdef STRICT char *regops = " [-ae] [-F fs] [-v var=val]" #else char *regops = " [-aecCV] [-F fs] [-v var=val]"; #endif fprintf(stderr, "usage: %s%s%s file ...\n %s%s%s file ...\n", myname, regops, opt1, myname, regops, opt2); exit(11); } /* Generate compiled regular expressions */ struct re_pattern_buffer * make_regexp(s, ignorecase) NODE *s; int ignorecase; { struct re_pattern_buffer *rp; char *err; emalloc(rp, struct re_pattern_buffer *, sizeof(*rp), "make_regexp"); memset((char *) rp, 0, sizeof(*rp)); emalloc(rp->buffer, char *, 16, "make_regexp"); rp->allocated = 16; emalloc(rp->fastmap, char *, 256, "make_regexp"); if (! strict && ignorecase) rp->translate = casetable; else rp->translate = NULL; if ((err = re_compile_pattern(s->stptr, s->stlen, rp)) != NULL) fatal("%s: /%s/", err, s->stptr); free_temp(s); return rp; } struct re_pattern_buffer * mk_re_parse(s, ignorecase) char *s; int ignorecase; { char *src; register char *dest; register int c; int in_brack = 0; for (dest = src = s; *src != '\0';) { if (*src == '\\') { c = *++src; switch (c) { case '/': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case 'x': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': c = parse_escape(&src); if (c < 0) cant_happen(); *dest++ = (char)c; break; default: *dest++ = '\\'; *dest++ = (char)c; src++; break; } } else if (*src == '/' && ! in_brack) break; else { if (*src == '[') in_brack = 1; else if (*src == ']') in_brack = 0; *dest++ = *src++; } } return make_regexp(tmp_string(s, dest-s), ignorecase); } static void copyleft () { extern char *version_string; char *cp; static char blurb[] = "Copyright (C) 1989, Free Software Foundation.\n\ GNU Awk comes with ABSOLUTELY NO WARRANTY. This is free software, and\n\ you are welcome to distribute it under the terms of the GNU General\n\ Public License, which covers both the warranty information and the\n\ terms for redistribution.\n\n\ You should have received a copy of the GNU General Public License along\n\ with this program; if not, write to the Free Software Foundation, Inc.,\n\ 675 Mass Ave, Cambridge, MA 02139, USA.\n"; fprintf (stderr, "%s, patchlevel %d\n", version_string, PATCHLEVEL); fputs(blurb, stderr); fflush(stderr); } static void set_fs(str) char *str; { register NODE **tmp; tmp = get_lhs(FS_node, 0); /* * Only if in full compatibility mode check for the stupid special * case so -F\t works as documented in awk even though the shell * hands us -Ft. Bleah! */ if (strict && str[0] == 't' && str[1] == '\0') str[0] = '\t'; *tmp = make_string(str, 1); do_deref(); } static void init_args(argc0, argc, argv0, argv) int argc0, argc; char *argv0; char **argv; { int i, j; NODE **aptr; ARGV_node = spc_var("ARGV", Nnull_string); aptr = assoc_lookup(ARGV_node, tmp_number(0.0)); *aptr = make_string(argv0, strlen(argv0)); for (i = argc0, j = 1; i < argc; i++) { aptr = assoc_lookup(ARGV_node, tmp_number((AWKNUM) j)); *aptr = make_string(argv[i], strlen(argv[i])); j++; } ARGC_node = spc_var("ARGC", make_number((AWKNUM) j)); } /* * Set all the special variables to their initial values. */ static void init_vars() { extern char **environ; char *var, *val; NODE **aptr; int i; FS_node = spc_var("FS", make_string(" ", 1)); NF_node = spc_var("NF", make_number(-1.0)); RS_node = spc_var("RS", make_string("\n", 1)); NR_node = spc_var("NR", make_number(0.0)); FNR_node = spc_var("FNR", make_number(0.0)); FILENAME_node = spc_var("FILENAME", make_string("-", 1)); OFS_node = spc_var("OFS", make_string(" ", 1)); ORS_node = spc_var("ORS", make_string("\n", 1)); OFMT_node = spc_var("OFMT", make_string("%.6g", 4)); RLENGTH_node = spc_var("RLENGTH", make_number(0.0)); RSTART_node = spc_var("RSTART", make_number(0.0)); SUBSEP_node = spc_var("SUBSEP", make_string("\034", 1)); IGNORECASE_node = spc_var("IGNORECASE", make_number(0.0)); ENVIRON_node = spc_var("ENVIRON", Nnull_string); for (i = 0; environ[i]; i++) { static char nullstr[] = ""; var = environ[i]; val = strchr(var, '='); if (val) *val++ = '\0'; else val = nullstr; aptr = assoc_lookup(ENVIRON_node, tmp_string(var, strlen (var))); *aptr = make_string(val, strlen (val)); /* restore '=' so that system() gets a valid environment */ if (val != nullstr) *--val = '='; } } /* Create a special variable */ static NODE * spc_var(name, value) char *name; NODE *value; { register NODE *r; if ((r = lookup(variables, name)) == NULL) r = install(variables, name, node(value, Node_var, (NODE *) NULL)); return r; } static void pre_assign(v) char *v; { char *cp; cp = strchr(v, '='); if (cp != NULL) { *cp++ = '\0'; variable(v)->var_value = make_string(cp, strlen(cp)); } else { fprintf (stderr, "%s: '%s' argument to -v not in 'var=value' form\n", myname, v); usage(); } } SIGTYPE catchsig(sig, code) int sig, code; { #ifdef lint code = 0; sig = code; code = sig; #endif if (sig == SIGFPE) { fatal("floating point exception"); } else if (sig == SIGSEGV) { msg("fatal error: segmentation fault"); /* fatal won't abort() if not compiled for debugging */ abort(); } else cant_happen(); /* NOTREACHED */ } gawk-2.11/eval.c 644 11660 0 71556 4527633571 11713 0ustar hackwheel/* * eval.c - gawk parse tree interpreter */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" extern void do_print(); extern void do_printf(); extern NODE *do_match(); extern NODE *do_sub(); extern NODE *do_getline(); extern NODE *concat_exp(); extern int in_array(); extern void do_delete(); extern double pow(); static int eval_condition(); static NODE *op_assign(); static NODE *func_call(); static NODE *match_op(); NODE *_t; /* used as a temporary in macros */ #ifdef MSDOS double _msc51bug; /* to get around a bug in MSC 5.1 */ #endif NODE *ret_node; /* More of that debugging stuff */ #ifdef DEBUG #define DBG_P(X) print_debug X #else #define DBG_P(X) #endif /* Macros and variables to save and restore function and loop bindings */ /* * the val variable allows return/continue/break-out-of-context to be * caught and diagnosed */ #define PUSH_BINDING(stack, x, val) (memcpy ((char *)(stack), (char *)(x), sizeof (jmp_buf)), val++) #define RESTORE_BINDING(stack, x, val) (memcpy ((char *)(x), (char *)(stack), sizeof (jmp_buf)), val--) static jmp_buf loop_tag; /* always the current binding */ static int loop_tag_valid = 0; /* nonzero when loop_tag valid */ static int func_tag_valid = 0; static jmp_buf func_tag; extern int exiting, exit_val; /* * This table is used by the regexp routines to do case independant * matching. Basically, every ascii character maps to itself, except * uppercase letters map to lower case ones. This table has 256 * entries, which may be overkill. Note also that if the system this * is compiled on doesn't use 7-bit ascii, casetable[] should not be * defined to the linker, so gawk should not load. * * Do NOT make this array static, it is used in several spots, not * just in this file. */ #if 'a' == 97 /* it's ascii */ char casetable[] = { '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', /* ' ' '!' '"' '#' '$' '%' '&' ''' */ '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', /* '(' ')' '*' '+' ',' '-' '.' '/' */ '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', /* '0' '1' '2' '3' '4' '5' '6' '7' */ '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', /* '8' '9' ':' ';' '<' '=' '>' '?' */ '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */ '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */ '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */ '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */ '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */ '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */ '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */ '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', /* 'x' 'y' 'z' '{' '|' '}' '~' */ '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247', '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257', '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267', '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307', '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317', '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327', '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377', }; #else #include "You lose. You will need a translation table for your character set." #endif /* * Tree is a bunch of rules to run. Returns zero if it hit an exit() * statement */ int interpret(tree) NODE *tree; { volatile jmp_buf loop_tag_stack; /* shallow binding stack for loop_tag */ static jmp_buf rule_tag;/* tag the rule currently being run, for NEXT * and EXIT statements. It is static because * there are no nested rules */ register NODE *t = NULL;/* temporary */ volatile NODE **lhs; /* lhs == Left Hand Side for assigns, etc */ volatile struct search *l; /* For array_for */ volatile NODE *stable_tree; if (tree == NULL) return 1; sourceline = tree->source_line; source = tree->source_file; switch (tree->type) { case Node_rule_list: for (t = tree; t != NULL; t = t->rnode) { tree = t->lnode; /* FALL THROUGH */ case Node_rule_node: sourceline = tree->source_line; source = tree->source_file; switch (setjmp(rule_tag)) { case 0: /* normal non-jump */ /* test pattern, if any */ if (tree->lnode == NULL || eval_condition(tree->lnode)) { DBG_P(("Found a rule", tree->rnode)); if (tree->rnode == NULL) { /* * special case: pattern with * no action is equivalent to * an action of {print} */ NODE printnode; printnode.type = Node_K_print; printnode.lnode = NULL; printnode.rnode = NULL; do_print(&printnode); } else if (tree->rnode->type == Node_illegal) { /* * An empty statement * (``{ }'') is different * from a missing statement. * A missing statement is * equal to ``{ print }'' as * above, but an empty * statement is as in C, do * nothing. */ } else (void) interpret(tree->rnode); } break; case TAG_CONTINUE: /* NEXT statement */ return 1; case TAG_BREAK: return 0; default: cant_happen(); } if (t == NULL) break; } break; case Node_statement_list: for (t = tree; t != NULL; t = t->rnode) { DBG_P(("Statements", t->lnode)); (void) interpret(t->lnode); } break; case Node_K_if: DBG_P(("IF", tree->lnode)); if (eval_condition(tree->lnode)) { DBG_P(("True", tree->rnode->lnode)); (void) interpret(tree->rnode->lnode); } else { DBG_P(("False", tree->rnode->rnode)); (void) interpret(tree->rnode->rnode); } break; case Node_K_while: PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); DBG_P(("WHILE", tree->lnode)); stable_tree = tree; while (eval_condition(stable_tree->lnode)) { switch (setjmp(loop_tag)) { case 0: /* normal non-jump */ DBG_P(("DO", stable_tree->rnode)); (void) interpret(stable_tree->rnode); break; case TAG_CONTINUE: /* continue statement */ break; case TAG_BREAK: /* break statement */ RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); return 1; default: cant_happen(); } } RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); break; case Node_K_do: PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); stable_tree = tree; do { switch (setjmp(loop_tag)) { case 0: /* normal non-jump */ DBG_P(("DO", stable_tree->rnode)); (void) interpret(stable_tree->rnode); break; case TAG_CONTINUE: /* continue statement */ break; case TAG_BREAK: /* break statement */ RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); return 1; default: cant_happen(); } DBG_P(("WHILE", stable_tree->lnode)); } while (eval_condition(stable_tree->lnode)); RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); break; case Node_K_for: PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); DBG_P(("FOR", tree->forloop->init)); (void) interpret(tree->forloop->init); DBG_P(("FOR.WHILE", tree->forloop->cond)); stable_tree = tree; while (eval_condition(stable_tree->forloop->cond)) { switch (setjmp(loop_tag)) { case 0: /* normal non-jump */ DBG_P(("FOR.DO", stable_tree->lnode)); (void) interpret(stable_tree->lnode); /* fall through */ case TAG_CONTINUE: /* continue statement */ DBG_P(("FOR.INCR", stable_tree->forloop->incr)); (void) interpret(stable_tree->forloop->incr); break; case TAG_BREAK: /* break statement */ RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); return 1; default: cant_happen(); } } RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); break; case Node_K_arrayfor: #define hakvar forloop->init #define arrvar forloop->incr PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); DBG_P(("AFOR.VAR", tree->hakvar)); lhs = (volatile NODE **) get_lhs(tree->hakvar, 1); t = tree->arrvar; if (t->type == Node_param_list) t = stack_ptr[t->param_cnt]; stable_tree = tree; for (l = assoc_scan(t); l; l = assoc_next((struct search *)l)) { deref = *((NODE **) lhs); do_deref(); *lhs = dupnode(l->retval); if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); DBG_P(("AFOR.NEXTIS", *lhs)); switch (setjmp(loop_tag)) { case 0: DBG_P(("AFOR.DO", stable_tree->lnode)); (void) interpret(stable_tree->lnode); case TAG_CONTINUE: break; case TAG_BREAK: RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); field_num = -1; return 1; default: cant_happen(); } } field_num = -1; RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid); break; case Node_K_break: DBG_P(("BREAK", NULL)); if (loop_tag_valid == 0) fatal("unexpected break"); longjmp(loop_tag, TAG_BREAK); break; case Node_K_continue: DBG_P(("CONTINUE", NULL)); if (loop_tag_valid == 0) fatal("unexpected continue"); longjmp(loop_tag, TAG_CONTINUE); break; case Node_K_print: DBG_P(("PRINT", tree)); do_print(tree); break; case Node_K_printf: DBG_P(("PRINTF", tree)); do_printf(tree); break; case Node_K_next: DBG_P(("NEXT", NULL)); longjmp(rule_tag, TAG_CONTINUE); break; case Node_K_exit: /* * In A,K,&W, p. 49, it says that an exit statement "... * causes the program to behave as if the end of input had * occurred; no more input is read, and the END actions, if * any are executed." This implies that the rest of the rules * are not done. So we immediately break out of the main loop. */ DBG_P(("EXIT", NULL)); exiting = 1; if (tree) { t = tree_eval(tree->lnode); exit_val = (int) force_number(t); } free_temp(t); longjmp(rule_tag, TAG_BREAK); break; case Node_K_return: DBG_P(("RETURN", NULL)); t = tree_eval(tree->lnode); ret_node = dupnode(t); free_temp(t); longjmp(func_tag, TAG_RETURN); break; default: /* * Appears to be an expression statement. Throw away the * value. */ DBG_P(("E", NULL)); t = tree_eval(tree); free_temp(t); break; } return 1; } /* evaluate a subtree, allocating strings on a temporary stack. */ NODE * r_tree_eval(tree) NODE *tree; { register NODE *r, *t1, *t2; /* return value & temporary subtrees */ int i; register NODE **lhs; int di; AWKNUM x, x2; long lx; extern NODE **fields_arr; source = tree->source_file; sourceline = tree->source_line; switch (tree->type) { case Node_and: DBG_P(("AND", tree)); return tmp_number((AWKNUM) (eval_condition(tree->lnode) && eval_condition(tree->rnode))); case Node_or: DBG_P(("OR", tree)); return tmp_number((AWKNUM) (eval_condition(tree->lnode) || eval_condition(tree->rnode))); case Node_not: DBG_P(("NOT", tree)); return tmp_number((AWKNUM) ! eval_condition(tree->lnode)); /* Builtins */ case Node_builtin: DBG_P(("builtin", tree)); return ((*tree->proc) (tree->subnode)); case Node_K_getline: DBG_P(("GETLINE", tree)); return (do_getline(tree)); case Node_in_array: DBG_P(("IN_ARRAY", tree)); return tmp_number((AWKNUM) in_array(tree->lnode, tree->rnode)); case Node_func_call: DBG_P(("func_call", tree)); return func_call(tree->rnode, tree->lnode); case Node_K_delete: DBG_P(("DELETE", tree)); do_delete(tree->lnode, tree->rnode); return Nnull_string; /* unary operations */ case Node_var: case Node_var_array: case Node_param_list: case Node_subscript: case Node_field_spec: DBG_P(("var_type ref", tree)); lhs = get_lhs(tree, 0); field_num = -1; deref = 0; return *lhs; case Node_unary_minus: DBG_P(("UMINUS", tree)); t1 = tree_eval(tree->subnode); x = -force_number(t1); free_temp(t1); return tmp_number(x); case Node_cond_exp: DBG_P(("?:", tree)); if (eval_condition(tree->lnode)) { DBG_P(("True", tree->rnode->lnode)); return tree_eval(tree->rnode->lnode); } DBG_P(("False", tree->rnode->rnode)); return tree_eval(tree->rnode->rnode); case Node_match: case Node_nomatch: case Node_regex: DBG_P(("[no]match_op", tree)); return match_op(tree); case Node_func: fatal("function `%s' called with space between name and (,\n%s", tree->lnode->param, "or used in other expression context"); /* assignments */ case Node_assign: DBG_P(("ASSIGN", tree)); r = tree_eval(tree->rnode); lhs = get_lhs(tree->lnode, 1); *lhs = dupnode(r); free_temp(r); do_deref(); if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); field_num = -1; return *lhs; /* other assignment types are easier because they are numeric */ case Node_preincrement: case Node_predecrement: case Node_postincrement: case Node_postdecrement: case Node_assign_exp: case Node_assign_times: case Node_assign_quotient: case Node_assign_mod: case Node_assign_plus: case Node_assign_minus: return op_assign(tree); default: break; /* handled below */ } /* evaluate subtrees in order to do binary operation, then keep going */ t1 = tree_eval(tree->lnode); t2 = tree_eval(tree->rnode); switch (tree->type) { case Node_concat: DBG_P(("CONCAT", tree)); t1 = force_string(t1); t2 = force_string(t2); r = newnode(Node_val); r->flags |= (STR|TEMP); r->stlen = t1->stlen + t2->stlen; r->stref = 1; emalloc(r->stptr, char *, r->stlen + 1, "tree_eval"); memcpy(r->stptr, t1->stptr, t1->stlen); memcpy(r->stptr + t1->stlen, t2->stptr, t2->stlen + 1); free_temp(t1); free_temp(t2); return r; case Node_geq: case Node_leq: case Node_greater: case Node_less: case Node_notequal: case Node_equal: di = cmp_nodes(t1, t2); free_temp(t1); free_temp(t2); switch (tree->type) { case Node_equal: DBG_P(("EQUAL", tree)); return tmp_number((AWKNUM) (di == 0)); case Node_notequal: DBG_P(("NOT_EQUAL", tree)); return tmp_number((AWKNUM) (di != 0)); case Node_less: DBG_P(("LESS_THAN", tree)); return tmp_number((AWKNUM) (di < 0)); case Node_greater: DBG_P(("GREATER_THAN", tree)); return tmp_number((AWKNUM) (di > 0)); case Node_leq: DBG_P(("LESS_THAN_EQUAL", tree)); return tmp_number((AWKNUM) (di <= 0)); case Node_geq: DBG_P(("GREATER_THAN_EQUAL", tree)); return tmp_number((AWKNUM) (di >= 0)); default: cant_happen(); } break; default: break; /* handled below */ } (void) force_number(t1); (void) force_number(t2); switch (tree->type) { case Node_exp: DBG_P(("EXPONENT", tree)); if ((lx = t2->numbr) == t2->numbr) { /* integer exponent */ if (lx == 0) x = 1; else if (lx == 1) x = t1->numbr; else { /* doing it this way should be more precise */ for (x = x2 = t1->numbr; --lx; ) x *= x2; } } else x = pow((double) t1->numbr, (double) t2->numbr); free_temp(t1); free_temp(t2); return tmp_number(x); case Node_times: DBG_P(("MULT", tree)); x = t1->numbr * t2->numbr; free_temp(t1); free_temp(t2); return tmp_number(x); case Node_quotient: DBG_P(("DIVIDE", tree)); x = t2->numbr; free_temp(t2); if (x == (AWKNUM) 0) fatal("division by zero attempted"); /* NOTREACHED */ else { x = t1->numbr / x; free_temp(t1); return tmp_number(x); } case Node_mod: DBG_P(("MODULUS", tree)); x = t2->numbr; free_temp(t2); if (x == (AWKNUM) 0) fatal("division by zero attempted in mod"); /* NOTREACHED */ lx = t1->numbr / x; /* assignment to long truncates */ x2 = lx * x; x = t1->numbr - x2; free_temp(t1); return tmp_number(x); case Node_plus: DBG_P(("PLUS", tree)); x = t1->numbr + t2->numbr; free_temp(t1); free_temp(t2); return tmp_number(x); case Node_minus: DBG_P(("MINUS", tree)); x = t1->numbr - t2->numbr; free_temp(t1); free_temp(t2); return tmp_number(x); default: fatal("illegal type (%d) in tree_eval", tree->type); } return 0; } /* * This makes numeric operations slightly more efficient. Just change the * value of a numeric node, if possible */ void assign_number(ptr, value) NODE **ptr; AWKNUM value; { extern NODE *deref; register NODE *n = *ptr; #ifdef DEBUG if (n->type != Node_val) cant_happen(); #endif if (n == Nnull_string) { *ptr = make_number(value); deref = 0; return; } if (n->stref > 1) { *ptr = make_number(value); return; } if ((n->flags & STR) && (n->flags & (MALLOC|TEMP))) free(n->stptr); n->numbr = value; n->flags |= (NUM|NUMERIC); n->flags &= ~STR; n->stref = 0; deref = 0; } /* Is TREE true or false? Returns 0==false, non-zero==true */ static int eval_condition(tree) NODE *tree; { register NODE *t1; int ret; if (tree == NULL) /* Null trees are the easiest kinds */ return 1; if (tree->type == Node_line_range) { /* * Node_line_range is kind of like Node_match, EXCEPT: the * lnode field (more properly, the condpair field) is a node * of a Node_cond_pair; whether we evaluate the lnode of that * node or the rnode depends on the triggered word. More * precisely: if we are not yet triggered, we tree_eval the * lnode; if that returns true, we set the triggered word. * If we are triggered (not ELSE IF, note), we tree_eval the * rnode, clear triggered if it succeeds, and perform our * action (regardless of success or failure). We want to be * able to begin and end on a single input record, so this * isn't an ELSE IF, as noted above. */ if (!tree->triggered) if (!eval_condition(tree->condpair->lnode)) return 0; else tree->triggered = 1; /* Else we are triggered */ if (eval_condition(tree->condpair->rnode)) tree->triggered = 0; return 1; } /* * Could just be J.random expression. in which case, null and 0 are * false, anything else is true */ t1 = tree_eval(tree); if (t1->flags & NUMERIC) ret = t1->numbr != 0.0; else ret = t1->stlen != 0; free_temp(t1); return ret; } int cmp_nodes(t1, t2) NODE *t1, *t2; { AWKNUM d; AWKNUM d1; AWKNUM d2; int ret; int len1, len2; if (t1 == t2) return 0; d1 = force_number(t1); d2 = force_number(t2); if ((t1->flags & NUMERIC) && (t2->flags & NUMERIC)) { d = d1 - d2; if (d == 0.0) /* from profiling, this is most common */ return 0; if (d > 0.0) return 1; return -1; } t1 = force_string(t1); t2 = force_string(t2); len1 = t1->stlen; len2 = t2->stlen; if (len1 == 0) { if (len2 == 0) return 0; else return -1; } else if (len2 == 0) return 1; ret = memcmp(t1->stptr, t2->stptr, len1 <= len2 ? len1 : len2); if (ret == 0 && len1 != len2) return len1 < len2 ? -1: 1; return ret; } static NODE * op_assign(tree) NODE *tree; { AWKNUM rval, lval; NODE **lhs; AWKNUM t1, t2; long ltemp; NODE *tmp; lhs = get_lhs(tree->lnode, 1); lval = force_number(*lhs); switch(tree->type) { case Node_preincrement: case Node_predecrement: DBG_P(("+-X", tree)); assign_number(lhs, lval + (tree->type == Node_preincrement ? 1.0 : -1.0)); do_deref(); if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); field_num = -1; return *lhs; case Node_postincrement: case Node_postdecrement: DBG_P(("X+-", tree)); assign_number(lhs, lval + (tree->type == Node_postincrement ? 1.0 : -1.0)); do_deref(); if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); field_num = -1; return tmp_number(lval); default: break; /* handled below */ } tmp = tree_eval(tree->rnode); rval = force_number(tmp); free_temp(tmp); switch(tree->type) { case Node_assign_exp: DBG_P(("ASSIGN_exp", tree)); if ((ltemp = rval) == rval) { /* integer exponent */ if (ltemp == 0) assign_number(lhs, (AWKNUM) 1); else if (ltemp == 1) assign_number(lhs, lval); else { /* doing it this way should be more precise */ for (t1 = t2 = lval; --ltemp; ) t1 *= t2; assign_number(lhs, t1); } } else assign_number(lhs, (AWKNUM) pow((double) lval, (double) rval)); break; case Node_assign_times: DBG_P(("ASSIGN_times", tree)); assign_number(lhs, lval * rval); break; case Node_assign_quotient: DBG_P(("ASSIGN_quotient", tree)); if (rval == (AWKNUM) 0) fatal("division by zero attempted in /="); assign_number(lhs, lval / rval); break; case Node_assign_mod: DBG_P(("ASSIGN_mod", tree)); if (rval == (AWKNUM) 0) fatal("division by zero attempted in %="); ltemp = lval / rval; /* assignment to long truncates */ t1 = ltemp * rval; t2 = lval - t1; assign_number(lhs, t2); break; case Node_assign_plus: DBG_P(("ASSIGN_plus", tree)); assign_number(lhs, lval + rval); break; case Node_assign_minus: DBG_P(("ASSIGN_minus", tree)); assign_number(lhs, lval - rval); break; default: cant_happen(); } do_deref(); if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); field_num = -1; return *lhs; } NODE **stack_ptr; static NODE * func_call(name, arg_list) NODE *name; /* name is a Node_val giving function name */ NODE *arg_list; /* Node_expression_list of calling args. */ { register NODE *arg, *argp, *r; NODE *n, *f; volatile jmp_buf func_tag_stack; volatile jmp_buf loop_tag_stack; volatile int save_loop_tag_valid = 0; volatile NODE **save_stack, *save_ret_node; NODE **local_stack, **sp; int count; extern NODE *ret_node; /* * retrieve function definition node */ f = lookup(variables, name->stptr); if (!f || f->type != Node_func) fatal("function `%s' not defined", name->stptr); #ifdef FUNC_TRACE fprintf(stderr, "function %s called\n", name->stptr); #endif count = f->lnode->param_cnt; emalloc(local_stack, NODE **, count * sizeof(NODE *), "func_call"); sp = local_stack; /* * for each calling arg. add NODE * on stack */ for (argp = arg_list; count && argp != NULL; argp = argp->rnode) { arg = argp->lnode; r = newnode(Node_var); /* * call by reference for arrays; see below also */ if (arg->type == Node_param_list) arg = stack_ptr[arg->param_cnt]; if (arg->type == Node_var_array) *r = *arg; else { n = tree_eval(arg); r->lnode = dupnode(n); r->rnode = (NODE *) NULL; free_temp(n); } *sp++ = r; count--; } if (argp != NULL) /* left over calling args. */ warning( "function `%s' called with more arguments than declared", name->stptr); /* * add remaining params. on stack with null value */ while (count-- > 0) { r = newnode(Node_var); r->lnode = Nnull_string; r->rnode = (NODE *) NULL; *sp++ = r; } /* * Execute function body, saving context, as a return statement * will longjmp back here. * * Have to save and restore the loop_tag stuff so that a return * inside a loop in a function body doesn't scrog any loops going * on in the main program. We save the necessary info in variables * local to this function so that function nesting works OK. * We also only bother to save the loop stuff if we're in a loop * when the function is called. */ if (loop_tag_valid) { int junk = 0; save_loop_tag_valid = (volatile int) loop_tag_valid; PUSH_BINDING(loop_tag_stack, loop_tag, junk); loop_tag_valid = 0; } save_stack = (volatile NODE **) stack_ptr; stack_ptr = local_stack; PUSH_BINDING(func_tag_stack, func_tag, func_tag_valid); save_ret_node = (volatile NODE *) ret_node; ret_node = Nnull_string; /* default return value */ if (setjmp(func_tag) == 0) (void) interpret(f->rnode); r = ret_node; ret_node = (NODE *) save_ret_node; RESTORE_BINDING(func_tag_stack, func_tag, func_tag_valid); stack_ptr = (NODE **) save_stack; /* * here, we pop each parameter and check whether * it was an array. If so, and if the arg. passed in was * a simple variable, then the value should be copied back. * This achieves "call-by-reference" for arrays. */ sp = local_stack; count = f->lnode->param_cnt; for (argp = arg_list; count > 0 && argp != NULL; argp = argp->rnode) { arg = argp->lnode; n = *sp++; if (arg->type == Node_var && n->type == Node_var_array) { arg->var_array = n->var_array; arg->type = Node_var_array; } deref = n->lnode; do_deref(); freenode(n); count--; } while (count-- > 0) { n = *sp++; deref = n->lnode; do_deref(); freenode(n); } free((char *) local_stack); /* Restore the loop_tag stuff if necessary. */ if (save_loop_tag_valid) { int junk = 0; loop_tag_valid = (int) save_loop_tag_valid; RESTORE_BINDING(loop_tag_stack, loop_tag, junk); } if (!(r->flags & PERM)) r->flags |= TEMP; return r; } /* * This returns a POINTER to a node pointer. get_lhs(ptr) is the current * value of the var, or where to store the var's new value */ NODE ** get_lhs(ptr, assign) NODE *ptr; int assign; /* this is being called for the LHS of an assign. */ { register NODE **aptr; NODE *n; #ifdef DEBUG if (ptr == NULL) cant_happen(); #endif deref = NULL; field_num = -1; switch (ptr->type) { case Node_var: case Node_var_array: if (ptr == NF_node && (int) NF_node->var_value->numbr == -1) (void) get_field(HUGE-1, assign); /* parse record */ deref = ptr->var_value; #ifdef DEBUG if (deref->type != Node_val) cant_happen(); if (deref->flags == 0) cant_happen(); #endif return &(ptr->var_value); case Node_param_list: n = stack_ptr[ptr->param_cnt]; deref = n->var_value; #ifdef DEBUG if (deref->type != Node_val) cant_happen(); if (deref->flags == 0) cant_happen(); #endif return &(n->var_value); case Node_field_spec: n = tree_eval(ptr->lnode); field_num = (int) force_number(n); free_temp(n); if (field_num < 0) fatal("attempt to access field %d", field_num); aptr = get_field(field_num, assign); deref = *aptr; return aptr; case Node_subscript: n = ptr->lnode; if (n->type == Node_param_list) n = stack_ptr[n->param_cnt]; aptr = assoc_lookup(n, concat_exp(ptr->rnode)); deref = *aptr; #ifdef DEBUG if (deref->type != Node_val) cant_happen(); if (deref->flags == 0) cant_happen(); #endif return aptr; case Node_func: fatal ("`%s' is a function, assignment is not allowed", ptr->lnode->param); default: cant_happen(); } return 0; } static NODE * match_op(tree) NODE *tree; { NODE *t1; struct re_pattern_buffer *rp; int i; int match = 1; if (tree->type == Node_nomatch) match = 0; if (tree->type == Node_regex) t1 = WHOLELINE; else { if (tree->lnode) t1 = force_string(tree_eval(tree->lnode)); else t1 = WHOLELINE; tree = tree->rnode; } if (tree->type == Node_regex) { rp = tree->rereg; if (!strict && ((IGNORECASE_node->var_value->numbr != 0) ^ (tree->re_case != 0))) { /* recompile since case sensitivity differs */ rp = tree->rereg = mk_re_parse(tree->re_text, (IGNORECASE_node->var_value->numbr != 0)); tree->re_case = (IGNORECASE_node->var_value->numbr != 0); } } else { rp = make_regexp(force_string(tree_eval(tree)), (IGNORECASE_node->var_value->numbr != 0)); if (rp == NULL) cant_happen(); } i = re_search(rp, t1->stptr, t1->stlen, 0, t1->stlen, (struct re_registers *) NULL); i = (i == -1) ^ (match == 1); free_temp(t1); if (tree->type != Node_regex) { free(rp->buffer); free(rp->fastmap); free((char *) rp); } return tmp_number((AWKNUM) i); } gawk-2.11/builtin.c 644 11660 0 50263 4527633565 12425 0ustar hackwheel/* * builtin.c - Builtin functions and various utility procedures */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" extern void srandom(); extern char *initstate(); extern char *setstate(); extern long random(); extern NODE **fields_arr; static void get_one(); static void get_two(); static int get_three(); /* Builtin functions */ NODE * do_exp(tree) NODE *tree; { NODE *tmp; double d, res; double exp(); get_one(tree, &tmp); d = force_number(tmp); free_temp(tmp); errno = 0; res = exp(d); if (errno == ERANGE) warning("exp argument %g is out of range", d); return tmp_number((AWKNUM) res); } NODE * do_index(tree) NODE *tree; { NODE *s1, *s2; register char *p1, *p2; register int l1, l2; long ret; get_two(tree, &s1, &s2); force_string(s1); force_string(s2); p1 = s1->stptr; p2 = s2->stptr; l1 = s1->stlen; l2 = s2->stlen; ret = 0; if (! strict && IGNORECASE_node->var_value->numbr != 0.0) { while (l1) { if (casetable[*p1] == casetable[*p2] && strncasecmp(p1, p2, l2) == 0) { ret = 1 + s1->stlen - l1; break; } l1--; p1++; } } else { while (l1) { if (STREQN(p1, p2, l2)) { ret = 1 + s1->stlen - l1; break; } l1--; p1++; } } free_temp(s1); free_temp(s2); return tmp_number((AWKNUM) ret); } NODE * do_int(tree) NODE *tree; { NODE *tmp; double floor(); double d; get_one(tree, &tmp); d = floor((double)force_number(tmp)); free_temp(tmp); return tmp_number((AWKNUM) d); } NODE * do_length(tree) NODE *tree; { NODE *tmp; int len; get_one(tree, &tmp); len = force_string(tmp)->stlen; free_temp(tmp); return tmp_number((AWKNUM) len); } NODE * do_log(tree) NODE *tree; { NODE *tmp; double log(); double d, arg; get_one(tree, &tmp); arg = (double) force_number(tmp); if (arg < 0.0) warning("log called with negative argument %g", arg); d = log(arg); free_temp(tmp); return tmp_number((AWKNUM) d); } /* * Note that the output buffer cannot be static because sprintf may get * called recursively by force_string. Hence the wasteful alloca calls */ /* %e and %f formats are not properly implemented. Someone should fix them */ NODE * do_sprintf(tree) NODE *tree; { #define bchunk(s,l) if(l) {\ while((l)>ofre) {\ char *tmp;\ tmp=(char *)alloca(osiz*2);\ memcpy(tmp,obuf,olen);\ obuf=tmp;\ ofre+=osiz;\ osiz*=2;\ }\ memcpy(obuf+olen,s,(l));\ olen+=(l);\ ofre-=(l);\ } /* Is there space for something L big in the buffer? */ #define chksize(l) if((l)>ofre) {\ char *tmp;\ tmp=(char *)alloca(osiz*2);\ memcpy(tmp,obuf,olen);\ obuf=tmp;\ ofre+=osiz;\ osiz*=2;\ } /* * Get the next arg to be formatted. If we've run out of args, * return "" (Null string) */ #define parse_next_arg() {\ if(!carg) arg= Nnull_string;\ else {\ get_one(carg,&arg);\ carg=carg->rnode;\ }\ } char *obuf; int osiz, ofre, olen; static char chbuf[] = "0123456789abcdef"; static char sp[] = " "; char *s0, *s1; int n0; NODE *sfmt, *arg; register NODE *carg; long fw, prec, lj, alt, big; long *cur; long val; #ifdef sun386 /* Can't cast unsigned (int/long) from ptr->value */ long tmp_uval; /* on 386i 4.0.1 C compiler -- it just hangs */ #endif unsigned long uval; int sgn; int base; char cpbuf[30]; /* if we have numbers bigger than 30 */ char *cend = &cpbuf[30];/* chars, we lose, but seems unlikely */ char *cp; char *fill; double tmpval; char *pr_str; int ucasehex = 0; extern char *gcvt(); obuf = (char *) alloca(120); osiz = 120; ofre = osiz; olen = 0; get_one(tree, &sfmt); sfmt = force_string(sfmt); carg = tree->rnode; for (s0 = s1 = sfmt->stptr, n0 = sfmt->stlen; n0-- > 0;) { if (*s1 != '%') { s1++; continue; } bchunk(s0, s1 - s0); s0 = s1; cur = &fw; fw = 0; prec = 0; lj = alt = big = 0; fill = sp; cp = cend; s1++; retry: --n0; switch (*s1++) { case '%': bchunk("%", 1); s0 = s1; break; case '0': if (fill != sp || lj) goto lose; if (cur == &fw) fill = "0"; /* FALL through */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (cur == 0) goto lose; *cur = s1[-1] - '0'; while (n0 > 0 && *s1 >= '0' && *s1 <= '9') { --n0; *cur = *cur * 10 + *s1++ - '0'; } goto retry; #ifdef not_yet case ' ': /* print ' ' or '-' */ case '+': /* print '+' or '-' */ #endif case '-': if (lj || fill != sp) goto lose; lj++; goto retry; case '.': if (cur != &fw) goto lose; cur = ≺ goto retry; case '#': if (alt) goto lose; alt++; goto retry; case 'l': if (big) goto lose; big++; goto retry; case 'c': parse_next_arg(); if (arg->flags & NUMERIC) { #ifdef sun386 tmp_uval = arg->numbr; uval= (unsigned long) tmp_uval; #else uval = (unsigned long) arg->numbr; #endif cpbuf[0] = uval; prec = 1; pr_str = cpbuf; goto dopr_string; } if (! prec) prec = 1; else if (prec > arg->stlen) prec = arg->stlen; pr_str = arg->stptr; goto dopr_string; case 's': parse_next_arg(); arg = force_string(arg); if (!prec || prec > arg->stlen) prec = arg->stlen; pr_str = arg->stptr; dopr_string: if (fw > prec && !lj) { while (fw > prec) { bchunk(sp, 1); fw--; } } bchunk(pr_str, (int) prec); if (fw > prec) { while (fw > prec) { bchunk(sp, 1); fw--; } } s0 = s1; free_temp(arg); break; case 'd': case 'i': parse_next_arg(); val = (long) force_number(arg); free_temp(arg); if (val < 0) { sgn = 1; val = -val; } else sgn = 0; do { *--cp = '0' + val % 10; val /= 10; } while (val); if (sgn) *--cp = '-'; if (prec > fw) fw = prec; prec = cend - cp; if (fw > prec && !lj) { if (fill != sp && *cp == '-') { bchunk(cp, 1); cp++; prec--; fw--; } while (fw > prec) { bchunk(fill, 1); fw--; } } bchunk(cp, (int) prec); if (fw > prec) { while (fw > prec) { bchunk(fill, 1); fw--; } } s0 = s1; break; case 'u': base = 10; goto pr_unsigned; case 'o': base = 8; goto pr_unsigned; case 'X': ucasehex = 1; case 'x': base = 16; goto pr_unsigned; pr_unsigned: parse_next_arg(); uval = (unsigned long) force_number(arg); free_temp(arg); do { *--cp = chbuf[uval % base]; if (ucasehex && isalpha(*cp)) *cp = toupper(*cp); uval /= base; } while (uval); if (alt && (base == 8 || base == 16)) { if (base == 16) { if (ucasehex) *--cp = 'X'; else *--cp = 'x'; } *--cp = '0'; } prec = cend - cp; if (fw > prec && !lj) { while (fw > prec) { bchunk(fill, 1); fw--; } } bchunk(cp, (int) prec); if (fw > prec) { while (fw > prec) { bchunk(fill, 1); fw--; } } s0 = s1; break; case 'g': parse_next_arg(); tmpval = force_number(arg); free_temp(arg); if (prec == 0) prec = 13; (void) gcvt(tmpval, (int) prec, cpbuf); prec = strlen(cpbuf); cp = cpbuf; if (fw > prec && !lj) { if (fill != sp && *cp == '-') { bchunk(cp, 1); cp++; prec--; } /* Deal with .5 as 0.5 */ if (fill == sp && *cp == '.') { --fw; while (--fw >= prec) { bchunk(fill, 1); } bchunk("0", 1); } else while (fw-- > prec) bchunk(fill, 1); } else {/* Turn .5 into 0.5 */ /* FOO */ if (*cp == '.' && fill == sp) { bchunk("0", 1); --fw; } } bchunk(cp, (int) prec); if (fw > prec) while (fw-- > prec) bchunk(fill, 1); s0 = s1; break; case 'f': parse_next_arg(); tmpval = force_number(arg); free_temp(arg); chksize(fw + prec + 5); /* 5==slop */ cp = cpbuf; *cp++ = '%'; if (lj) *cp++ = '-'; if (fill != sp) *cp++ = '0'; if (cur != &fw) { (void) strcpy(cp, "*.*f"); (void) sprintf(obuf + olen, cpbuf, (int) fw, (int) prec, (double) tmpval); } else { (void) strcpy(cp, "*f"); (void) sprintf(obuf + olen, cpbuf, (int) fw, (double) tmpval); } ofre -= strlen(obuf + olen); olen += strlen(obuf + olen); /* There may be nulls */ s0 = s1; break; case 'e': parse_next_arg(); tmpval = force_number(arg); free_temp(arg); chksize(fw + prec + 5); /* 5==slop */ cp = cpbuf; *cp++ = '%'; if (lj) *cp++ = '-'; if (fill != sp) *cp++ = '0'; if (cur != &fw) { (void) strcpy(cp, "*.*e"); (void) sprintf(obuf + olen, cpbuf, (int) fw, (int) prec, (double) tmpval); } else { (void) strcpy(cp, "*e"); (void) sprintf(obuf + olen, cpbuf, (int) fw, (double) tmpval); } ofre -= strlen(obuf + olen); olen += strlen(obuf + olen); /* There may be nulls */ s0 = s1; break; default: lose: break; } } bchunk(s0, s1 - s0); free_temp(sfmt); return tmp_string(obuf, olen); } void do_printf(tree) NODE *tree; { struct redirect *rp = NULL; register FILE *fp = stdout; int errflg = 0; /* not used, sigh */ if (tree->rnode) { rp = redirect(tree->rnode, &errflg); if (rp) fp = rp->fp; } if (fp) print_simple(do_sprintf(tree->lnode), fp); if (rp && (rp->flag & RED_NOBUF)) fflush(fp); } NODE * do_sqrt(tree) NODE *tree; { NODE *tmp; double sqrt(); double d, arg; get_one(tree, &tmp); arg = (double) force_number(tmp); if (arg < 0.0) warning("sqrt called with negative argument %g", arg); d = sqrt(arg); free_temp(tmp); return tmp_number((AWKNUM) d); } NODE * do_substr(tree) NODE *tree; { NODE *t1, *t2, *t3; NODE *r; register int indx, length; t1 = t2 = t3 = NULL; length = -1; if (get_three(tree, &t1, &t2, &t3) == 3) length = (int) force_number(t3); indx = (int) force_number(t2) - 1; t1 = force_string(t1); if (length == -1) length = t1->stlen; if (indx < 0) indx = 0; if (indx >= t1->stlen || length <= 0) { if (t3) free_temp(t3); free_temp(t2); free_temp(t1); return Nnull_string; } if (indx + length > t1->stlen) length = t1->stlen - indx; if (t3) free_temp(t3); free_temp(t2); r = tmp_string(t1->stptr + indx, length); free_temp(t1); return r; } NODE * do_system(tree) NODE *tree; { #if defined(unix) || defined(MSDOS) /* || defined(gnu) */ NODE *tmp; int ret; (void) flush_io (); /* so output is synchronous with gawk's */ get_one(tree, &tmp); ret = system(force_string(tmp)->stptr); ret = (ret >> 8) & 0xff; free_temp(tmp); return tmp_number((AWKNUM) ret); #else fatal("the \"system\" function is not supported."); /* NOTREACHED */ #endif } void do_print(tree) register NODE *tree; { struct redirect *rp = NULL; register FILE *fp = stdout; int errflg = 0; /* not used, sigh */ if (tree->rnode) { rp = redirect(tree->rnode, &errflg); if (rp) fp = rp->fp; } if (!fp) return; tree = tree->lnode; if (!tree) tree = WHOLELINE; if (tree->type != Node_expression_list) { if (!(tree->flags & STR)) cant_happen(); print_simple(tree, fp); } else { while (tree) { print_simple(force_string(tree_eval(tree->lnode)), fp); tree = tree->rnode; if (tree) print_simple(OFS_node->var_value, fp); } } print_simple(ORS_node->var_value, fp); if (rp && (rp->flag & RED_NOBUF)) fflush(fp); } NODE * do_tolower(tree) NODE *tree; { NODE *t1, *t2; register char *cp, *cp2; get_one(tree, &t1); t1 = force_string(t1); t2 = tmp_string(t1->stptr, t1->stlen); for (cp = t2->stptr, cp2 = t2->stptr + t2->stlen; cp < cp2; cp++) if (isupper(*cp)) *cp = tolower(*cp); free_temp(t1); return t2; } NODE * do_toupper(tree) NODE *tree; { NODE *t1, *t2; register char *cp; get_one(tree, &t1); t1 = force_string(t1); t2 = tmp_string(t1->stptr, t1->stlen); for (cp = t2->stptr; cp < t2->stptr + t2->stlen; cp++) if (islower(*cp)) *cp = toupper(*cp); free_temp(t1); return t2; } /* * Get the arguments to functions. No function cares if you give it too many * args (they're ignored). Only a few fuctions complain about being given * too few args. The rest have defaults. */ static void get_one(tree, res) NODE *tree, **res; { if (!tree) { *res = WHOLELINE; return; } *res = tree_eval(tree->lnode); } static void get_two(tree, res1, res2) NODE *tree, **res1, **res2; { if (!tree) { *res1 = WHOLELINE; return; } *res1 = tree_eval(tree->lnode); if (!tree->rnode) return; tree = tree->rnode; *res2 = tree_eval(tree->lnode); } static int get_three(tree, res1, res2, res3) NODE *tree, **res1, **res2, **res3; { if (!tree) { *res1 = WHOLELINE; return 0; } *res1 = tree_eval(tree->lnode); if (!tree->rnode) return 1; tree = tree->rnode; *res2 = tree_eval(tree->lnode); if (!tree->rnode) return 2; tree = tree->rnode; *res3 = tree_eval(tree->lnode); return 3; } int a_get_three(tree, res1, res2, res3) NODE *tree, **res1, **res2, **res3; { if (!tree) { *res1 = WHOLELINE; return 0; } *res1 = tree_eval(tree->lnode); if (!tree->rnode) return 1; tree = tree->rnode; *res2 = tree->lnode; if (!tree->rnode) return 2; tree = tree->rnode; *res3 = tree_eval(tree->lnode); return 3; } void print_simple(tree, fp) NODE *tree; FILE *fp; { if (fwrite(tree->stptr, sizeof(char), tree->stlen, fp) != tree->stlen) warning("fwrite: %s", strerror(errno)); free_temp(tree); } NODE * do_atan2(tree) NODE *tree; { NODE *t1, *t2; extern double atan2(); double d1, d2; get_two(tree, &t1, &t2); d1 = force_number(t1); d2 = force_number(t2); free_temp(t1); free_temp(t2); return tmp_number((AWKNUM) atan2(d1, d2)); } NODE * do_sin(tree) NODE *tree; { NODE *tmp; extern double sin(); double d; get_one(tree, &tmp); d = sin((double)force_number(tmp)); free_temp(tmp); return tmp_number((AWKNUM) d); } NODE * do_cos(tree) NODE *tree; { NODE *tmp; extern double cos(); double d; get_one(tree, &tmp); d = cos((double)force_number(tmp)); free_temp(tmp); return tmp_number((AWKNUM) d); } static int firstrand = 1; static char state[256]; #define MAXLONG 2147483647 /* maximum value for long int */ /* ARGSUSED */ NODE * do_rand(tree) NODE *tree; { if (firstrand) { (void) initstate((unsigned) 1, state, sizeof state); srandom(1); firstrand = 0; } return tmp_number((AWKNUM) random() / MAXLONG); } NODE * do_srand(tree) NODE *tree; { NODE *tmp; static long save_seed = 1; long ret = save_seed; /* SVR4 awk srand returns previous seed */ extern long time(); if (firstrand) (void) initstate((unsigned) 1, state, sizeof state); else (void) setstate(state); if (!tree) srandom((int) (save_seed = time((long *) 0))); else { get_one(tree, &tmp); srandom((int) (save_seed = (long) force_number(tmp))); free_temp(tmp); } firstrand = 0; return tmp_number((AWKNUM) ret); } NODE * do_match(tree) NODE *tree; { NODE *t1; int rstart; struct re_registers reregs; struct re_pattern_buffer *rp; int need_to_free = 0; t1 = force_string(tree_eval(tree->lnode)); tree = tree->rnode; if (tree == NULL || tree->lnode == NULL) fatal("match called with only one argument"); tree = tree->lnode; if (tree->type == Node_regex) { rp = tree->rereg; if (!strict && ((IGNORECASE_node->var_value->numbr != 0) ^ (tree->re_case != 0))) { /* recompile since case sensitivity differs */ rp = tree->rereg = mk_re_parse(tree->re_text, (IGNORECASE_node->var_value->numbr != 0)); tree->re_case = (IGNORECASE_node->var_value->numbr != 0); } } else { need_to_free = 1; rp = make_regexp(force_string(tree_eval(tree)), (IGNORECASE_node->var_value->numbr != 0)); if (rp == NULL) cant_happen(); } rstart = re_search(rp, t1->stptr, t1->stlen, 0, t1->stlen, &reregs); free_temp(t1); if (rstart >= 0) { rstart++; /* 1-based indexing */ /* RSTART set to rstart below */ RLENGTH_node->var_value->numbr = (AWKNUM) (reregs.end[0] - reregs.start[0]); } else { /* * Match failed. Set RSTART to 0, RLENGTH to -1. * Return the value of RSTART. */ rstart = 0; /* used as return value */ RLENGTH_node->var_value->numbr = -1.0; } RSTART_node->var_value->numbr = (AWKNUM) rstart; if (need_to_free) { free(rp->buffer); free(rp->fastmap); free((char *) rp); } return tmp_number((AWKNUM) rstart); } static NODE * sub_common(tree, global) NODE *tree; int global; { register int len; register char *scan; register char *bp, *cp; int search_start = 0; int match_length; int matches = 0; char *buf; struct re_pattern_buffer *rp; NODE *s; /* subst. pattern */ NODE *t; /* string to make sub. in; $0 if none given */ struct re_registers reregs; unsigned int saveflags; NODE *tmp; NODE **lhs; char *lastbuf; int need_to_free = 0; if (tree == NULL) fatal("sub or gsub called with 0 arguments"); tmp = tree->lnode; if (tmp->type == Node_regex) { rp = tmp->rereg; if (! strict && ((IGNORECASE_node->var_value->numbr != 0) ^ (tmp->re_case != 0))) { /* recompile since case sensitivity differs */ rp = tmp->rereg = mk_re_parse(tmp->re_text, (IGNORECASE_node->var_value->numbr != 0)); tmp->re_case = (IGNORECASE_node->var_value->numbr != 0); } } else { need_to_free = 1; rp = make_regexp(force_string(tree_eval(tmp)), (IGNORECASE_node->var_value->numbr != 0)); if (rp == NULL) cant_happen(); } tree = tree->rnode; if (tree == NULL) fatal("sub or gsub called with only 1 argument"); s = force_string(tree_eval(tree->lnode)); tree = tree->rnode; deref = 0; field_num = -1; if (tree == NULL) { t = node0_valid ? fields_arr[0] : *get_field(0, 0); lhs = &fields_arr[0]; field_num = 0; deref = t; } else { t = tree->lnode; lhs = get_lhs(t, 1); t = force_string(tree_eval(t)); } /* * create a private copy of the string */ if (t->stref > 1 || (t->flags & PERM)) { saveflags = t->flags; t->flags &= ~MALLOC; tmp = dupnode(t); t->flags = saveflags; do_deref(); t = tmp; if (lhs) *lhs = tmp; } lastbuf = t->stptr; do { if (re_search(rp, t->stptr, t->stlen, search_start, t->stlen-search_start, &reregs) == -1 || reregs.start[0] == reregs.end[0]) break; matches++; /* * first, make a pass through the sub. pattern, to calculate * the length of the string after substitution */ match_length = reregs.end[0] - reregs.start[0]; len = t->stlen - match_length; for (scan = s->stptr; scan < s->stptr + s->stlen; scan++) if (*scan == '&') len += match_length; else if (*scan == '\\' && *(scan+1) == '&') { scan++; len++; } else len++; emalloc(buf, char *, len + 1, "do_sub"); bp = buf; /* * now, create the result, copying in parts of the original * string */ for (scan = t->stptr; scan < t->stptr + reregs.start[0]; scan++) *bp++ = *scan; for (scan = s->stptr; scan < s->stptr + s->stlen; scan++) if (*scan == '&') for (cp = t->stptr + reregs.start[0]; cp < t->stptr + reregs.end[0]; cp++) *bp++ = *cp; else if (*scan == '\\' && *(scan+1) == '&') { scan++; *bp++ = *scan; } else *bp++ = *scan; search_start = bp - buf; for (scan = t->stptr + reregs.end[0]; scan < t->stptr + t->stlen; scan++) *bp++ = *scan; *bp = '\0'; free(lastbuf); t->stptr = buf; lastbuf = buf; t->stlen = len; } while (global && search_start < t->stlen); free_temp(s); if (need_to_free) { free(rp->buffer); free(rp->fastmap); free((char *) rp); } if (matches > 0) { if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); t->flags &= ~(NUM|NUMERIC); } field_num = -1; return tmp_number((AWKNUM) matches); } NODE * do_gsub(tree) NODE *tree; { return sub_common(tree, 1); } NODE * do_sub(tree) NODE *tree; { return sub_common(tree, 0); } gawk-2.11/msg.c 644 11660 0 4170 4463465371 11516 0ustar hackwheel/* * msg.c - routines for error messages */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" int sourceline = 0; char *source = NULL; /* VARARGS2 */ static void err(s, msg, argp) char *s; char *msg; va_list *argp; { int line; char *file; (void) fprintf(stderr, "%s: %s ", myname, s); vfprintf(stderr, msg, *argp); (void) fprintf(stderr, "\n"); line = (int) FNR_node->var_value->numbr; if (line) { (void) fprintf(stderr, " input line number %d", line); file = FILENAME_node->var_value->stptr; if (file && !STREQ(file, "-")) (void) fprintf(stderr, ", file `%s'", file); (void) fprintf(stderr, "\n"); } if (sourceline) { (void) fprintf(stderr, " source line number %d", sourceline); if (source) (void) fprintf(stderr, ", file `%s'", source); (void) fprintf(stderr, "\n"); } } /*VARARGS0*/ void msg(va_alist) va_dcl { va_list args; char *mesg; va_start(args); mesg = va_arg(args, char *); err("", mesg, &args); va_end(args); } /*VARARGS0*/ void warning(va_alist) va_dcl { va_list args; char *mesg; va_start(args); mesg = va_arg(args, char *); err("warning:", mesg, &args); va_end(args); } /*VARARGS0*/ void fatal(va_alist) va_dcl { va_list args; char *mesg; va_start(args); mesg = va_arg(args, char *); err("fatal error:", mesg, &args); va_end(args); #ifdef DEBUG abort(); #endif exit(1); } gawk-2.11/debug.c 644 11660 0 24741 4527633567 12051 0ustar hackwheel/* * debug.c -- Various debugging routines */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" #ifdef DEBUG extern NODE **fields_arr; /* This is all debugging stuff. Ignore it and maybe it'll go away. */ /* * Some of it could be turned into a really cute trace command, if anyone * wants to. */ char *nnames[] = { "illegal", "times", "quotient", "mod", "plus", "minus", "cond_pair", "subscript", "concat", "exp", /* 10 */ "preincrement", "predecrement", "postincrement", "postdecrement", "unary_minus", "field_spec", "assign", "assign_times", "assign_quotient", "assign_mod", /* 20 */ "assign_plus", "assign_minus", "assign_exp", "and", "or", "equal", "notequal", "less", "greater", "leq", /* 30 */ "geq", "match", "nomatch", "not", "rule_list", "rule_node", "statement_list", "if_branches", "expression_list", "param_list", /* 40 */ "K_if", "K_while", "K_for", "K_arrayfor", "K_break", "K_continue", "K_print", "K_printf", "K_next", "K_exit", /* 50 */ "K_do", "K_return", "K_delete", "K_getline", "K_function", "redirect_output", "redirect_append", "redirect_pipe", "redirect_pipein", "redirect_input", /* 60 */ "var", "var_array", "val", "builtin", "line_range", "in_array", "func", "func_call", "cond_exp", "regex", /* 70 */ "hashnode", "ahash" }; ptree(n) NODE *n; { print_parse_tree(n); } pt() { long x; (void) scanf("%x", &x); printf("0x%x\n", x); print_parse_tree((NODE *) x); fflush(stdout); } static depth = 0; print_parse_tree(ptr) NODE *ptr; { if (!ptr) { printf("NULL\n"); return; } if ((int) (ptr->type) < 0 || (int) (ptr->type) > sizeof(nnames) / sizeof(nnames[0])) { printf("(0x%x Type %d??)\n", ptr, ptr->type); return; } printf("(%d)%*s", depth, depth, ""); switch ((int) ptr->type) { case (int) Node_val: printf("(0x%x Value ", ptr); if (ptr->flags&STR) printf("str: \"%.*s\" ", ptr->stlen, ptr->stptr); if (ptr->flags&NUM) printf("num: %g", ptr->numbr); printf(")\n"); return; case (int) Node_var_array: { struct search *l; printf("(0x%x Array)\n", ptr); for (l = assoc_scan(ptr); l; l = assoc_next(l)) { printf("\tindex: "); print_parse_tree(l->retval); printf("\tvalue: "); print_parse_tree(*assoc_lookup(ptr, l->retval)); printf("\n"); } return; } case Node_param_list: printf("(0x%x Local variable %s)\n", ptr, ptr->param); if (ptr->rnode) print_parse_tree(ptr->rnode); return; case Node_regex: printf("(0x%x Regular expression %s\n", ptr, ptr->re_text); return; } if (ptr->lnode) printf("0x%x = left<--", ptr->lnode); printf("(0x%x %s.%d)", ptr, nnames[(int) (ptr->type)], ptr->type); if (ptr->rnode) printf("-->right = 0x%x", ptr->rnode); printf("\n"); depth++; if (ptr->lnode) print_parse_tree(ptr->lnode); switch ((int) ptr->type) { case (int) Node_line_range: case (int) Node_match: case (int) Node_nomatch: break; case (int) Node_builtin: printf("Builtin: %d\n", ptr->proc); break; case (int) Node_K_for: case (int) Node_K_arrayfor: printf("(%s:)\n", nnames[(int) (ptr->type)]); print_parse_tree(ptr->forloop->init); printf("looping:\n"); print_parse_tree(ptr->forloop->cond); printf("doing:\n"); print_parse_tree(ptr->forloop->incr); break; default: if (ptr->rnode) print_parse_tree(ptr->rnode); break; } --depth; } /* * print out all the variables in the world */ dump_vars() { register int n; register NODE *buc; #ifdef notdef printf("Fields:"); dump_fields(); #endif printf("Vars:\n"); for (n = 0; n < HASHSIZE; n++) { for (buc = variables[n]; buc; buc = buc->hnext) { printf("'%.*s': ", buc->hlength, buc->hname); print_parse_tree(buc->hvalue); } } printf("End\n"); } #ifdef notdef dump_fields() { register NODE **p; register int n; printf("%d fields\n", f_arr_siz); for (n = 0, p = &fields_arr[0]; n < f_arr_siz; n++, p++) { printf("$%d is '", n); print_simple(*p, stdout); printf("'\n"); } } #endif /* VARARGS1 */ print_debug(str, n) char *str; { extern int debugging; if (debugging) printf("%s:0x%x\n", str, n); } int indent = 0; print_a_node(ptr) NODE *ptr; { NODE *p1; char *str, *str2; int n; NODE *buc; if (!ptr) return; /* don't print null ptrs */ switch (ptr->type) { case Node_val: if (ptr->flags&NUM) printf("%g", ptr->numbr); else printf("\"%.*s\"", ptr->stlen, ptr->stptr); return; case Node_times: str = "*"; goto pr_twoop; case Node_quotient: str = "/"; goto pr_twoop; case Node_mod: str = "%"; goto pr_twoop; case Node_plus: str = "+"; goto pr_twoop; case Node_minus: str = "-"; goto pr_twoop; case Node_exp: str = "^"; goto pr_twoop; case Node_concat: str = " "; goto pr_twoop; case Node_assign: str = "="; goto pr_twoop; case Node_assign_times: str = "*="; goto pr_twoop; case Node_assign_quotient: str = "/="; goto pr_twoop; case Node_assign_mod: str = "%="; goto pr_twoop; case Node_assign_plus: str = "+="; goto pr_twoop; case Node_assign_minus: str = "-="; goto pr_twoop; case Node_assign_exp: str = "^="; goto pr_twoop; case Node_and: str = "&&"; goto pr_twoop; case Node_or: str = "||"; goto pr_twoop; case Node_equal: str = "=="; goto pr_twoop; case Node_notequal: str = "!="; goto pr_twoop; case Node_less: str = "<"; goto pr_twoop; case Node_greater: str = ">"; goto pr_twoop; case Node_leq: str = "<="; goto pr_twoop; case Node_geq: str = ">="; goto pr_twoop; pr_twoop: print_a_node(ptr->lnode); printf("%s", str); print_a_node(ptr->rnode); return; case Node_not: str = "!"; str2 = ""; goto pr_oneop; case Node_field_spec: str = "$("; str2 = ")"; goto pr_oneop; case Node_postincrement: str = ""; str2 = "++"; goto pr_oneop; case Node_postdecrement: str = ""; str2 = "--"; goto pr_oneop; case Node_preincrement: str = "++"; str2 = ""; goto pr_oneop; case Node_predecrement: str = "--"; str2 = ""; goto pr_oneop; pr_oneop: printf(str); print_a_node(ptr->subnode); printf(str2); return; case Node_expression_list: print_a_node(ptr->lnode); if (ptr->rnode) { printf(","); print_a_node(ptr->rnode); } return; case Node_var: for (n = 0; n < HASHSIZE; n++) { for (buc = variables[n]; buc; buc = buc->hnext) { if (buc->hvalue == ptr) { printf("%.*s", buc->hlength, buc->hname); n = HASHSIZE; break; } } } return; case Node_subscript: print_a_node(ptr->lnode); printf("["); print_a_node(ptr->rnode); printf("]"); return; case Node_builtin: printf("some_builtin("); print_a_node(ptr->subnode); printf(")"); return; case Node_statement_list: printf("{\n"); indent++; for (n = indent; n; --n) printf(" "); while (ptr) { print_maybe_semi(ptr->lnode); if (ptr->rnode) for (n = indent; n; --n) printf(" "); ptr = ptr->rnode; } --indent; for (n = indent; n; --n) printf(" "); printf("}\n"); for (n = indent; n; --n) printf(" "); return; case Node_K_if: printf("if("); print_a_node(ptr->lnode); printf(") "); ptr = ptr->rnode; if (ptr->lnode->type == Node_statement_list) { printf("{\n"); indent++; for (p1 = ptr->lnode; p1; p1 = p1->rnode) { for (n = indent; n; --n) printf(" "); print_maybe_semi(p1->lnode); } --indent; for (n = indent; n; --n) printf(" "); if (ptr->rnode) { printf("} else "); } else { printf("}\n"); return; } } else { print_maybe_semi(ptr->lnode); if (ptr->rnode) { for (n = indent; n; --n) printf(" "); printf("else "); } else return; } if (!ptr->rnode) return; deal_with_curls(ptr->rnode); return; case Node_K_while: printf("while("); print_a_node(ptr->lnode); printf(") "); deal_with_curls(ptr->rnode); return; case Node_K_do: printf("do "); deal_with_curls(ptr->rnode); printf("while("); print_a_node(ptr->lnode); printf(") "); return; case Node_K_for: printf("for("); print_a_node(ptr->forloop->init); printf(";"); print_a_node(ptr->forloop->cond); printf(";"); print_a_node(ptr->forloop->incr); printf(") "); deal_with_curls(ptr->forsub); return; case Node_K_arrayfor: printf("for("); print_a_node(ptr->forloop->init); printf(" in "); print_a_node(ptr->forloop->incr); printf(") "); deal_with_curls(ptr->forsub); return; case Node_K_printf: printf("printf("); print_a_node(ptr->lnode); printf(")"); return; case Node_K_print: printf("print("); print_a_node(ptr->lnode); printf(")"); return; case Node_K_next: printf("next"); return; case Node_K_break: printf("break"); return; case Node_K_delete: printf("delete "); print_a_node(ptr->lnode); return; case Node_func: printf("function %s (", ptr->lnode->param); if (ptr->lnode->rnode) print_a_node(ptr->lnode->rnode); printf(")\n"); print_a_node(ptr->rnode); return; case Node_param_list: printf("%s", ptr->param); if (ptr->rnode) { printf(", "); print_a_node(ptr->rnode); } return; default: print_parse_tree(ptr); return; } } print_maybe_semi(ptr) NODE *ptr; { print_a_node(ptr); switch (ptr->type) { case Node_K_if: case Node_K_for: case Node_K_arrayfor: case Node_statement_list: break; default: printf(";\n"); break; } } deal_with_curls(ptr) NODE *ptr; { int n; if (ptr->type == Node_statement_list) { printf("{\n"); indent++; while (ptr) { for (n = indent; n; --n) printf(" "); print_maybe_semi(ptr->lnode); ptr = ptr->rnode; } --indent; for (n = indent; n; --n) printf(" "); printf("}\n"); } else { print_maybe_semi(ptr); } } NODE * do_prvars() { dump_vars(); return Nnull_string; } NODE * do_bp() { return Nnull_string; } #endif #ifdef MEMDEBUG #undef free extern void free(); void do_free(s) char *s; { free(s); } #endif gawk-2.11/io.c 644 11660 0 42073 4527633607 11363 0ustar hackwheel/* * io.c - routines for dealing with input and output and records */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" #ifndef O_RDONLY #include #endif #include extern FILE *popen(); static void do_file(); static IOBUF *nextfile(); static int get_a_record(); static int iop_close(); static IOBUF *iop_alloc(); static void close_one(); static int close_redir(); static IOBUF *gawk_popen(); static int gawk_pclose(); static struct redirect *red_head = NULL; static int getline_redirect = 0; /* "getline cnt != EOF) return curfile; for (; i < (int) (ARGC_node->lnode->numbr); i++) { arg = (*assoc_lookup(ARGV_node, tmp_number((AWKNUM) i)))->stptr; if (*arg == '\0') continue; cp = strchr(arg, '='); if (cp != NULL) { *cp++ = '\0'; variable(arg)->var_value = make_string(cp, strlen(cp)); *--cp = '='; /* restore original text of ARGV */ } else { files++; if (STREQ(arg, "-")) fd = 0; else fd = devopen(arg, "r"); if (fd == -1) fatal("cannot open file `%s' for reading (%s)", arg, strerror(errno)); /* NOTREACHED */ /* This is a kludge. */ deref = FILENAME_node->var_value; do_deref(); FILENAME_node->var_value = make_string(arg, strlen(arg)); FNR_node->var_value->numbr = 0.0; i++; break; } } if (files == 0) { files++; /* no args. -- use stdin */ /* FILENAME is init'ed to "-" */ /* FNR is init'ed to 0 */ fd = 0; } if (fd == -1) return NULL; return curfile = iop_alloc(fd); } static IOBUF * iop_alloc(fd) int fd; { IOBUF *iop; struct stat stb; /* * System V doesn't have the file system block size in the * stat structure. So we have to make some sort of reasonable * guess. We use stdio's BUFSIZ, since that is what it was * meant for in the first place. */ #ifdef BLKSIZE_MISSING #define DEFBLKSIZE BUFSIZ #else #define DEFBLKSIZE (stb.st_blksize ? stb.st_blksize : BUFSIZ) #endif if (fd == -1) return NULL; emalloc(iop, IOBUF *, sizeof(IOBUF), "nextfile"); iop->flag = 0; if (isatty(fd)) { iop->flag |= IOP_IS_TTY; iop->size = BUFSIZ; } else if (fstat(fd, &stb) == -1) fatal("can't stat fd %d (%s)", fd, strerror(errno)); else if (lseek(fd, 0L, 0) == -1) iop->size = DEFBLKSIZE; else iop->size = (stb.st_size < DEFBLKSIZE ? stb.st_size+1 : DEFBLKSIZE); errno = 0; iop->fd = fd; emalloc(iop->buf, char *, iop->size, "nextfile"); iop->off = iop->buf; iop->cnt = 0; iop->secsiz = iop->size < BUFSIZ ? iop->size : BUFSIZ; emalloc(iop->secbuf, char *, iop->secsiz, "nextfile"); return iop; } void do_input() { IOBUF *iop; extern int exiting; while ((iop = nextfile()) != NULL) { do_file(iop); if (exiting) break; } } static int iop_close(iop) IOBUF *iop; { int ret; ret = close(iop->fd); if (ret == -1) warning("close of fd %d failed (%s)", iop->fd, strerror(errno)); free(iop->buf); free(iop->secbuf); free((char *)iop); return ret == -1 ? 1 : 0; } /* * This reads in a record from the input file */ static int inrec(iop) IOBUF *iop; { int cnt; int retval = 0; cnt = get_a_record(&line_buf, iop); if (cnt == EOF) { cnt = 0; retval = 1; } else { if (!getline_redirect) { assign_number(&NR_node->var_value, NR_node->var_value->numbr + 1.0); assign_number(&FNR_node->var_value, FNR_node->var_value->numbr + 1.0); } } set_record(line_buf, cnt); return retval; } static void do_file(iop) IOBUF *iop; { /* This is where it spends all its time. The infamous MAIN LOOP */ if (inrec(iop) == 0) while (interpret(expression_value) && inrec(iop) == 0) ; (void) iop_close(iop); } int get_rs() { register NODE *tmp; tmp = force_string(RS_node->var_value); if (tmp->stlen == 0) return 0; return *(tmp->stptr); } /* Redirection for printf and print commands */ struct redirect * redirect(tree, errflg) NODE *tree; int *errflg; { register NODE *tmp; register struct redirect *rp; register char *str; int tflag = 0; int outflag = 0; char *direction = "to"; char *mode; int fd; switch (tree->type) { case Node_redirect_append: tflag = RED_APPEND; case Node_redirect_output: outflag = (RED_FILE|RED_WRITE); tflag |= outflag; break; case Node_redirect_pipe: tflag = (RED_PIPE|RED_WRITE); break; case Node_redirect_pipein: tflag = (RED_PIPE|RED_READ); break; case Node_redirect_input: tflag = (RED_FILE|RED_READ); break; default: fatal ("invalid tree type %d in redirect()", tree->type); break; } tmp = force_string(tree_eval(tree->subnode)); str = tmp->stptr; for (rp = red_head; rp != NULL; rp = rp->next) if (STREQ(rp->value, str) && ((rp->flag & ~RED_NOBUF) == tflag || (outflag && (rp->flag & (RED_FILE|RED_WRITE)) == outflag))) break; if (rp == NULL) { emalloc(rp, struct redirect *, sizeof(struct redirect), "redirect"); emalloc(str, char *, tmp->stlen+1, "redirect"); memcpy(str, tmp->stptr, tmp->stlen+1); rp->value = str; rp->flag = tflag; rp->offset = 0; rp->fp = NULL; rp->iop = NULL; /* maintain list in most-recently-used first order */ if (red_head) red_head->prev = rp; rp->prev = NULL; rp->next = red_head; red_head = rp; } while (rp->fp == NULL && rp->iop == NULL) { mode = NULL; errno = 0; switch (tree->type) { case Node_redirect_output: mode = "w"; break; case Node_redirect_append: mode = "a"; break; case Node_redirect_pipe: if ((rp->fp = popen(str, "w")) == NULL) fatal("can't open pipe (\"%s\") for output (%s)", str, strerror(errno)); rp->flag |= RED_NOBUF; break; case Node_redirect_pipein: direction = "from"; if (gawk_popen(str, rp) == NULL) fatal("can't open pipe (\"%s\") for input (%s)", str, strerror(errno)); break; case Node_redirect_input: direction = "from"; rp->iop = iop_alloc(devopen(str, "r")); break; default: cant_happen(); } if (mode != NULL) { fd = devopen(str, mode); if (fd != -1) { rp->fp = fdopen(fd, mode); if (isatty(fd)) rp->flag |= RED_NOBUF; } } if (rp->fp == NULL && rp->iop == NULL) { /* too many files open -- close one and try again */ if (errno == ENFILE || errno == EMFILE) close_one(); else { /* * Some other reason for failure. * * On redirection of input from a file, * just return an error, so e.g. getline * can return -1. For output to file, * complain. The shell will complain on * a bad command to a pipe. */ *errflg = 1; if (tree->type == Node_redirect_output || tree->type == Node_redirect_append) fatal("can't redirect %s `%s' (%s)", direction, str, strerror(errno)); else return NULL; } } } if (rp->offset != 0) /* this file was previously open */ if (fseek(rp->fp, rp->offset, 0) == -1) fatal("can't seek to %ld on `%s' (%s)", rp->offset, str, strerror(errno)); free_temp(tmp); return rp; } static void close_one() { register struct redirect *rp; register struct redirect *rplast = NULL; /* go to end of list first, to pick up least recently used entry */ for (rp = red_head; rp != NULL; rp = rp->next) rplast = rp; /* now work back up through the list */ for (rp = rplast; rp != NULL; rp = rp->prev) if (rp->fp && (rp->flag & RED_FILE)) { rp->offset = ftell(rp->fp); if (fclose(rp->fp)) warning("close of \"%s\" failed (%s).", rp->value, strerror(errno)); rp->fp = NULL; break; } if (rp == NULL) /* surely this is the only reason ??? */ fatal("too many pipes or input files open"); } NODE * do_close(tree) NODE *tree; { NODE *tmp; register struct redirect *rp; tmp = force_string(tree_eval(tree->subnode)); for (rp = red_head; rp != NULL; rp = rp->next) { if (STREQ(rp->value, tmp->stptr)) break; } free_temp(tmp); if (rp == NULL) /* no match */ return tmp_number((AWKNUM) 0.0); fflush(stdout); /* synchronize regular output */ return tmp_number((AWKNUM)close_redir(rp)); } static int close_redir(rp) register struct redirect *rp; { int status = 0; if ((rp->flag & (RED_PIPE|RED_WRITE)) == (RED_PIPE|RED_WRITE)) status = pclose(rp->fp); else if (rp->fp) status = fclose(rp->fp); else if (rp->iop) { if (rp->flag & RED_PIPE) status = gawk_pclose(rp); else status = iop_close(rp->iop); } /* SVR4 awk checks and warns about status of close */ if (status) warning("failure status (%d) on %s close of \"%s\" (%s).", status, (rp->flag & RED_PIPE) ? "pipe" : "file", rp->value, strerror(errno)); if (rp->next) rp->next->prev = rp->prev; if (rp->prev) rp->prev->next = rp->next; else red_head = rp->next; free(rp->value); free((char *)rp); return status; } int flush_io () { register struct redirect *rp; int status = 0; errno = 0; if (fflush(stdout)) { warning("error writing standard output (%s).", strerror(errno)); status++; } errno = 0; if (fflush(stderr)) { warning("error writing standard error (%s).", strerror(errno)); status++; } for (rp = red_head; rp != NULL; rp = rp->next) /* flush both files and pipes, what the heck */ if ((rp->flag & RED_WRITE) && rp->fp != NULL) if (fflush(rp->fp)) { warning("%s flush of \"%s\" failed (%s).", (rp->flag & RED_PIPE) ? "pipe" : "file", rp->value, strerror(errno)); status++; } return status; } int close_io () { register struct redirect *rp; int status = 0; for (rp = red_head; rp != NULL; rp = rp->next) if (close_redir(rp)) status++; return status; } /* devopen --- handle /dev/std{in,out,err}, /dev/fd/N, regular files */ int devopen (name, mode) char *name, *mode; { int openfd = -1; FILE *fdopen (); char *cp; int flag = 0; switch(mode[0]) { case 'r': flag = O_RDONLY; break; case 'w': flag = O_WRONLY|O_CREAT|O_TRUNC; break; case 'a': flag = O_WRONLY|O_APPEND|O_CREAT; break; default: cant_happen(); } #if defined(STRICT) || defined(NO_DEV_FD) return (open (name, flag, 0666)); #else if (strict) return (open (name, flag, 0666)); if (!STREQN (name, "/dev/", 5)) return (open (name, flag, 0666)); else cp = name + 5; /* XXX - first three tests ignore mode */ if (STREQ(cp, "stdin")) return (0); else if (STREQ(cp, "stdout")) return (1); else if (STREQ(cp, "stderr")) return (2); else if (STREQN(cp, "fd/", 3)) { cp += 3; if (sscanf (cp, "%d", & openfd) == 1 && openfd >= 0) /* got something */ return openfd; else return -1; } else return (open (name, flag, 0666)); #endif } #ifndef MSDOS static IOBUF * gawk_popen(cmd, rp) char *cmd; struct redirect *rp; { int p[2]; register int pid; rp->pid = -1; rp->iop = NULL; if (pipe(p) < 0) return NULL; if ((pid = fork()) == 0) { close(p[0]); dup2(p[1], 1); close(p[1]); execl("/bin/sh", "sh", "-c", cmd, 0); _exit(127); } if (pid == -1) return NULL; rp->pid = pid; close(p[1]); return (rp->iop = iop_alloc(p[0])); } static int gawk_pclose(rp) struct redirect *rp; { SIGTYPE (*hstat)(), (*istat)(), (*qstat)(); int pid; int status; struct redirect *redp; iop_close(rp->iop); if (rp->pid == -1) return rp->status; hstat = signal(SIGHUP, SIG_IGN); istat = signal(SIGINT, SIG_IGN); qstat = signal(SIGQUIT, SIG_IGN); for (;;) { pid = wait(&status); if (pid == -1 && errno == ECHILD) break; else if (pid == rp->pid) { rp->pid = -1; rp->status = status; break; } else { for (redp = red_head; redp != NULL; redp = redp->next) if (pid == redp->pid) { redp->pid = -1; redp->status = status; break; } } } signal(SIGHUP, hstat); signal(SIGINT, istat); signal(SIGQUIT, qstat); return(rp->status); } #else static struct { char *command; char *name; } pipes[_NFILE]; static IOBUF * gawk_popen(cmd, rp) char *cmd; struct redirect *rp; { extern char *strdup(const char *); int current; char *name; static char cmdbuf[256]; /* get a name to use. */ if ((name = tempnam(".", "pip")) == NULL) return NULL; sprintf(cmdbuf,"%s > %s", cmd, name); system(cmdbuf); if ((current = open(name,O_RDONLY)) == -1) return NULL; pipes[current].name = name; pipes[current].command = strdup(cmd); return (rp->iop = iop_alloc(current)); } static int gawk_pclose(rp) struct redirect *rp; { int cur = rp->iop->fd; int rval; rval = iop_close(rp->iop); /* check for an open file */ if (pipes[cur].name == NULL) return -1; unlink(pipes[cur].name); free(pipes[cur].name); pipes[cur].name = NULL; free(pipes[cur].command); return rval; } #endif #define DO_END_OF_BUF len = bp - iop->off;\ used = last - start;\ while (len + used > iop->secsiz) {\ iop->secsiz *= 2;\ erealloc(iop->secbuf,char *,iop->secsiz,"get");\ }\ last = iop->secbuf + used;\ start = iop->secbuf;\ memcpy(last, iop->off, len);\ last += len;\ iop->cnt = read(iop->fd, iop->buf, iop->size);\ if (iop->cnt < 0)\ return iop->cnt;\ end_data = iop->buf + iop->cnt;\ iop->off = bp = iop->buf; #define DO_END_OF_DATA iop->cnt = read(iop->fd, end_data, end_buf - end_data);\ if (iop->cnt < 0)\ return iop->cnt;\ end_data += iop->cnt;\ if (iop->cnt == 0)\ break;\ iop->cnt = end_data - iop->buf; static int get_a_record(res, iop) char **res; IOBUF *iop; { register char *end_data; register char *end_buf; char *start; register char *bp; register char *last; int len, used; register char rs = get_rs(); if (iop->cnt < 0) return iop->cnt; if ((iop->flag & IOP_IS_TTY) && output_is_tty) fflush(stdout); end_data = iop->buf + iop->cnt; if (iop->off >= end_data) { iop->cnt = read(iop->fd, iop->buf, iop->size); if (iop->cnt <= 0) return iop->cnt = EOF; end_data = iop->buf + iop->cnt; iop->off = iop->buf; } last = start = bp = iop->off; end_buf = iop->buf + iop->size; if (rs == 0) { while (!(*bp == '\n' && bp != iop->buf && bp[-1] == '\n')) { if (++bp == end_buf) { DO_END_OF_BUF } if (bp == end_data) { DO_END_OF_DATA } } if (*bp == '\n' && bp != iop->off && bp[-1] == '\n') { int tmp = 0; /* allow for more than two newlines */ while (*bp == '\n') { tmp++; if (++bp == end_buf) { DO_END_OF_BUF } if (bp == end_data) { DO_END_OF_DATA } } iop->off = bp; bp -= 1 + tmp; } else if (bp != iop->buf && bp[-1] != '\n') { warning("record not terminated"); iop->off = bp + 2; } else { bp--; iop->off = bp + 2; } } else { while (*bp++ != rs) { if (bp == end_buf) { DO_END_OF_BUF } if (bp == end_data) { DO_END_OF_DATA } } if (*--bp != rs) { warning("record not terminated"); bp++; } iop->off = bp + 1; } if (start == iop->secbuf) { len = bp - iop->buf; if (len > 0) { used = last - start; while (len + used > iop->secsiz) { iop->secsiz *= 2; erealloc(iop->secbuf,char *,iop->secsiz,"get2"); } last = iop->secbuf + used; start = iop->secbuf; memcpy(last, iop->buf, len); last += len; } } else last = bp; *last = '\0'; *res = start; return last - start; } NODE * do_getline(tree) NODE *tree; { struct redirect *rp; IOBUF *iop; int cnt; NODE **lhs; int redir_error = 0; if (tree->rnode == NULL) { /* no redirection */ iop = nextfile(); if (iop == NULL) /* end of input */ return tmp_number((AWKNUM) 0.0); } else { rp = redirect(tree->rnode, &redir_error); if (rp == NULL && redir_error) /* failed redirect */ return tmp_number((AWKNUM) -1.0); iop = rp->iop; getline_redirect++; } if (tree->lnode == NULL) { /* no optional var. -- read in $0 */ if (inrec(iop) != 0) { getline_redirect = 0; return tmp_number((AWKNUM) 0.0); } } else { /* read in a named variable */ char *s = NULL; lhs = get_lhs(tree->lnode, 1); cnt = get_a_record(&s, iop); if (!getline_redirect) { assign_number(&NR_node->var_value, NR_node->var_value->numbr + 1.0); assign_number(&FNR_node->var_value, FNR_node->var_value->numbr + 1.0); } if (cnt == EOF) { getline_redirect = 0; free(s); return tmp_number((AWKNUM) 0.0); } *lhs = make_string(s, strlen(s)); do_deref(); /* we may have to regenerate $0 here! */ if (field_num == 0) set_record(fields_arr[0]->stptr, fields_arr[0]->stlen); field_num = -1; } getline_redirect = 0; return tmp_number((AWKNUM) 1.0); } gawk-2.11/field.c 644 11660 0 24473 4527633572 12044 0ustar hackwheel/* * field.c - routines for dealing with fields and record parsing */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" extern void assoc_clear(); extern int a_get_three(); extern int get_rs(); static char *get_fs(); static int re_split(); static int parse_fields(); static void set_element(); char *line_buf = NULL; /* holds current input line */ static char *parse_extent; /* marks where to restart parse of record */ static int parse_high_water=0; /* field number that we have parsed so far */ static char f_empty[] = ""; static char *save_fs = " "; /* save current value of FS when line is read, * to be used in deferred parsing */ NODE **fields_arr; /* array of pointers to the field nodes */ NODE node0; /* node for $0 which never gets free'd */ int node0_valid = 1; /* $(>0) has not been changed yet */ void init_fields() { emalloc(fields_arr, NODE **, sizeof(NODE *), "init_fields"); node0.type = Node_val; node0.stref = 0; node0.stptr = ""; node0.flags = (STR|PERM); /* never free buf */ fields_arr[0] = &node0; } /* * Danger! Must only be called for fields we know have just been blanked, or * fields we know don't exist yet. */ /*ARGSUSED*/ static void set_field(num, str, len, dummy) int num; char *str; int len; NODE *dummy; /* not used -- just to make interface same as set_element */ { NODE *n; int t; static int nf_high_water = 0; if (num > nf_high_water) { erealloc(fields_arr, NODE **, (num + 1) * sizeof(NODE *), "set_field"); nf_high_water = num; } /* fill in fields that don't exist */ for (t = parse_high_water + 1; t < num; t++) fields_arr[t] = Nnull_string; n = make_string(str, len); (void) force_number(n); fields_arr[num] = n; parse_high_water = num; } /* Someone assigned a value to $(something). Fix up $0 to be right */ static void rebuild_record() { register int tlen; register NODE *tmp; NODE *ofs; char *ops; register char *cops; register NODE **ptr; register int ofslen; tlen = 0; ofs = force_string(OFS_node->var_value); ofslen = ofs->stlen; ptr = &fields_arr[parse_high_water]; while (ptr > &fields_arr[0]) { tmp = force_string(*ptr); tlen += tmp->stlen; ptr--; } tlen += (parse_high_water - 1) * ofslen; emalloc(ops, char *, tlen + 1, "fix_fields"); cops = ops; ops[0] = '\0'; for (ptr = &fields_arr[1]; ptr <= &fields_arr[parse_high_water]; ptr++) { tmp = *ptr; if (tmp->stlen == 1) *cops++ = tmp->stptr[0]; else if (tmp->stlen != 0) { memcpy(cops, tmp->stptr, tmp->stlen); cops += tmp->stlen; } if (ptr != &fields_arr[parse_high_water]) { if (ofslen == 1) *cops++ = ofs->stptr[0]; else if (ofslen != 0) { memcpy(cops, ofs->stptr, ofslen); cops += ofslen; } } } tmp = make_string(ops, tlen); free(ops); deref = fields_arr[0]; do_deref(); fields_arr[0] = tmp; } /* * setup $0, but defer parsing rest of line until reference is made to $(>0) * or to NF. At that point, parse only as much as necessary. */ void set_record(buf, cnt) char *buf; int cnt; { register int i; assign_number(&NF_node->var_value, (AWKNUM)-1); for (i = 1; i <= parse_high_water; i++) { deref = fields_arr[i]; do_deref(); } parse_high_water = 0; node0_valid = 1; if (buf == line_buf) { deref = fields_arr[0]; do_deref(); save_fs = get_fs(); node0.type = Node_val; node0.stptr = buf; node0.stlen = cnt; node0.stref = 1; node0.flags = (STR|PERM); /* never free buf */ fields_arr[0] = &node0; } } NODE ** get_field(num, assign) int num; int assign; /* this field is on the LHS of an assign */ { int n; /* * if requesting whole line but some other field has been altered, * then the whole line must be rebuilt */ if (num == 0 && (node0_valid == 0 || assign)) { /* first, parse remainder of input record */ if (NF_node->var_value->numbr == -1) { if (parse_high_water == 0) parse_extent = node0.stptr; n = parse_fields(HUGE-1, &parse_extent, node0.stlen - (parse_extent - node0.stptr), save_fs, set_field, (NODE *)NULL); assign_number(&NF_node->var_value, (AWKNUM)n); } if (node0_valid == 0) rebuild_record(); return &fields_arr[0]; } if (num > 0 && assign) node0_valid = 0; if (num <= parse_high_water) /* we have already parsed this field */ return &fields_arr[num]; if (parse_high_water == 0 && num > 0) /* starting at the beginning */ parse_extent = fields_arr[0]->stptr; /* * parse up to num fields, calling set_field() for each, and saving * in parse_extent the point where the parse left off */ n = parse_fields(num, &parse_extent, fields_arr[0]->stlen - (parse_extent-fields_arr[0]->stptr), save_fs, set_field, (NODE *)NULL); if (num == HUGE-1) num = n; if (n < num) { /* requested field number beyond end of record; * set_field will just extend the number of fields, * with empty fields */ set_field(num, f_empty, 0, (NODE *) NULL); /* * if this field is onthe LHS of an assignment, then we want to * set NF to this value, below */ if (assign) n = num; } /* * if we reached the end of the record, set NF to the number of fields * so far. Note that num might actually refer to a field that * is beyond the end of the record, but we won't set NF to that value at * this point, since this is only a reference to the field and NF * only gets set if the field is assigned to -- in this case n has * been set to num above */ if (*parse_extent == '\0') assign_number(&NF_node->var_value, (AWKNUM)n); return &fields_arr[num]; } /* * this is called both from get_field() and from do_split() */ static int parse_fields(up_to, buf, len, fs, set, n) int up_to; /* parse only up to this field number */ char **buf; /* on input: string to parse; on output: point to start next */ int len; register char *fs; void (*set) (); /* routine to set the value of the parsed field */ NODE *n; { char *s = *buf; register char *field; register char *scan; register char *end = s + len; int NF = parse_high_water; char rs = get_rs(); if (up_to == HUGE) NF = 0; if (*fs && *(fs + 1) != '\0') { /* fs is a regexp */ struct re_registers reregs; scan = s; if (rs == 0 && STREQ(FS_node->var_value->stptr, " ")) { while ((*scan == '\n' || *scan == ' ' || *scan == '\t') && scan < end) scan++; } s = scan; while (scan < end && re_split(scan, (int)(end - scan), fs, &reregs) != -1 && NF < up_to) { if (reregs.end[0] == 0) { /* null match */ scan++; if (scan == end) { (*set)(++NF, s, scan - s, n); up_to = NF; break; } continue; } (*set)(++NF, s, scan - s + reregs.start[0], n); scan += reregs.end[0]; s = scan; } if (NF != up_to && scan <= end) { if (!(rs == 0 && scan == end)) { (*set)(++NF, scan, (int)(end - scan), n); scan = end; } } *buf = scan; return (NF); } for (scan = s; scan < end && NF < up_to; scan++) { /* * special case: fs is single space, strip leading * whitespace */ if (*fs == ' ') { while ((*scan == ' ' || *scan == '\t') && scan < end) scan++; if (scan >= end) break; } field = scan; if (*fs == ' ') while (*scan != ' ' && *scan != '\t' && scan < end) scan++; else { while (*scan != *fs && scan < end) scan++; if (rs && scan == end-1 && *scan == *fs) { (*set)(++NF, field, (int)(scan - field), n); field = scan; } } (*set)(++NF, field, (int)(scan - field), n); if (scan == end) break; } *buf = scan; return NF; } static int re_split(buf, len, fs, reregsp) char *buf, *fs; int len; struct re_registers *reregsp; { typedef struct re_pattern_buffer RPAT; static RPAT *rp; static char *last_fs = NULL; if ((last_fs != NULL && !STREQ(fs, last_fs)) || (rp && ! strict && ((IGNORECASE_node->var_value->numbr != 0) ^ (rp->translate != NULL)))) { /* fs has changed or IGNORECASE has changed */ free(rp->buffer); free(rp->fastmap); free((char *) rp); free(last_fs); last_fs = NULL; } if (last_fs == NULL) { /* first time */ emalloc(rp, RPAT *, sizeof(RPAT), "re_split"); memset((char *) rp, 0, sizeof(RPAT)); emalloc(rp->buffer, char *, 8, "re_split"); rp->allocated = 8; emalloc(rp->fastmap, char *, 256, "re_split"); emalloc(last_fs, char *, strlen(fs) + 1, "re_split"); (void) strcpy(last_fs, fs); if (! strict && IGNORECASE_node->var_value->numbr != 0.0) rp->translate = casetable; else rp->translate = NULL; if (re_compile_pattern(fs, strlen(fs), rp) != NULL) fatal("illegal regular expression for FS: `%s'", fs); } return re_search(rp, buf, len, 0, len, reregsp); } NODE * do_split(tree) NODE *tree; { NODE *t1, *t2, *t3; register char *splitc; char *s; NODE *n; if (a_get_three(tree, &t1, &t2, &t3) < 3) splitc = get_fs(); else splitc = force_string(t3)->stptr; n = t2; if (t2->type == Node_param_list) n = stack_ptr[t2->param_cnt]; if (n->type != Node_var && n->type != Node_var_array) fatal("second argument of split is not a variable"); assoc_clear(n); tree = force_string(t1); s = tree->stptr; return tmp_number((AWKNUM) parse_fields(HUGE, &s, tree->stlen, splitc, set_element, n)); } static char * get_fs() { register NODE *tmp; static char buf[10]; tmp = force_string(FS_node->var_value); if (get_rs() == 0) { if (tmp->stlen == 1) { if (tmp->stptr[0] == ' ') (void) strcpy(buf, "[ \n]+"); else sprintf(buf, "[%c\n]", tmp->stptr[0]); } else if (tmp->stlen == 0) { buf[0] = '\n'; buf[1] = '\0'; } else return tmp->stptr; return buf; } return tmp->stptr; } static void set_element(num, s, len, n) int num; char *s; int len; NODE *n; { *assoc_lookup(n, tmp_number((AWKNUM) (num))) = make_string(s, len); } gawk-2.11/array.c 644 11660 0 13732 4527633560 12070 0ustar hackwheel/* * array.c - routines for associative arrays. */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" #ifdef DONTDEF int primes[] = {31, 61, 127, 257, 509, 1021, 2053, 4099, 8191, 16381}; #endif #define ASSOC_HASHSIZE 127 #define STIR_BITS(n) ((n) << 5 | (((n) >> 27) & 0x1f)) #define HASHSTEP(old, c) ((old << 1) + c) #define MAKE_POS(v) (v & ~0x80000000) /* make number positive */ NODE * concat_exp(tree) NODE *tree; { NODE *r; char *str; char *s; unsigned len; int offset; int subseplen; char *subsep; if (tree->type != Node_expression_list) return force_string(tree_eval(tree)); r = force_string(tree_eval(tree->lnode)); if (tree->rnode == NULL) return r; subseplen = SUBSEP_node->lnode->stlen; subsep = SUBSEP_node->lnode->stptr; len = r->stlen + subseplen + 1; emalloc(str, char *, len, "concat_exp"); memcpy(str, r->stptr, r->stlen+1); s = str + r->stlen; free_temp(r); tree = tree->rnode; while (tree) { if (subseplen == 1) *s++ = *subsep; else { memcpy(s, subsep, subseplen+1); s += subseplen; } r = force_string(tree_eval(tree->lnode)); len += r->stlen + subseplen; offset = s - str; erealloc(str, char *, len, "concat_exp"); s = str + offset; memcpy(s, r->stptr, r->stlen+1); s += r->stlen; free_temp(r); tree = tree->rnode; } r = tmp_string(str, s - str); free(str); return r; } /* Flush all the values in symbol[] before doing a split() */ void assoc_clear(symbol) NODE *symbol; { int i; NODE *bucket, *next; if (symbol->var_array == 0) return; for (i = 0; i < ASSOC_HASHSIZE; i++) { for (bucket = symbol->var_array[i]; bucket; bucket = next) { next = bucket->ahnext; deref = bucket->ahname; do_deref(); deref = bucket->ahvalue; do_deref(); freenode(bucket); } symbol->var_array[i] = 0; } } /* * calculate the hash function of the string subs, also returning in *typtr * the type (string or number) */ static int hash_calc(subs) NODE *subs; { register int hash1 = 0, i; subs = force_string(subs); for (i = 0; i < subs->stlen; i++) hash1 = HASHSTEP(hash1, subs->stptr[i]); hash1 = MAKE_POS(STIR_BITS((int) hash1)) % ASSOC_HASHSIZE; return (hash1); } /* * locate symbol[subs], given hash of subs and type */ static NODE * /* NULL if not found */ assoc_find(symbol, subs, hash1) NODE *symbol, *subs; int hash1; { register NODE *bucket; for (bucket = symbol->var_array[hash1]; bucket; bucket = bucket->ahnext) { if (cmp_nodes(bucket->ahname, subs)) continue; return bucket; } return NULL; } /* * test whether the array element symbol[subs] exists or not */ int in_array(symbol, subs) NODE *symbol, *subs; { register int hash1; if (symbol->type == Node_param_list) symbol = stack_ptr[symbol->param_cnt]; if (symbol->var_array == 0) return 0; subs = concat_exp(subs); hash1 = hash_calc(subs); if (assoc_find(symbol, subs, hash1) == NULL) { free_temp(subs); return 0; } else { free_temp(subs); return 1; } } /* * SYMBOL is the address of the node (or other pointer) being dereferenced. * SUBS is a number or string used as the subscript. * * Find SYMBOL[SUBS] in the assoc array. Install it with value "" if it * isn't there. Returns a pointer ala get_lhs to where its value is stored */ NODE ** assoc_lookup(symbol, subs) NODE *symbol, *subs; { register int hash1, i; register NODE *bucket; hash1 = hash_calc(subs); if (symbol->var_array == 0) { /* this table really should grow * dynamically */ emalloc(symbol->var_array, NODE **, (sizeof(NODE *) * ASSOC_HASHSIZE), "assoc_lookup"); for (i = 0; i < ASSOC_HASHSIZE; i++) symbol->var_array[i] = 0; symbol->type = Node_var_array; } else { bucket = assoc_find(symbol, subs, hash1); if (bucket != NULL) { free_temp(subs); return &(bucket->ahvalue); } } bucket = newnode(Node_ahash); bucket->ahname = dupnode(subs); bucket->ahvalue = Nnull_string; bucket->ahnext = symbol->var_array[hash1]; symbol->var_array[hash1] = bucket; return &(bucket->ahvalue); } void do_delete(symbol, tree) NODE *symbol, *tree; { register int hash1; register NODE *bucket, *last; NODE *subs; if (symbol->var_array == 0) return; subs = concat_exp(tree); hash1 = hash_calc(subs); last = NULL; for (bucket = symbol->var_array[hash1]; bucket; last = bucket, bucket = bucket->ahnext) if (cmp_nodes(bucket->ahname, subs) == 0) break; free_temp(subs); if (bucket == NULL) return; if (last) last->ahnext = bucket->ahnext; else symbol->var_array[hash1] = bucket->ahnext; deref = bucket->ahname; do_deref(); deref = bucket->ahvalue; do_deref(); freenode(bucket); } struct search * assoc_scan(symbol) NODE *symbol; { struct search *lookat; if (!symbol->var_array) return 0; emalloc(lookat, struct search *, sizeof(struct search), "assoc_scan"); lookat->numleft = ASSOC_HASHSIZE; lookat->arr_ptr = symbol->var_array; lookat->bucket = symbol->var_array[0]; return assoc_next(lookat); } struct search * assoc_next(lookat) struct search *lookat; { for (; lookat->numleft; lookat->numleft--) { while (lookat->bucket != 0) { lookat->retval = lookat->bucket->ahname; lookat->bucket = lookat->bucket->ahnext; return lookat; } lookat->bucket = *++(lookat->arr_ptr); } free((char *) lookat); return 0; } gawk-2.11/node.c 644 11660 0 14246 4527633615 11701 0ustar hackwheel/* * node.c -- routines for node management */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "awk.h" extern double strtod(); /* * We can't dereference a variable until after we've given it its new value. * This variable points to the value we have to free up */ NODE *deref; AWKNUM r_force_number(n) NODE *n; { char *ptr; #ifdef DEBUG if (n == NULL) cant_happen(); if (n->type != Node_val) cant_happen(); if(n->flags == 0) cant_happen(); if (n->flags & NUM) return n->numbr; #endif if (n->stlen == 0) n->numbr = 0.0; else if (n->stlen == 1) { if (isdigit(n->stptr[0])) { n->numbr = n->stptr[0] - '0'; n->flags |= NUMERIC; } else n->numbr = 0.0; } else { errno = 0; n->numbr = (AWKNUM) strtod(n->stptr, &ptr); /* the following >= should be ==, but for SunOS 3.5 strtod() */ if (errno == 0 && ptr >= n->stptr + n->stlen) n->flags |= NUMERIC; } n->flags |= NUM; return n->numbr; } /* * the following lookup table is used as an optimization in force_string * (more complicated) variations on this theme didn't seem to pay off, but * systematic testing might be in order at some point */ static char *values[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", }; #define NVAL (sizeof(values)/sizeof(values[0])) NODE * r_force_string(s) NODE *s; { char buf[128]; char *fmt; long num; char *sp = buf; #ifdef DEBUG if (s == NULL) cant_happen(); if (s->type != Node_val) cant_happen(); if (s->flags & STR) return s; if (!(s->flags & NUM)) cant_happen(); if (s->stref != 0) cant_happen(); #endif s->flags |= STR; /* should check validity of user supplied OFMT */ fmt = OFMT_node->var_value->stptr; if ((num = s->numbr) == s->numbr) { /* integral value */ if (num < NVAL && num >= 0) { sp = values[num]; s->stlen = 1; } else { (void) sprintf(sp, "%ld", num); s->stlen = strlen(sp); } } else { (void) sprintf(sp, fmt, s->numbr); s->stlen = strlen(sp); } s->stref = 1; emalloc(s->stptr, char *, s->stlen + 1, "force_string"); memcpy(s->stptr, sp, s->stlen+1); return s; } /* * Duplicate a node. (For strings, "duplicate" means crank up the * reference count.) */ NODE * dupnode(n) NODE *n; { register NODE *r; if (n->flags & TEMP) { n->flags &= ~TEMP; n->flags |= MALLOC; return n; } if ((n->flags & (MALLOC|STR)) == (MALLOC|STR)) { if (n->stref < 255) n->stref++; return n; } r = newnode(Node_illegal); *r = *n; r->flags &= ~(PERM|TEMP); r->flags |= MALLOC; if (n->type == Node_val && (n->flags & STR)) { r->stref = 1; emalloc(r->stptr, char *, r->stlen + 1, "dupnode"); memcpy(r->stptr, n->stptr, r->stlen+1); } return r; } /* this allocates a node with defined numbr */ NODE * make_number(x) AWKNUM x; { register NODE *r; r = newnode(Node_val); r->numbr = x; r->flags |= (NUM|NUMERIC); r->stref = 0; return r; } /* * This creates temporary nodes. They go away quite quickly, so don't use * them for anything important */ NODE * tmp_number(x) AWKNUM x; { NODE *r; r = make_number(x); r->flags |= TEMP; return r; } /* * Make a string node. */ NODE * make_str_node(s, len, scan) char *s; int len; int scan; { register NODE *r; char *pf; register char *pt; register int c; register char *end; r = newnode(Node_val); emalloc(r->stptr, char *, len + 1, s); memcpy(r->stptr, s, len); r->stptr[len] = '\0'; end = &(r->stptr[len]); if (scan) { /* scan for escape sequences */ for (pf = pt = r->stptr; pf < end;) { c = *pf++; if (c == '\\') { c = parse_escape(&pf); if (c < 0) cant_happen(); *pt++ = c; } else *pt++ = c; } len = pt - r->stptr; erealloc(r->stptr, char *, len + 1, "make_str_node"); r->stptr[len] = '\0'; r->flags |= PERM; } r->stlen = len; r->stref = 1; r->flags |= (STR|MALLOC); return r; } /* Read the warning under tmp_number */ NODE * tmp_string(s, len) char *s; int len; { register NODE *r; r = make_string(s, len); r->flags |= TEMP; return r; } #define NODECHUNK 100 static NODE *nextfree = NULL; NODE * newnode(ty) NODETYPE ty; { NODE *it; NODE *np; #ifdef MPROF emalloc(it, NODE *, sizeof(NODE), "newnode"); #else if (nextfree == NULL) { /* get more nodes and initialize list */ emalloc(nextfree, NODE *, NODECHUNK * sizeof(NODE), "newnode"); for (np = nextfree; np < &nextfree[NODECHUNK - 1]; np++) np->nextp = np + 1; np->nextp = NULL; } /* get head of freelist */ it = nextfree; nextfree = nextfree->nextp; #endif it->type = ty; it->flags = MALLOC; #ifdef MEMDEBUG fprintf(stderr, "node: new: %0x\n", it); #endif return it; } void freenode(it) NODE *it; { #ifdef DEBUG NODE *nf; #endif #ifdef MEMDEBUG fprintf(stderr, "node: free: %0x\n", it); #endif #ifdef MPROF free((char *) it); #else #ifdef DEBUG for (nf = nextfree; nf; nf = nf->nextp) if (nf == it) fatal("attempt to free free node"); #endif /* add it to head of freelist */ it->nextp = nextfree; nextfree = it; #endif } #ifdef DEBUG pf() { NODE *nf = nextfree; while (nf != NULL) { fprintf(stderr, "%0x ", nf); nf = nf->nextp; } } #endif void do_deref() { if (deref == NULL) return; if (deref->flags & PERM) { deref = 0; return; } if ((deref->flags & MALLOC) || (deref->flags & TEMP)) { deref->flags &= ~TEMP; if (deref->flags & STR) { if (deref->stref > 1 && deref->stref != 255) { deref->stref--; deref = 0; return; } free(deref->stptr); } freenode(deref); } deref = 0; } gawk-2.11/missing.c 644 11660 0 2340 4527633611 12371 0ustar hackwheel#ifdef MSDOS #define BCOPY_MISSING #define STRCASE_MISSING #define BLKSIZE_MISSING #define SPRINTF_INT #define RANDOM_MISSING #define GETOPT_MISSING #endif #ifdef DUP2_MISSING #include "missing.d/dup2.c" #endif /* DUP2_MISSING */ #ifdef GCVT_MISSING #include "missing.d/gcvt.c" #endif /* GCVT_MISSING */ #ifdef GETOPT_MISSING #include "missing.d/getopt.c" #endif /* GETOPT_MISSING */ #ifdef MEMCMP_MISSING #include "missing.d/memcmp.c" #endif /* MEMCMP_MISSING */ #ifdef MEMCPY_MISSING #include "missing.d/memcpy.c" #endif /* MEMCPY_MISSING */ #ifdef MEMSET_MISSING #include "missing.d/memset.c" #endif /* MEMSET_MISSING */ #ifdef RANDOM_MISSING #include "missing.d/random.c" #endif /* RANDOM_MISSING */ #ifdef STRCASE_MISSING #include "missing.d/strcase.c" #endif /* STRCASE_MISSING */ #ifdef STRCHR_MISSING #include "missing.d/strchr.c" #endif /* STRCHR_MISSING */ #ifdef STRERROR_MISSING #include "missing.d/strerror.c" #endif /* STRERROR_MISSING */ #ifdef STRTOD_MISSING #include "missing.d/strtod.c" #endif /* STRTOD_MISSING */ #ifdef TMPNAM_MISSING #include "missing.d/tmpnam.c" #endif /* TMPNAM_MISSING */ #if defined(VPRINTF_MISSING) && defined(BSDSTDIO) #include "missing.d/vprintf.c" #endif /* VPRINTF_MISSING && BSDSTDIO */ gawk-2.11/awk.tab.c 644 11660 0 263270 4521144045 12312 0ustar hackwheel /* A Bison parser, made from awk.y */ #define FUNC_CALL 258 #define NAME 259 #define REGEXP 260 #define ERROR 261 #define NUMBER 262 #define YSTRING 263 #define RELOP 264 #define APPEND_OP 265 #define ASSIGNOP 266 #define MATCHOP 267 #define NEWLINE 268 #define CONCAT_OP 269 #define LEX_BEGIN 270 #define LEX_END 271 #define LEX_IF 272 #define LEX_ELSE 273 #define LEX_RETURN 274 #define LEX_DELETE 275 #define LEX_WHILE 276 #define LEX_DO 277 #define LEX_FOR 278 #define LEX_BREAK 279 #define LEX_CONTINUE 280 #define LEX_PRINT 281 #define LEX_PRINTF 282 #define LEX_NEXT 283 #define LEX_EXIT 284 #define LEX_FUNCTION 285 #define LEX_GETLINE 286 #define LEX_IN 287 #define LEX_AND 288 #define LEX_OR 289 #define INCREMENT 290 #define DECREMENT 291 #define LEX_BUILTIN 292 #define LEX_LENGTH 293 #define UNARY 294 #line 26 "awk.y" #ifdef DEBUG #define YYDEBUG 12 #endif #include "awk.h" /* * This line is necessary since the Bison parser skeleton uses bcopy. * Systems without memcpy should use -DMEMCPY_MISSING, per the Makefile. * It should not hurt anything if Yacc is being used instead of Bison. */ #define bcopy(s,d,n) memcpy((d),(s),(n)) extern void msg(); extern struct re_pattern_buffer *mk_re_parse(); NODE *node(); NODE *lookup(); NODE *install(); static NODE *snode(); static NODE *mkrangenode(); static FILE *pathopen(); static NODE *make_for_loop(); static NODE *append_right(); static void func_install(); static NODE *make_param(); static int hashf(); static void pop_params(); static void pop_var(); static int yylex (); static void yyerror(); static int want_regexp; /* lexical scanning kludge */ static int want_assign; /* lexical scanning kludge */ static int can_return; /* lexical scanning kludge */ static int io_allowed = 1; /* lexical scanning kludge */ static int lineno = 1; /* for error msgs */ static char *lexptr; /* pointer to next char during parsing */ static char *lexptr_begin; /* keep track of where we were for error msgs */ static int curinfile = -1; /* index into sourcefiles[] */ static int param_counter; NODE *variables[HASHSIZE]; extern int errcount; extern NODE *begin_block; extern NODE *end_block; #line 77 "awk.y" typedef union { long lval; AWKNUM fval; NODE *nodeval; NODETYPE nodetypeval; char *sval; NODE *(*ptrval)(); } YYSTYPE; #ifndef YYLTYPE typedef struct yyltype { int timestamp; int first_line; int first_column; int last_line; int last_column; char *text; } yyltype; #define YYLTYPE yyltype #endif #define YYACCEPT return(0) #define YYABORT return(1) #define YYERROR goto yyerrlab #include #ifndef __STDC__ #define const #endif #define YYFINAL 298 #define YYFLAG -32768 #define YYNTBASE 61 #define YYTRANSLATE(x) ((unsigned)(x) <= 294 ? yytranslate[x] : 105) static const char yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 49, 2, 2, 52, 48, 2, 2, 53, 54, 46, 44, 60, 45, 2, 47, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 40, 59, 41, 2, 42, 39, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 55, 2, 56, 51, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 57, 43, 58, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 50 }; static const short yyrline[] = { 0, 136, 141, 149, 165, 166, 170, 172, 186, 188, 202, 208, 214, 216, 218, 220, 229, 231, 236, 240, 248, 257, 259, 268, 270, 281, 286, 291, 293, 301, 303, 308, 310, 316, 318, 320, 322, 324, 326, 328, 333, 337, 342, 345, 348, 350, 352, 355, 356, 358, 360, 362, 364, 369, 371, 376, 381, 388, 390, 395, 397, 402, 404, 409, 411, 413, 415, 420, 422, 427, 429, 431, 433, 435, 441, 443, 448, 450, 455, 457, 463, 465, 467, 469, 474, 476, 481, 483, 489, 491, 493, 495, 500, 503, 504, 506, 511, 520, 522, 524, 526, 528, 530, 532, 534, 536, 538, 540, 542, 547, 550, 551, 553, 555, 564, 566, 568, 570, 572, 574, 576, 578, 583, 585, 587, 589, 591, 593, 597, 599, 601, 603, 605, 607, 609, 613, 615, 617, 619, 621, 623, 625, 627, 632, 634, 639, 641, 643, 648, 652, 656, 660, 661, 665, 668 }; static const char * const yytname[] = { 0, "error","$illegal.","FUNC_CALL","NAME","REGEXP","ERROR","NUMBER","YSTRING","RELOP","APPEND_OP", "ASSIGNOP","MATCHOP","NEWLINE","CONCAT_OP","LEX_BEGIN","LEX_END","LEX_IF","LEX_ELSE","LEX_RETURN","LEX_DELETE", "LEX_WHILE","LEX_DO","LEX_FOR","LEX_BREAK","LEX_CONTINUE","LEX_PRINT","LEX_PRINTF","LEX_NEXT","LEX_EXIT","LEX_FUNCTION", "LEX_GETLINE","LEX_IN","LEX_AND","LEX_OR","INCREMENT","DECREMENT","LEX_BUILTIN","LEX_LENGTH","'?'","':'", "'<'","'>'","'|'","'+'","'-'","'*'","'/'","'%'","'!'","UNARY", "'^'","'$'","'('","')'","'['","']'","'{'","'}'","';'","','", "start" }; static const short yyr1[] = { 0, 61, 62, 62, 62, 62, 64, 63, 65, 63, 63, 63, 63, 63, 63, 63, 66, 66, 68, 67, 69, 70, 70, 72, 71, 73, 73, 74, 74, 74, 74, 75, 75, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 77, 76, 76, 78, 76, 76, 76, 79, 79, 80, 80, 81, 81, 82, 82, 83, 83, 84, 84, 84, 84, 85, 85, 86, 86, 86, 86, 86, 87, 87, 88, 88, 89, 89, 89, 89, 89, 89, 90, 90, 91, 91, 91, 91, 91, 91, 93, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 95, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 97, 97, 98, 98, 98, 99, 100, 101, 102, 102, 103, 104 }; static const short yyr2[] = { 0, 3, 1, 2, 1, 2, 0, 3, 0, 3, 2, 2, 2, 1, 2, 2, 1, 1, 0, 7, 3, 1, 3, 0, 4, 3, 4, 1, 2, 1, 2, 1, 2, 2, 2, 3, 1, 6, 8, 8, 10, 9, 2, 2, 6, 4, 0, 3, 3, 0, 4, 6, 2, 1, 1, 6, 9, 1, 2, 0, 1, 0, 2, 0, 2, 2, 2, 0, 1, 1, 3, 1, 2, 3, 0, 1, 0, 1, 1, 3, 1, 2, 3, 3, 0, 1, 1, 3, 1, 2, 3, 3, 0, 4, 5, 4, 3, 3, 3, 3, 1, 2, 3, 3, 3, 3, 5, 1, 2, 0, 4, 3, 3, 3, 1, 2, 3, 3, 3, 5, 1, 2, 2, 3, 4, 4, 1, 4, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 3, 3, 3, 2, 2, 0, 1, 1, 4, 2, 2, 2, 1, 0, 1, 1, 2 }; static const short yydefact[] = { 59, 57, 60, 0, 58, 4, 0, 145, 133, 134, 6, 8, 18, 143, 0, 0, 0, 126, 0, 0, 23, 0, 0, 0, 59, 0, 2, 0, 0, 100, 13, 21, 107, 132, 0, 0, 0, 153, 0, 10, 31, 59, 0, 11, 0, 61, 144, 128, 129, 0, 0, 0, 0, 142, 132, 141, 0, 101, 122, 147, 88, 0, 86, 148, 5, 3, 1, 15, 0, 12, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 108, 0, 0, 0, 0, 0, 0, 0, 92, 130, 131, 29, 0, 49, 0, 0, 59, 0, 0, 0, 53, 54, 46, 74, 59, 0, 27, 0, 36, 0, 0, 151, 59, 0, 0, 86, 0, 7, 32, 9, 17, 16, 0, 0, 96, 0, 0, 0, 0, 89, 150, 0, 0, 123, 0, 103, 99, 102, 97, 98, 0, 104, 105, 143, 154, 22, 139, 140, 136, 137, 138, 135, 0, 0, 74, 0, 0, 0, 74, 42, 43, 0, 0, 75, 149, 30, 28, 151, 80, 143, 0, 0, 114, 63, 0, 78, 120, 132, 52, 0, 34, 25, 152, 33, 127, 146, 0, 62, 124, 125, 24, 90, 0, 91, 87, 20, 0, 95, 93, 0, 0, 0, 0, 0, 145, 0, 47, 48, 26, 61, 115, 0, 0, 0, 0, 0, 81, 0, 0, 0, 0, 0, 0, 0, 121, 109, 35, 71, 69, 0, 0, 94, 106, 59, 50, 0, 59, 0, 0, 0, 113, 63, 65, 64, 66, 45, 82, 83, 79, 118, 116, 117, 111, 112, 0, 0, 59, 72, 0, 0, 0, 0, 0, 0, 0, 74, 0, 0, 110, 19, 73, 70, 55, 51, 37, 0, 59, 74, 0, 44, 119, 59, 59, 0, 0, 59, 0, 38, 39, 59, 0, 56, 0, 41, 40, 0, 0, 0 }; static const short yydefgoto[] = { 296, 25, 26, 38, 42, 123, 27, 44, 67, 28, 29, 56, 30, 106, 39, 107, 162, 155, 108, 109, 2, 3, 125, 216, 230, 231, 163, 174, 175, 114, 115, 81, 153, 225, 256, 32, 45, 33, 111, 112, 134, 182, 113, 133 }; static const short yypact[] = { 21, -32768, 37, 1020,-32768,-32768, -32, 1,-32768,-32768, 17, 17,-32768, 11, 11, 11, 31, 45, 1757, 1757,-32768, 1738, 1757, 1112, 21, 540,-32768, 13, 40,-32768,-32768, 816, 142, 55, 612, 1092, 1112,-32768, 13,-32768, 37, 21, 13,-32768, 51, 59,-32768,-32768,-32768, 1092, 1092, 1757, 1625, 27, -7, 27, 97,-32768, 27,-32768,-32768, 4, 1225,-32768,-32768,-32768,-32768,-32768, 706,-32768,-32768, 1625, 1625, 100, 1625, 1625, 1625, 1625, 1625, 76, 21, 300, 1625, 1757, 1757, 1757, 1757, 1757, 1757,-32768,-32768, -32768,-32768, 52,-32768, 109, 62, 21, 64, 17, 17, -32768,-32768,-32768, 1625, 21, 659,-32768, 763,-32768, 920, 612, 65, 21, 67, 7, 1324, 25,-32768,-32768,-32768, -32768,-32768, 70, 1757,-32768, 67, 67, 1225, 84, 1625, -32768, 101, 1159,-32768, 659, 1811, 1796,-32768, 1465, 1371, 1277, 1811, 1811, 11,-32768, 1324, -10, -10, 27, 27, 27, 27, 1625, 1625, 1625, 87, 1625, 863, 1672,-32768, -32768, 17, 17, 1324,-32768,-32768,-32768, 65,-32768, 11, 1738, 1112,-32768, 9, 0, 1512, 142, 83,-32768, 659, -32768,-32768,-32768,-32768,-32768,-32768, 8, 142,-32768,-32768, -32768, 1324, 134,-32768, 1324,-32768, 1625,-32768, 1324, 1225, 17, 1112, 1225, 122, -16, 65,-32768,-32768,-32768, 59, -32768, 4, 1625, 1625, 1625, 17, 1691, 1178, 1691, 1691, 140, 1691, 1691, 1691, 939,-32768,-32768,-32768,-32768, 67, 23,-32768, 1324, 21,-32768, 26, 21, 94, 144, 1045, -32768, 9, 1324, 1324, 1324,-32768, 1512,-32768, 1512, 782, 1858,-32768, 1606, 1559, 1418, 1691, 21,-32768, 44, 863, 17, 863, 1625, 67, 973, 1625, 17, 1691, 1512,-32768, -32768,-32768, 131,-32768,-32768, 1225, 21, 1625, 67,-32768, 1512, 21, 21, 863, 67, 21, 863,-32768,-32768, 21, 863,-32768, 863,-32768,-32768, 163, 166,-32768 }; static const short yypgoto[] = {-32768, -32768, 145,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 201, -32768, 78, -54, 12, 225,-32768,-32768,-32768,-32768, 363, 104, -39, -70,-32768,-32768, -152,-32768,-32768, 60, -19, -3,-32768, -83,-32768, 146, -126, 74, 178, -100, 319, 10, 329, -29 }; #define YYLAST 1911 static const short yytable[] = { 31, 217, 82, 201, 61, 130, 168, 206, 130, 228, -77, 181, 229, -77, 135, 7, 239, 117, 198, 213, 62, 35, 31, 43, 258, 176, 130, 130, 90, 91, 1, 110, 116, 116, 1, 196, 85, 86, 87, 36, 70, 88, -77, -77, 210, 271, 116, 116, 272, 128, 4, 214, 215, 1, 121, 122, 36, 180, 131, -77, 80, -85, -67, 22, 80, 110, 89, 80, 136, 137, 24, 139, 140, 141, 142, 143, 37, -68, 88, 146, 227, 186, 261, 80, 49, 80, 80, 46, 47, 48, 90, 91, 54, 54, 226, 54, 54, 24, 50, 37, 124, 164, 129, 110, 138, 154, 69, 144, 110, 126, 127, 160, 161, 156, 279, 157, 118, 159, 90, 91, 120, 131, 179, 187, 37, 54, 285, 192, 63, 66, 195, 191, 110, 193, 247, 249, 250, 251, 232, 253, 254, 255, 202, 238, 252, 119, 218, 263, 264, 282, 199, 200, 164, 212, 203, 110, 164, 54, 54, 54, 54, 54, 54, 297, 53, 55, 298, 58, 59, 62, 65, 241, 267, 269, 207, 208, 0, 110, 209, 0, 0, 34, 178, 236, 145, 281, 83, 84, 85, 86, 87, 0, 0, 88, 233, 0, 0, 58, 54, 116, 0, 158, 259, 34, 0, 68, 34, 0, 0, 165, 243, 244, 245, 235, 0, 0, 34, 184, 46, 0, 34, 0, 57, 0, 0, 0, 0, 0, 246, 147, 148, 149, 150, 151, 152, 0, 0, 265, 0, 0, 0, 0, 0, 0, 46, 54, 0, 0, 0, 0, 178, 0, 0, 0, 177, 0, 0, 110, 0, 110, 276, 0, 0, 164, 0, 0, 0, 0, 0, 0, 188, 0, 0, 274, 0, 164, 0, 0, 0, 280, 0, 110, 0, 0, 110, 0, 0, 0, 110, 0, 110, 178, 178, 178, 178, 0, 178, 178, 178, 178, 0, 0, 0, 0, 7, 0, 0, 8, 9, 173, 0, 0, 0, 0, 0, 0, 0, 58, 0, 0, 0, 178, 177, 178, 178, 178, 0, 178, 178, 178, 178, 167, 0, 0, 0, 14, 15, 0, 260, 41, 41, 262, 178, 178, 18, 19, 0, 20, 0, 21, 0, 0, 22, 23, 0, 178, 0, 41, 0, 0, 167, 270, 0, 177, 177, 177, 177, 0, 177, 177, 177, 177, 211, 40, 40, 0, 0, 173, 0, 0, 132, 284, 0, 204, 0, 0, 287, 288, 0, 0, 291, 40, 0, 177, 293, 177, 177, 177, 0, 177, 177, 177, 177, 0, 0, 167, 0, 0, 0, 0, 0, 0, 0, 0, 177, 177, 0, 0, 173, 173, 173, 173, 0, 173, 173, 173, 173, 177, 41, 41, 0, 0, 0, 185, 0, 0, 0, 0, 0, 41, 0, 183, 0, 0, 0, 189, 190, 0, 173, 0, 173, 173, 173, 0, 173, 173, 173, 173, 0, 0, 0, 0, 40, 40, 0, 0, 0, 0, 0, 173, 173, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 173, 0, 0, 273, 0, 275, 0, 0, 0, 41, 41, 0, 0, 0, 0, 183, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 289, 0, 0, 292, 0, 0, 0, 294, 0, 295, 234, 0, 0, 237, 0, 0, 40, 40, 0, 0, 0, 41, 242, 0, 0, 0, 240, 0, 0, 0, 0, -59, 64, 0, 6, 7, 41, 0, 8, 9, 257, 0, 0, 0, 1, 0, 10, 11, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, 266, 12, 13, 0, 0, 0, 14, 15, 16, 17, 40, 0, 0, 0, 277, 18, 19, 0, 20, 0, 21, 41, 0, 22, 23, 278, 283, 41, 24, 286, 0, 0, 0, 0, 0, 290, 0, 0, 0, 0, 0, 0, 0, 0, 92, 0, 6, 7, 0, 0, 8, 9, 0, 0, 0, 40, 0, 0, 0, 0, 93, 40, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 166, 21, 6, 7, 22, 23, 8, 9, 0, 24, 105, 37, 0, 0, 0, 0, 93, 0, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 92, 21, 6, 7, 22, 23, 8, 9, 0, 24, 105, 37, 0, 0, 0, 0, 93, 0, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 0, 0, 22, 23, 0, 0, 0, 24, 169, 37, 6, 7, 0, 0, 8, 9, 0, -76, 0, 0, -76, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 8, 9, -32768, 0, 0, 170, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, -76, -76, 18, 19, 0, 20, 0, 171, 0, 0, 22, 172, 14, 15, 6, 7, 0, -76, 8, 9, 71, 18, 19, 72, 20, 0, 171, 0, 0, 22, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 74, 75, 14, 15, 16, 17, 76, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 6, 7, 22, 23, 8, 9, 0, 0, 0, 0, 80, 0, 0, 0, 93, 0, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 0, 0, 22, 23, 0, 0, 0, 24, 0, 37, 6, 7, 0, 0, 8, 9, 71, 0, 0, 72, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 8, 9, 0, 0, 0, 13, 73, 74, 75, 14, 15, 16, 17, 76, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 0, 0, 22, 23, 14, 15, 6, 7, 0, 37, 8, 9, 71, 18, 19, 72, 20, 0, 171, 0, 0, 22, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 74, 75, 14, 15, 16, 17, 76, 0, 77, 78, 79, 18, 19, 0, 20, 5, 21, 6, 7, 22, 23, 8, 9, 0, 0, 0, 37, 0, 0, 10, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 12, 13, 8, 9, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 0, 0, 22, 23, 0, 0, 13, 24, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 60, 21, 6, 7, 22, 23, 8, 9, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 6, 7, 0, 0, 8, 9, 0, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 0, 13, 22, 23, -84, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 194, 21, 6, 7, 22, 23, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 0, 6, 7, 0, 0, 8, 9, 0, 0, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 170, 0, 22, 23, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 171, 6, 7, 22, 52, 8, 9, 71, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 74, 75, 14, 15, 16, 17, 76, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 0, 0, 22, 23, 131, 6, 7, 0, 0, 8, 9, 71, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 74, 75, 14, 15, 16, 17, 76, 197, 77, 78, 79, 18, 19, 0, 20, 0, 21, 6, 7, 22, 23, 8, 9, 71, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 74, 75, 14, 15, 16, 17, 76, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 6, 7, 22, 23, 8, 9, 71, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 74, 0, 14, 15, 16, 17, 0, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 6, 7, 22, 23, 8, 9, 219, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 170, 221, 222, 223, 14, 15, 16, 17, 224, 268, 0, 0, 0, 18, 19, 0, 20, 0, 171, 6, 7, 22, 52, 8, 9, 71, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 73, 0, 0, 14, 15, 16, 17, 0, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 6, 7, 22, 23, 8, 9, 219, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 170, 221, 222, 223, 14, 15, 16, 17, 224, 0, 0, 0, 0, 18, 19, 0, 20, 0, 171, 6, 7, 22, 52, 8, 9, 219, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 170, 221, 222, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 171, 6, 7, 22, 52, 8, 9, 219, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 8, 9, 0, 0, 0, 170, 221, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 171, 13, 0, 22, 52, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 6, 205, 22, 23, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 8, 9, 0, 0, 0, 13, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 21, 170, 0, 22, 23, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 171, 6, 7, 22, 52, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 0, 14, 15, 16, 17, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 51, 0, 0, 22, 52, 14, 15, 16, 17, 0, 0, 0, 0, 7, 18, 19, 8, 9, 71, 51, 0,-32768, 22, 52, 0, 0, 0, 0, 7, 0, 0, 8, 9,-32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 15, 0, 0, 0, 0, 77, 78, 79, 18, 19, 0, 20, 0, 21, 14, 15, 22, 23, 0, 0,-32768,-32768,-32768, 18, 19, 0, 20, 0, 21, 0, 7, 22, 23, 8, 9, 219, 0, 0,-32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 15, 0, 0, 0, 0, 0, 0, 0, 18, 19, 0, 20, 0, 171, 0, 0, 22, 52 }; static const short yycheck[] = { 3, 1, 31, 155, 23, 1, 106, 159, 1, 1, 10, 111, 4, 13, 68, 4, 32, 36, 144, 10, 23, 53, 25, 11, 1, 108, 1, 1, 35, 36, 13, 34, 35, 36, 13, 135, 46, 47, 48, 55, 28, 51, 42, 43, 170, 1, 49, 50, 4, 52, 13, 42, 43, 13, 3, 4, 55, 111, 54, 59, 60, 54, 54, 52, 60, 68, 11, 60, 71, 72, 57, 74, 75, 76, 77, 78, 59, 54, 51, 82, 180, 56, 56, 60, 53, 60, 60, 13, 14, 15, 35, 36, 18, 19, 11, 21, 22, 57, 53, 59, 41, 104, 5, 106, 4, 53, 28, 31, 111, 49, 50, 99, 100, 4, 266, 53, 38, 53, 35, 36, 42, 54, 110, 53, 59, 51, 278, 130, 24, 25, 133, 47, 135, 32, 217, 218, 219, 220, 4, 222, 223, 224, 55, 21, 4, 41, 175, 53, 4, 18, 153, 154, 155, 172, 157, 158, 159, 83, 84, 85, 86, 87, 88, 0, 18, 19, 0, 21, 22, 172, 25, 210, 242, 256, 162, 163, -1, 180, 168, -1, -1, 3, 108, 202, 80, 268, 44, 45, 46, 47, 48, -1, -1, 51, 197, -1, -1, 51, 124, 202, -1, 97, 231, 25, -1, 27, 28, -1, -1, 105, 213, 214, 215, 201, -1, -1, 38, 113, 144, -1, 42, -1, 21, -1, -1, -1, -1, -1, 216, 83, 84, 85, 86, 87, 88, -1, -1, 240, -1, -1, -1, -1, -1, -1, 170, 171, -1, -1, -1, -1, 176, -1, -1, -1, 108, -1, -1, 260, -1, 262, 263, -1, -1, 266, -1, -1, -1, -1, -1, -1, 124, -1, -1, 261, -1, 278, -1, -1, -1, 267, -1, 284, -1, -1, 287, -1, -1, -1, 291, -1, 293, 217, 218, 219, 220, -1, 222, 223, 224, 225, -1, -1, -1, -1, 4, -1, -1, 7, 8, 108, -1, -1, -1, -1, -1, -1, -1, 171, -1, -1, -1, 247, 176, 249, 250, 251, -1, 253, 254, 255, 256, 106, -1, -1, -1, 35, 36, -1, 234, 10, 11, 237, 268, 269, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, -1, 281, -1, 28, -1, -1, 135, 257, -1, 217, 218, 219, 220, -1, 222, 223, 224, 225, 171, 10, 11, -1, -1, 176, -1, -1, 61, 277, -1, 158, -1, -1, 282, 283, -1, -1, 286, 28, -1, 247, 290, 249, 250, 251, -1, 253, 254, 255, 256, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, 268, 269, -1, -1, 217, 218, 219, 220, -1, 222, 223, 224, 225, 281, 99, 100, -1, -1, -1, 114, -1, -1, -1, -1, -1, 110, -1, 112, -1, -1, -1, 126, 127, -1, 247, -1, 249, 250, 251, -1, 253, 254, 255, 256, -1, -1, -1, -1, 99, 100, -1, -1, -1, -1, -1, 268, 269, -1, -1, 110, -1, -1, -1, -1, -1, -1, -1, -1, 281, -1, -1, 260, -1, 262, -1, -1, -1, 162, 163, -1, -1, -1, -1, 168, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 284, -1, -1, 287, -1, -1, -1, 291, -1, 293, 200, -1, -1, 203, -1, -1, 162, 163, -1, -1, -1, 201, 212, -1, -1, -1, 206, -1, -1, -1, -1, 0, 1, -1, 3, 4, 216, -1, 7, 8, 230, -1, -1, -1, 13, -1, 15, 16, -1, -1, -1, -1, -1, -1, -1, 201, -1, -1, -1, -1, 240, 30, 31, -1, -1, -1, 35, 36, 37, 38, 216, -1, -1, -1, 264, 44, 45, -1, 47, -1, 49, 261, -1, 52, 53, 265, 276, 267, 57, 279, -1, -1, -1, -1, -1, 285, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 3, 4, -1, -1, 7, 8, -1, -1, -1, 261, -1, -1, -1, -1, 17, 267, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, 1, 49, 3, 4, 52, 53, 7, 8, -1, 57, 58, 59, -1, -1, -1, -1, 17, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, 1, 49, 3, 4, 52, 53, 7, 8, -1, 57, 58, 59, -1, -1, -1, -1, 17, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, -1, -1, -1, 57, 1, 59, 3, 4, -1, -1, 7, 8, -1, 10, -1, -1, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, -1, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, 42, 43, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, 35, 36, 3, 4, -1, 59, 7, 8, 9, 44, 45, 12, 47, -1, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, -1, -1, -1, -1, 60, -1, -1, -1, 17, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, -1, -1, -1, 57, -1, 59, 3, 4, -1, -1, 7, 8, 9, -1, -1, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, 35, 36, 3, 4, -1, 59, 7, 8, 9, 44, 45, 12, 47, -1, 49, -1, -1, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, -1, 47, 1, 49, 3, 4, 52, 53, 7, 8, -1, -1, -1, 59, -1, -1, 15, 16, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 30, 31, 7, 8, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, -1, -1, 31, 57, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, 1, 49, 3, 4, 52, 53, 7, 8, -1, -1, -1, 59, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 3, 4, -1, -1, 7, 8, -1, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, -1, 31, 52, 53, 54, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, 1, 49, 3, 4, 52, 53, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 3, 4, -1, -1, 7, 8, -1, -1, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 31, -1, 52, 53, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, 54, 3, 4, -1, -1, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, -1, 35, 36, 37, 38, -1, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, -1, -1, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, -1, -1, 35, 36, 37, 38, -1, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 32, 33, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, -1, -1, 7, 8, -1, -1, -1, 31, 32, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 31, -1, 52, 53, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, -1, -1, 7, 8, -1, -1, -1, 31, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 31, -1, 52, 53, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, 3, 4, 52, 53, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, -1, -1, 7, 8, -1, -1, -1, -1, -1, -1, -1, 35, 36, 37, 38, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53, 35, 36, 37, 38, -1, -1, -1, -1, 4, 44, 45, 7, 8, 9, 49, -1, 12, 52, 53, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, 36, -1, -1, -1, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, 35, 36, 52, 53, -1, -1, 41, 42, 43, 44, 45, -1, 47, -1, 49, -1, 4, 52, 53, 7, 8, 9, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, 36, -1, -1, -1, -1, -1, -1, -1, 44, 45, -1, 47, -1, 49, -1, -1, 52, 53 }; #define YYPURE 1 /* -*-C-*- Note some compilers choke on comments on `#line' lines. */ #line 3 "bison.simple" /* Skeleton output parser for bison, Copyright (C) 1984 Bob Corbett and Richard Stallman This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) #include #endif /* This is the parser code that is written into each bison parser when the %semantic_parser declaration is not specified in the grammar. It was written by Richard Stallman by simplifying the hairy parser used when %semantic_parser is specified. */ /* Note: there must be only one dollar sign in this file. It is replaced by the list of actions, each action as one case of the switch. */ #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY -2 #define YYEOF 0 #define YYFAIL goto yyerrlab; #define YYACCEPT return(0) #define YYABORT return(1) #define YYERROR goto yyerrlab #define YYTERROR 1 #define YYERRCODE 256 #ifndef YYIMPURE #define YYLEX yylex() #endif #ifndef YYPURE #define YYLEX yylex(&yylval, &yylloc) #endif /* If nonreentrant, generate the variables here */ #ifndef YYIMPURE int yychar; /* the lookahead symbol */ YYSTYPE yylval; /* the semantic value of the */ /* lookahead symbol */ YYLTYPE yylloc; /* location data for the lookahead */ /* symbol */ int yynerrs; /* number of parse errors so far */ #endif /* YYIMPURE */ #if YYDEBUG != 0 int yydebug; /* nonzero means print parse trace */ /* Since this is uninitialized, it does not stop multiple parsers from coexisting. */ #endif /* YYMAXDEPTH indicates the initial size of the parser's stacks */ #ifndef YYMAXDEPTH #define YYMAXDEPTH 200 #endif /* YYMAXLIMIT is the maximum size the stacks can grow to (effective only if the built-in stack extension method is used). */ #ifndef YYMAXLIMIT #define YYMAXLIMIT 10000 #endif #line 90 "bison.simple" int yyparse() { register int yystate; register int yyn; register short *yyssp; register YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyerrstatus; /* number of tokens to shift before error messages enabled */ int yychar1; /* lookahead token as an internal (translated) token number */ short yyssa[YYMAXDEPTH]; /* the state stack */ YYSTYPE yyvsa[YYMAXDEPTH]; /* the semantic value stack */ YYLTYPE yylsa[YYMAXDEPTH]; /* the location stack */ short *yyss = yyssa; /* refer to the stacks thru separate pointers */ YYSTYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */ YYLTYPE *yyls = yylsa; int yymaxdepth = YYMAXDEPTH; #ifndef YYPURE int yychar; YYSTYPE yylval; YYLTYPE yylloc; int yynerrs; #endif YYSTYPE yyval; /* the variable used to return */ /* semantic values from the action */ /* routines */ int yylen; #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Starting parse\n"); #endif yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. */ yyssp = yyss - 1; yyvsp = yyvs; yylsp = yyls; /* Push a new state, which is found in yystate . */ /* In all cases, when you get here, the value and location stacks have just been pushed. so pushing a state here evens the stacks. */ yynewstate: *++yyssp = yystate; if (yyssp >= yyss + yymaxdepth - 1) { /* Give user a chance to reallocate the stack */ /* Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; YYLTYPE *yyls1 = yyls; short *yyss1 = yyss; /* Get the current used size of the three stacks, in elements. */ int size = yyssp - yyss + 1; #ifdef yyoverflow /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. */ yyoverflow("parser stack overflow", &yyss1, size * sizeof (*yyssp), &yyvs1, size * sizeof (*yyvsp), &yyls1, size * sizeof (*yylsp), &yymaxdepth); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; #else /* no yyoverflow */ /* Extend the stack our own way. */ if (yymaxdepth >= YYMAXLIMIT) yyerror("parser stack overflow"); yymaxdepth *= 2; if (yymaxdepth > YYMAXLIMIT) yymaxdepth = YYMAXLIMIT; yyss = (short *) alloca (yymaxdepth * sizeof (*yyssp)); bcopy ((char *)yyss1, (char *)yyss, size * sizeof (*yyssp)); yyvs = (YYSTYPE *) alloca (yymaxdepth * sizeof (*yyvsp)); bcopy ((char *)yyvs1, (char *)yyvs, size * sizeof (*yyvsp)); #ifdef YYLSP_NEEDED yyls = (YYLTYPE *) alloca (yymaxdepth * sizeof (*yylsp)); bcopy ((char *)yyls1, (char *)yyls, size * sizeof (*yylsp)); #endif #endif /* no yyoverflow */ yyssp = yyss + size - 1; yyvsp = yyvs + size - 1; #ifdef YYLSP_NEEDED yylsp = yyls + size - 1; #endif #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Stack size increased to %d\n", yymaxdepth); #endif if (yyssp >= yyss + yymaxdepth - 1) YYABORT; } #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Entering state %d\n", yystate); #endif /* Do appropriate processing given the current state. */ /* Read a lookahead token if we need one and don't already have one. */ yyresume: /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYFLAG) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* yychar is either YYEMPTY or YYEOF or a valid token in external form. */ if (yychar == YYEMPTY) { #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Reading a token: "); #endif yychar = YYLEX; } /* Convert token to internal form (in yychar1) for indexing tables with */ if (yychar <= 0) /* This means end of input. */ { yychar1 = 0; yychar = YYEOF; /* Don't call YYLEX any more */ #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Now at end of input.\n"); #endif } else { yychar1 = YYTRANSLATE(yychar); #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Next token is %d (%s)\n", yychar, yytname[yychar1]); #endif } yyn += yychar1; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1) goto yydefault; yyn = yytable[yyn]; /* yyn is what to do for this token type in this state. Negative => reduce, -yyn is rule number. Positive => shift, yyn is new state. New state is final state => don't bother to shift, just return success. 0, or most negative number => error. */ if (yyn < 0) { if (yyn == YYFLAG) goto yyerrlab; yyn = -yyn; goto yyreduce; } else if (yyn == 0) goto yyerrlab; if (yyn == YYFINAL) YYACCEPT; /* Shift the lookahead token. */ #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]); #endif /* Discard the token being shifted unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; *++yyvsp = yylval; #ifdef YYLSP_NEEDED *++yylsp = yylloc; #endif /* count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; yystate = yyn; goto yynewstate; /* Do the default action for the current state. */ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; /* Do a reduction. yyn is the number of a rule to reduce with. */ yyreduce: yylen = yyr2[yyn]; yyval = yyvsp[1-yylen]; /* implement default value of the action */ #if YYDEBUG != 0 if (yydebug) { if (yylen == 1) fprintf (stderr, "Reducing 1 value via line %d, ", yyrline[yyn]); else fprintf (stderr, "Reducing %d values via line %d, ", yylen, yyrline[yyn]); } #endif switch (yyn) { case 1: #line 137 "awk.y" { expression_value = yyvsp[-1].nodeval; ; break;} case 2: #line 142 "awk.y" { if (yyvsp[0].nodeval != NULL) yyval.nodeval = yyvsp[0].nodeval; else yyval.nodeval = NULL; yyerrok; ; break;} case 3: #line 151 "awk.y" { if (yyvsp[0].nodeval == NULL) yyval.nodeval = yyvsp[-1].nodeval; else if (yyvsp[-1].nodeval == NULL) yyval.nodeval = yyvsp[0].nodeval; else { if (yyvsp[-1].nodeval->type != Node_rule_list) yyvsp[-1].nodeval = node(yyvsp[-1].nodeval, Node_rule_list, (NODE*)NULL); yyval.nodeval = append_right (yyvsp[-1].nodeval, node(yyvsp[0].nodeval, Node_rule_list,(NODE *) NULL)); } yyerrok; ; break;} case 4: #line 165 "awk.y" { yyval.nodeval = NULL; ; break;} case 5: #line 166 "awk.y" { yyval.nodeval = NULL; ; break;} case 6: #line 170 "awk.y" { io_allowed = 0; ; break;} case 7: #line 172 "awk.y" { if (begin_block) { if (begin_block->type != Node_rule_list) begin_block = node(begin_block, Node_rule_list, (NODE *)NULL); append_right (begin_block, node( node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval), Node_rule_list, (NODE *)NULL) ); } else begin_block = node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval); yyval.nodeval = NULL; io_allowed = 1; yyerrok; ; break;} case 8: #line 186 "awk.y" { io_allowed = 0; ; break;} case 9: #line 188 "awk.y" { if (end_block) { if (end_block->type != Node_rule_list) end_block = node(end_block, Node_rule_list, (NODE *)NULL); append_right (end_block, node( node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval), Node_rule_list, (NODE *)NULL)); } else end_block = node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval); yyval.nodeval = NULL; io_allowed = 1; yyerrok; ; break;} case 10: #line 203 "awk.y" { msg ("error near line %d: BEGIN blocks must have an action part", lineno); errcount++; yyerrok; ; break;} case 11: #line 209 "awk.y" { msg ("error near line %d: END blocks must have an action part", lineno); errcount++; yyerrok; ; break;} case 12: #line 215 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_rule_node, yyvsp[0].nodeval); yyerrok; ; break;} case 13: #line 217 "awk.y" { yyval.nodeval = node ((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval); yyerrok; ; break;} case 14: #line 219 "awk.y" { if(yyvsp[-1].nodeval) yyval.nodeval = node (yyvsp[-1].nodeval, Node_rule_node, (NODE *)NULL); yyerrok; ; break;} case 15: #line 221 "awk.y" { func_install(yyvsp[-1].nodeval, yyvsp[0].nodeval); yyval.nodeval = NULL; yyerrok; ; break;} case 16: #line 230 "awk.y" { yyval.sval = yyvsp[0].sval; ; break;} case 17: #line 232 "awk.y" { yyval.sval = yyvsp[0].sval; ; break;} case 18: #line 237 "awk.y" { param_counter = 0; ; break;} case 19: #line 241 "awk.y" { yyval.nodeval = append_right(make_param(yyvsp[-4].sval), yyvsp[-2].nodeval); can_return = 1; ; break;} case 20: #line 249 "awk.y" { yyval.nodeval = yyvsp[-1].nodeval; can_return = 0; ; break;} case 21: #line 258 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 22: #line 260 "awk.y" { yyval.nodeval = mkrangenode ( node(yyvsp[-2].nodeval, Node_cond_pair, yyvsp[0].nodeval) ); ; break;} case 23: #line 269 "awk.y" { ++want_regexp; ; break;} case 24: #line 271 "awk.y" { want_regexp = 0; yyval.nodeval = node((NODE *)NULL,Node_regex,(NODE *)mk_re_parse(yyvsp[-1].sval, 0)); yyval.nodeval -> re_case = 0; emalloc (yyval.nodeval -> re_text, char *, strlen(yyvsp[-1].sval)+1, "regexp"); strcpy (yyval.nodeval -> re_text, yyvsp[-1].sval); ; break;} case 25: #line 282 "awk.y" { /* empty actions are different from missing actions */ yyval.nodeval = node ((NODE *) NULL, Node_illegal, (NODE *) NULL); ; break;} case 26: #line 287 "awk.y" { yyval.nodeval = yyvsp[-2].nodeval ; ; break;} case 27: #line 292 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 28: #line 294 "awk.y" { if (yyvsp[-1].nodeval == NULL || yyvsp[-1].nodeval->type != Node_statement_list) yyvsp[-1].nodeval = node(yyvsp[-1].nodeval, Node_statement_list,(NODE *)NULL); yyval.nodeval = append_right(yyvsp[-1].nodeval, node( yyvsp[0].nodeval, Node_statement_list, (NODE *)NULL)); yyerrok; ; break;} case 29: #line 302 "awk.y" { yyval.nodeval = NULL; ; break;} case 30: #line 304 "awk.y" { yyval.nodeval = NULL; ; break;} case 31: #line 309 "awk.y" { yyval.nodetypeval = Node_illegal; ; break;} case 32: #line 311 "awk.y" { yyval.nodetypeval = Node_illegal; ; break;} case 33: #line 317 "awk.y" { yyval.nodeval = NULL; ; break;} case 34: #line 319 "awk.y" { yyval.nodeval = NULL; ; break;} case 35: #line 321 "awk.y" { yyval.nodeval = yyvsp[-1].nodeval; ; break;} case 36: #line 323 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 37: #line 325 "awk.y" { yyval.nodeval = node (yyvsp[-3].nodeval, Node_K_while, yyvsp[0].nodeval); ; break;} case 38: #line 327 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_K_do, yyvsp[-5].nodeval); ; break;} case 39: #line 329 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_K_arrayfor, make_for_loop(variable(yyvsp[-5].sval), (NODE *)NULL, variable(yyvsp[-3].sval))); ; break;} case 40: #line 334 "awk.y" { yyval.nodeval = node(yyvsp[0].nodeval, Node_K_for, (NODE *)make_for_loop(yyvsp[-7].nodeval, yyvsp[-5].nodeval, yyvsp[-3].nodeval)); ; break;} case 41: #line 338 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_K_for, (NODE *)make_for_loop(yyvsp[-6].nodeval, (NODE *)NULL, yyvsp[-3].nodeval)); ; break;} case 42: #line 344 "awk.y" { yyval.nodeval = node ((NODE *)NULL, Node_K_break, (NODE *)NULL); ; break;} case 43: #line 347 "awk.y" { yyval.nodeval = node ((NODE *)NULL, Node_K_continue, (NODE *)NULL); ; break;} case 44: #line 349 "awk.y" { yyval.nodeval = node (yyvsp[-3].nodeval, yyvsp[-5].nodetypeval, yyvsp[-1].nodeval); ; break;} case 45: #line 351 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-3].nodetypeval, yyvsp[-1].nodeval); ; break;} case 46: #line 353 "awk.y" { if (! io_allowed) yyerror("next used in BEGIN or END action"); ; break;} case 47: #line 355 "awk.y" { yyval.nodeval = node ((NODE *)NULL, Node_K_next, (NODE *)NULL); ; break;} case 48: #line 357 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_exit, (NODE *)NULL); ; break;} case 49: #line 359 "awk.y" { if (! can_return) yyerror("return used outside function context"); ; break;} case 50: #line 361 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_return, (NODE *)NULL); ; break;} case 51: #line 363 "awk.y" { yyval.nodeval = node (variable(yyvsp[-4].sval), Node_K_delete, yyvsp[-2].nodeval); ; break;} case 52: #line 365 "awk.y" { yyval.nodeval = yyvsp[-1].nodeval; ; break;} case 53: #line 370 "awk.y" { yyval.nodetypeval = yyvsp[0].nodetypeval; ; break;} case 54: #line 372 "awk.y" { yyval.nodetypeval = yyvsp[0].nodetypeval; ; break;} case 55: #line 377 "awk.y" { yyval.nodeval = node(yyvsp[-3].nodeval, Node_K_if, node(yyvsp[0].nodeval, Node_if_branches, (NODE *)NULL)); ; break;} case 56: #line 383 "awk.y" { yyval.nodeval = node (yyvsp[-6].nodeval, Node_K_if, node (yyvsp[-3].nodeval, Node_if_branches, yyvsp[0].nodeval)); ; break;} case 57: #line 389 "awk.y" { yyval.nodetypeval = NULL; ; break;} case 58: #line 391 "awk.y" { yyval.nodetypeval = NULL; ; break;} case 59: #line 396 "awk.y" { yyval.nodetypeval = NULL; ; break;} case 60: #line 398 "awk.y" { yyval.nodetypeval = NULL; ; break;} case 61: #line 403 "awk.y" { yyval.nodeval = NULL; ; break;} case 62: #line 405 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_input, (NODE *)NULL); ; break;} case 63: #line 410 "awk.y" { yyval.nodeval = NULL; ; break;} case 64: #line 412 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_output, (NODE *)NULL); ; break;} case 65: #line 414 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_append, (NODE *)NULL); ; break;} case 66: #line 416 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_pipe, (NODE *)NULL); ; break;} case 67: #line 421 "awk.y" { yyval.nodeval = NULL; ; break;} case 68: #line 423 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 69: #line 428 "awk.y" { yyval.nodeval = make_param(yyvsp[0].sval); ; break;} case 70: #line 430 "awk.y" { yyval.nodeval = append_right(yyvsp[-2].nodeval, make_param(yyvsp[0].sval)); yyerrok; ; break;} case 71: #line 432 "awk.y" { yyval.nodeval = NULL; ; break;} case 72: #line 434 "awk.y" { yyval.nodeval = NULL; ; break;} case 73: #line 436 "awk.y" { yyval.nodeval = NULL; ; break;} case 74: #line 442 "awk.y" { yyval.nodeval = NULL; ; break;} case 75: #line 444 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 76: #line 449 "awk.y" { yyval.nodeval = NULL; ; break;} case 77: #line 451 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 78: #line 456 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL); ; break;} case 79: #line 458 "awk.y" { yyval.nodeval = append_right(yyvsp[-2].nodeval, node( yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL)); yyerrok; ; break;} case 80: #line 464 "awk.y" { yyval.nodeval = NULL; ; break;} case 81: #line 466 "awk.y" { yyval.nodeval = NULL; ; break;} case 82: #line 468 "awk.y" { yyval.nodeval = NULL; ; break;} case 83: #line 470 "awk.y" { yyval.nodeval = NULL; ; break;} case 84: #line 475 "awk.y" { yyval.nodeval = NULL; ; break;} case 85: #line 477 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 86: #line 482 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL); ; break;} case 87: #line 484 "awk.y" { yyval.nodeval = append_right(yyvsp[-2].nodeval, node( yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL)); yyerrok; ; break;} case 88: #line 490 "awk.y" { yyval.nodeval = NULL; ; break;} case 89: #line 492 "awk.y" { yyval.nodeval = NULL; ; break;} case 90: #line 494 "awk.y" { yyval.nodeval = NULL; ; break;} case 91: #line 496 "awk.y" { yyval.nodeval = NULL; ; break;} case 92: #line 501 "awk.y" { want_assign = 0; ; break;} case 93: #line 503 "awk.y" { yyval.nodeval = node (yyvsp[-3].nodeval, yyvsp[-2].nodetypeval, yyvsp[0].nodeval); ; break;} case 94: #line 505 "awk.y" { yyval.nodeval = node (variable(yyvsp[0].sval), Node_in_array, yyvsp[-3].nodeval); ; break;} case 95: #line 507 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_K_getline, node (yyvsp[-3].nodeval, Node_redirect_pipein, (NODE *)NULL)); ; break;} case 96: #line 512 "awk.y" { /* "too painful to do right" */ /* if (! io_allowed && $3 == NULL) yyerror("non-redirected getline illegal inside BEGIN or END action"); */ yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_getline, yyvsp[0].nodeval); ; break;} case 97: #line 521 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_and, yyvsp[0].nodeval); ; break;} case 98: #line 523 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_or, yyvsp[0].nodeval); ; break;} case 99: #line 525 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ; break;} case 100: #line 527 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 101: #line 529 "awk.y" { yyval.nodeval = node((NODE *) NULL, Node_nomatch, yyvsp[0].nodeval); ; break;} case 102: #line 531 "awk.y" { yyval.nodeval = node (variable(yyvsp[0].sval), Node_in_array, yyvsp[-2].nodeval); ; break;} case 103: #line 533 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ; break;} case 104: #line 535 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_less, yyvsp[0].nodeval); ; break;} case 105: #line 537 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_greater, yyvsp[0].nodeval); ; break;} case 106: #line 539 "awk.y" { yyval.nodeval = node(yyvsp[-4].nodeval, Node_cond_exp, node(yyvsp[-2].nodeval, Node_if_branches, yyvsp[0].nodeval));; break;} case 107: #line 541 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 108: #line 543 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_concat, yyvsp[0].nodeval); ; break;} case 109: #line 548 "awk.y" { want_assign = 0; ; break;} case 110: #line 550 "awk.y" { yyval.nodeval = node (yyvsp[-3].nodeval, yyvsp[-2].nodetypeval, yyvsp[0].nodeval); ; break;} case 111: #line 552 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_and, yyvsp[0].nodeval); ; break;} case 112: #line 554 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_or, yyvsp[0].nodeval); ; break;} case 113: #line 556 "awk.y" { /* "too painful to do right" */ /* if (! io_allowed && $3 == NULL) yyerror("non-redirected getline illegal inside BEGIN or END action"); */ yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_getline, yyvsp[0].nodeval); ; break;} case 114: #line 565 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 115: #line 567 "awk.y" { yyval.nodeval = node((NODE *) NULL, Node_nomatch, yyvsp[0].nodeval); ; break;} case 116: #line 569 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ; break;} case 117: #line 571 "awk.y" { yyval.nodeval = node (variable(yyvsp[0].sval), Node_in_array, yyvsp[-2].nodeval); ; break;} case 118: #line 573 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ; break;} case 119: #line 575 "awk.y" { yyval.nodeval = node(yyvsp[-4].nodeval, Node_cond_exp, node(yyvsp[-2].nodeval, Node_if_branches, yyvsp[0].nodeval));; break;} case 120: #line 577 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 121: #line 579 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_concat, yyvsp[0].nodeval); ; break;} case 122: #line 584 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_not,(NODE *) NULL); ; break;} case 123: #line 586 "awk.y" { yyval.nodeval = yyvsp[-1].nodeval; ; break;} case 124: #line 588 "awk.y" { yyval.nodeval = snode (yyvsp[-1].nodeval, Node_builtin, yyvsp[-3].ptrval); ; break;} case 125: #line 590 "awk.y" { yyval.nodeval = snode (yyvsp[-1].nodeval, Node_builtin, yyvsp[-3].ptrval); ; break;} case 126: #line 592 "awk.y" { yyval.nodeval = snode ((NODE *)NULL, Node_builtin, yyvsp[0].ptrval); ; break;} case 127: #line 594 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_func_call, make_string(yyvsp[-3].sval, strlen(yyvsp[-3].sval))); ; break;} case 128: #line 598 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_preincrement, (NODE *)NULL); ; break;} case 129: #line 600 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_predecrement, (NODE *)NULL); ; break;} case 130: #line 602 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_postincrement, (NODE *)NULL); ; break;} case 131: #line 604 "awk.y" { yyval.nodeval = node (yyvsp[-1].nodeval, Node_postdecrement, (NODE *)NULL); ; break;} case 132: #line 606 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 133: #line 608 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 134: #line 610 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 135: #line 614 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_exp, yyvsp[0].nodeval); ; break;} case 136: #line 616 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_times, yyvsp[0].nodeval); ; break;} case 137: #line 618 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_quotient, yyvsp[0].nodeval); ; break;} case 138: #line 620 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_mod, yyvsp[0].nodeval); ; break;} case 139: #line 622 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_plus, yyvsp[0].nodeval); ; break;} case 140: #line 624 "awk.y" { yyval.nodeval = node (yyvsp[-2].nodeval, Node_minus, yyvsp[0].nodeval); ; break;} case 141: #line 626 "awk.y" { yyval.nodeval = node (yyvsp[0].nodeval, Node_unary_minus, (NODE *)NULL); ; break;} case 142: #line 628 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 143: #line 633 "awk.y" { yyval.nodeval = NULL; ; break;} case 144: #line 635 "awk.y" { yyval.nodeval = yyvsp[0].nodeval; ; break;} case 145: #line 640 "awk.y" { want_assign = 1; yyval.nodeval = variable (yyvsp[0].sval); ; break;} case 146: #line 642 "awk.y" { want_assign = 1; yyval.nodeval = node (variable(yyvsp[-3].sval), Node_subscript, yyvsp[-1].nodeval); ; break;} case 147: #line 644 "awk.y" { want_assign = 1; yyval.nodeval = node (yyvsp[0].nodeval, Node_field_spec, (NODE *)NULL); ; break;} case 149: #line 652 "awk.y" { yyerrok; ; break;} case 150: #line 656 "awk.y" { yyval.nodetypeval = Node_illegal; yyerrok; ; break;} case 153: #line 665 "awk.y" { yyerrok; ; break;} case 154: #line 668 "awk.y" { yyval.nodetypeval = Node_illegal; yyerrok; ; break;} } /* the action file gets copied in in place of this dollarsign */ #line 327 "bison.simple" yyvsp -= yylen; yyssp -= yylen; #ifdef YYLSP_NEEDED yylsp -= yylen; #endif #if YYDEBUG != 0 if (yydebug) { short *ssp1 = yyss - 1; fprintf (stderr, "state stack now"); while (ssp1 != yyssp) fprintf (stderr, " %d", *++ssp1); fprintf (stderr, "\n"); } #endif *++yyvsp = yyval; #ifdef YYLSP_NEEDED yylsp++; if (yylen == 0) { yylsp->first_line = yylloc.first_line; yylsp->first_column = yylloc.first_column; yylsp->last_line = (yylsp-1)->last_line; yylsp->last_column = (yylsp-1)->last_column; yylsp->text = 0; } else { yylsp->last_line = (yylsp+yylen-1)->last_line; yylsp->last_column = (yylsp+yylen-1)->last_column; } #endif /* Now "shift" the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTBASE] + *yyssp; if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTBASE]; goto yynewstate; yyerrlab: /* here on detecting error */ if (! yyerrstatus) /* If not already recovering from an error, report this error. */ { ++yynerrs; yyerror("parse error"); } if (yyerrstatus == 3) { /* if just tried and failed to reuse lookahead token after an error, discard it. */ /* return failure if at end of input */ if (yychar == YYEOF) YYABORT; #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]); #endif yychar = YYEMPTY; } /* Else will try to reuse lookahead token after shifting the error token. */ yyerrstatus = 3; /* Each real token shifted decrements this */ goto yyerrhandle; yyerrdefault: /* current state does not do anything special for the error token. */ #if 0 /* This is wrong; only states that explicitly want error tokens should shift them. */ yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/ if (yyn) goto yydefault; #endif yyerrpop: /* pop the current state because it cannot handle the error token */ if (yyssp == yyss) YYABORT; yyvsp--; yystate = *--yyssp; #ifdef YYLSP_NEEDED yylsp--; #endif #if YYDEBUG != 0 if (yydebug) { short *ssp1 = yyss - 1; fprintf (stderr, "Error: state stack now"); while (ssp1 != yyssp) fprintf (stderr, " %d", *++ssp1); fprintf (stderr, "\n"); } #endif yyerrhandle: yyn = yypact[yystate]; if (yyn == YYFLAG) goto yyerrdefault; yyn += YYTERROR; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR) goto yyerrdefault; yyn = yytable[yyn]; if (yyn < 0) { if (yyn == YYFLAG) goto yyerrpop; yyn = -yyn; goto yyreduce; } else if (yyn == 0) goto yyerrpop; if (yyn == YYFINAL) YYACCEPT; #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Shifting error token, "); #endif *++yyvsp = yylval; #ifdef YYLSP_NEEDED *++yylsp = yylloc; #endif yystate = yyn; goto yynewstate; } #line 671 "awk.y" struct token { char *operator; /* text to match */ NODETYPE value; /* node type */ int class; /* lexical class */ short nostrict; /* ignore if in strict compatibility mode */ NODE *(*ptr) (); /* function that implements this keyword */ }; extern NODE *do_exp(), *do_getline(), *do_index(), *do_length(), *do_sqrt(), *do_log(), *do_sprintf(), *do_substr(), *do_split(), *do_system(), *do_int(), *do_close(), *do_atan2(), *do_sin(), *do_cos(), *do_rand(), *do_srand(), *do_match(), *do_tolower(), *do_toupper(), *do_sub(), *do_gsub(); /* Special functions for debugging */ #ifdef DEBUG NODE *do_prvars(), *do_bp(); #endif /* Tokentab is sorted ascii ascending order, so it can be binary searched. */ static struct token tokentab[] = { { "BEGIN", Node_illegal, LEX_BEGIN, 0, 0 }, { "END", Node_illegal, LEX_END, 0, 0 }, { "atan2", Node_builtin, LEX_BUILTIN, 0, do_atan2 }, #ifdef DEBUG { "bp", Node_builtin, LEX_BUILTIN, 0, do_bp }, #endif { "break", Node_K_break, LEX_BREAK, 0, 0 }, { "close", Node_builtin, LEX_BUILTIN, 0, do_close }, { "continue", Node_K_continue, LEX_CONTINUE, 0, 0 }, { "cos", Node_builtin, LEX_BUILTIN, 0, do_cos }, { "delete", Node_K_delete, LEX_DELETE, 0, 0 }, { "do", Node_K_do, LEX_DO, 0, 0 }, { "else", Node_illegal, LEX_ELSE, 0, 0 }, { "exit", Node_K_exit, LEX_EXIT, 0, 0 }, { "exp", Node_builtin, LEX_BUILTIN, 0, do_exp }, { "for", Node_K_for, LEX_FOR, 0, 0 }, { "func", Node_K_function, LEX_FUNCTION, 0, 0 }, { "function", Node_K_function, LEX_FUNCTION, 0, 0 }, { "getline", Node_K_getline, LEX_GETLINE, 0, 0 }, { "gsub", Node_builtin, LEX_BUILTIN, 0, do_gsub }, { "if", Node_K_if, LEX_IF, 0, 0 }, { "in", Node_illegal, LEX_IN, 0, 0 }, { "index", Node_builtin, LEX_BUILTIN, 0, do_index }, { "int", Node_builtin, LEX_BUILTIN, 0, do_int }, { "length", Node_builtin, LEX_LENGTH, 0, do_length }, { "log", Node_builtin, LEX_BUILTIN, 0, do_log }, { "match", Node_builtin, LEX_BUILTIN, 0, do_match }, { "next", Node_K_next, LEX_NEXT, 0, 0 }, { "print", Node_K_print, LEX_PRINT, 0, 0 }, { "printf", Node_K_printf, LEX_PRINTF, 0, 0 }, #ifdef DEBUG { "prvars", Node_builtin, LEX_BUILTIN, 0, do_prvars }, #endif { "rand", Node_builtin, LEX_BUILTIN, 0, do_rand }, { "return", Node_K_return, LEX_RETURN, 0, 0 }, { "sin", Node_builtin, LEX_BUILTIN, 0, do_sin }, { "split", Node_builtin, LEX_BUILTIN, 0, do_split }, { "sprintf", Node_builtin, LEX_BUILTIN, 0, do_sprintf }, { "sqrt", Node_builtin, LEX_BUILTIN, 0, do_sqrt }, { "srand", Node_builtin, LEX_BUILTIN, 0, do_srand }, { "sub", Node_builtin, LEX_BUILTIN, 0, do_sub }, { "substr", Node_builtin, LEX_BUILTIN, 0, do_substr }, { "system", Node_builtin, LEX_BUILTIN, 0, do_system }, { "tolower", Node_builtin, LEX_BUILTIN, 0, do_tolower }, { "toupper", Node_builtin, LEX_BUILTIN, 0, do_toupper }, { "while", Node_K_while, LEX_WHILE, 0, 0 }, }; static char *token_start; /* VARARGS0 */ static void yyerror(va_alist) va_dcl { va_list args; char *mesg; register char *ptr, *beg; char *scan; errcount++; va_start(args); mesg = va_arg(args, char *); va_end(args); /* Find the current line in the input file */ if (! lexptr) { beg = "(END OF FILE)"; ptr = beg + 13; } else { if (*lexptr == '\n' && lexptr != lexptr_begin) --lexptr; for (beg = lexptr; beg != lexptr_begin && *beg != '\n'; --beg) ; /* NL isn't guaranteed */ for (ptr = lexptr; *ptr && *ptr != '\n'; ptr++) ; if (beg != lexptr_begin) beg++; } msg("syntax error near line %d:\n%.*s", lineno, ptr - beg, beg); scan = beg; while (scan < token_start) if (*scan++ == '\t') putc('\t', stderr); else putc(' ', stderr); putc('^', stderr); putc(' ', stderr); vfprintf(stderr, mesg, args); putc('\n', stderr); exit(1); } /* * Parse a C escape sequence. STRING_PTR points to a variable containing a * pointer to the string to parse. That pointer is updated past the * characters we use. The value of the escape sequence is returned. * * A negative value means the sequence \ newline was seen, which is supposed to * be equivalent to nothing at all. * * If \ is followed by a null character, we return a negative value and leave * the string pointer pointing at the null character. * * If \ is followed by 000, we return 0 and leave the string pointer after the * zeros. A value of 0 does not mean end of string. */ int parse_escape(string_ptr) char **string_ptr; { register int c = *(*string_ptr)++; register int i; register int count = 0; switch (c) { case 'a': return BELL; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case '\n': return -2; case 0: (*string_ptr)--; return -1; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': i = c - '0'; count = 0; while (++count < 3) { if ((c = *(*string_ptr)++) >= '0' && c <= '7') { i *= 8; i += c - '0'; } else { (*string_ptr)--; break; } } return i; case 'x': i = 0; while (1) { if (isxdigit((c = *(*string_ptr)++))) { if (isdigit(c)) i += c - '0'; else if (isupper(c)) i += c - 'A' + 10; else i += c - 'a' + 10; } else { (*string_ptr)--; break; } } return i; default: return c; } } /* * Read the input and turn it into tokens. Input is now read from a file * instead of from malloc'ed memory. The main program takes a program * passed as a command line argument and writes it to a temp file. Otherwise * the file name is made available in an external variable. */ static int yylex() { register int c; register int namelen; register char *tokstart; char *tokkey; static did_newline = 0; /* the grammar insists that actions end * with newlines. This was easier than * hacking the grammar. */ int seen_e = 0; /* These are for numbers */ int seen_point = 0; int esc_seen; extern char **sourcefile; extern int tempsource, numfiles; static int file_opened = 0; static FILE *fin; static char cbuf[BUFSIZ]; int low, mid, high; #ifdef DEBUG extern int debugging; #endif if (! file_opened) { file_opened = 1; #ifdef DEBUG if (debugging) { int i; for (i = 0; i <= numfiles; i++) fprintf (stderr, "sourcefile[%d] = %s\n", i, sourcefile[i]); } #endif nextfile: if ((fin = pathopen (sourcefile[++curinfile])) == NULL) fatal("cannot open `%s' for reading (%s)", sourcefile[curinfile], strerror(errno)); *(lexptr = cbuf) = '\0'; /* * immediately unlink the tempfile so that it will * go away cleanly if we bomb. */ if (tempsource && curinfile == 0) (void) unlink (sourcefile[curinfile]); } retry: if (! *lexptr) if (fgets (cbuf, sizeof cbuf, fin) == NULL) { if (fin != NULL) fclose (fin); /* be neat and clean */ if (curinfile < numfiles) goto nextfile; return 0; } else lexptr = lexptr_begin = cbuf; if (want_regexp) { int in_brack = 0; want_regexp = 0; token_start = tokstart = lexptr; while (c = *lexptr++) { switch (c) { case '[': in_brack = 1; break; case ']': in_brack = 0; break; case '\\': if (*lexptr++ == '\0') { yyerror("unterminated regexp ends with \\"); return ERROR; } else if (lexptr[-1] == '\n') goto retry; break; case '/': /* end of the regexp */ if (in_brack) break; lexptr--; yylval.sval = tokstart; return REGEXP; case '\n': lineno++; case '\0': lexptr--; /* so error messages work */ yyerror("unterminated regexp"); return ERROR; } } } if (*lexptr == '\n') { lexptr++; lineno++; return NEWLINE; } while (*lexptr == ' ' || *lexptr == '\t') lexptr++; token_start = tokstart = lexptr; switch (c = *lexptr++) { case 0: return 0; case '\n': lineno++; return NEWLINE; case '#': /* it's a comment */ while (*lexptr != '\n' && *lexptr != '\0') lexptr++; goto retry; case '\\': if (*lexptr == '\n') { lineno++; lexptr++; goto retry; } else break; case ')': case ']': case '(': case '[': case '$': case ';': case ':': case '?': /* * set node type to ILLEGAL because the action should set it * to the right thing */ yylval.nodetypeval = Node_illegal; return c; case '{': case ',': yylval.nodetypeval = Node_illegal; return c; case '*': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_times; lexptr++; return ASSIGNOP; } else if (*lexptr == '*') { /* make ** and **= aliases * for ^ and ^= */ if (lexptr[1] == '=') { yylval.nodetypeval = Node_assign_exp; lexptr += 2; return ASSIGNOP; } else { yylval.nodetypeval = Node_illegal; lexptr++; return '^'; } } yylval.nodetypeval = Node_illegal; return c; case '/': if (want_assign && *lexptr == '=') { yylval.nodetypeval = Node_assign_quotient; lexptr++; return ASSIGNOP; } yylval.nodetypeval = Node_illegal; return c; case '%': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_mod; lexptr++; return ASSIGNOP; } yylval.nodetypeval = Node_illegal; return c; case '^': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_exp; lexptr++; return ASSIGNOP; } yylval.nodetypeval = Node_illegal; return c; case '+': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_plus; lexptr++; return ASSIGNOP; } if (*lexptr == '+') { yylval.nodetypeval = Node_illegal; lexptr++; return INCREMENT; } yylval.nodetypeval = Node_illegal; return c; case '!': if (*lexptr == '=') { yylval.nodetypeval = Node_notequal; lexptr++; return RELOP; } if (*lexptr == '~') { yylval.nodetypeval = Node_nomatch; lexptr++; return MATCHOP; } yylval.nodetypeval = Node_illegal; return c; case '<': if (*lexptr == '=') { yylval.nodetypeval = Node_leq; lexptr++; return RELOP; } yylval.nodetypeval = Node_less; return c; case '=': if (*lexptr == '=') { yylval.nodetypeval = Node_equal; lexptr++; return RELOP; } yylval.nodetypeval = Node_assign; return ASSIGNOP; case '>': if (*lexptr == '=') { yylval.nodetypeval = Node_geq; lexptr++; return RELOP; } else if (*lexptr == '>') { yylval.nodetypeval = Node_redirect_append; lexptr++; return APPEND_OP; } yylval.nodetypeval = Node_greater; return c; case '~': yylval.nodetypeval = Node_match; return MATCHOP; case '}': /* * Added did newline stuff. Easier than * hacking the grammar */ if (did_newline) { did_newline = 0; return c; } did_newline++; --lexptr; return NEWLINE; case '"': esc_seen = 0; while (*lexptr != '\0') { switch (*lexptr++) { case '\\': esc_seen = 1; if (*lexptr == '\n') yyerror("newline in string"); if (*lexptr++ != '\0') break; /* fall through */ case '\n': lexptr--; yyerror("unterminated string"); return ERROR; case '"': yylval.nodeval = make_str_node(tokstart + 1, lexptr-tokstart-2, esc_seen); yylval.nodeval->flags |= PERM; return YSTRING; } } return ERROR; case '-': if (*lexptr == '=') { yylval.nodetypeval = Node_assign_minus; lexptr++; return ASSIGNOP; } if (*lexptr == '-') { yylval.nodetypeval = Node_illegal; lexptr++; return DECREMENT; } yylval.nodetypeval = Node_illegal; return c; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': /* It's a number */ for (namelen = 0; (c = tokstart[namelen]) != '\0'; namelen++) { switch (c) { case '.': if (seen_point) goto got_number; ++seen_point; break; case 'e': case 'E': if (seen_e) goto got_number; ++seen_e; if (tokstart[namelen + 1] == '-' || tokstart[namelen + 1] == '+') namelen++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: goto got_number; } } got_number: lexptr = tokstart + namelen; /* yylval.nodeval = make_string(tokstart, namelen); (void) force_number(yylval.nodeval); */ yylval.nodeval = make_number(atof(tokstart)); yylval.nodeval->flags |= PERM; return NUMBER; case '&': if (*lexptr == '&') { yylval.nodetypeval = Node_and; while (c = *++lexptr) { if (c == '#') while ((c = *++lexptr) != '\n' && c != '\0') ; if (c == '\n') lineno++; else if (! isspace(c)) break; } return LEX_AND; } return ERROR; case '|': if (*lexptr == '|') { yylval.nodetypeval = Node_or; while (c = *++lexptr) { if (c == '#') while ((c = *++lexptr) != '\n' && c != '\0') ; if (c == '\n') lineno++; else if (! isspace(c)) break; } return LEX_OR; } yylval.nodetypeval = Node_illegal; return c; } if (c != '_' && ! isalpha(c)) { yyerror("Invalid char '%c' in expression\n", c); return ERROR; } /* it's some type of name-type-thing. Find its length */ for (namelen = 0; is_identchar(tokstart[namelen]); namelen++) /* null */ ; emalloc(tokkey, char *, namelen+1, "yylex"); memcpy(tokkey, tokstart, namelen); tokkey[namelen] = '\0'; /* See if it is a special token. */ low = 0; high = (sizeof (tokentab) / sizeof (tokentab[0])) - 1; while (low <= high) { int i, c; mid = (low + high) / 2; c = *tokstart - tokentab[mid].operator[0]; i = c ? c : strcmp (tokkey, tokentab[mid].operator); if (i < 0) { /* token < mid */ high = mid - 1; } else if (i > 0) { /* token > mid */ low = mid + 1; } else { lexptr = tokstart + namelen; if (strict && tokentab[mid].nostrict) break; if (tokentab[mid].class == LEX_BUILTIN || tokentab[mid].class == LEX_LENGTH) yylval.ptrval = tokentab[mid].ptr; else yylval.nodetypeval = tokentab[mid].value; return tokentab[mid].class; } } /* It's a name. See how long it is. */ yylval.sval = tokkey; lexptr = tokstart + namelen; if (*lexptr == '(') return FUNC_CALL; else return NAME; } #ifndef DEFPATH #ifdef MSDOS #define DEFPATH "." #define ENVSEP ';' #else #define DEFPATH ".:/usr/lib/awk:/usr/local/lib/awk" #define ENVSEP ':' #endif #endif static FILE * pathopen (file) char *file; { static char *savepath = DEFPATH; static int first = 1; char *awkpath, *cp; char trypath[BUFSIZ]; FILE *fp; #ifdef DEBUG extern int debugging; #endif int fd; if (strcmp (file, "-") == 0) return (stdin); if (strict) return (fopen (file, "r")); if (first) { first = 0; if ((awkpath = getenv ("AWKPATH")) != NULL && *awkpath) savepath = awkpath; /* used for restarting */ } awkpath = savepath; /* some kind of path name, no search */ #ifndef MSDOS if (strchr (file, '/') != NULL) #else if (strchr (file, '/') != NULL || strchr (file, '\\') != NULL || strchr (file, ':') != NULL) #endif return ( (fd = devopen (file, "r")) >= 0 ? fdopen(fd, "r") : NULL); do { trypath[0] = '\0'; /* this should take into account limits on size of trypath */ for (cp = trypath; *awkpath && *awkpath != ENVSEP; ) *cp++ = *awkpath++; if (cp != trypath) { /* nun-null element in path */ *cp++ = '/'; strcpy (cp, file); } else strcpy (trypath, file); #ifdef DEBUG if (debugging) fprintf(stderr, "trying: %s\n", trypath); #endif if ((fd = devopen (trypath, "r")) >= 0 && (fp = fdopen(fd, "r")) != NULL) return (fp); /* no luck, keep going */ if(*awkpath == ENVSEP && awkpath[1] != '\0') awkpath++; /* skip colon */ } while (*awkpath); #ifdef MSDOS /* * Under DOS (and probably elsewhere) you might have one of the awk * paths defined, WITHOUT the current working directory in it. * Therefore you should try to open the file in the current directory. */ return ( (fd = devopen(file, "r")) >= 0 ? fdopen(fd, "r") : NULL); #else return (NULL); #endif } static NODE * node_common(op) NODETYPE op; { register NODE *r; extern int numfiles; extern int tempsource; extern char **sourcefile; r = newnode(op); r->source_line = lineno; if (numfiles > -1 && ! tempsource) r->source_file = sourcefile[curinfile]; else r->source_file = NULL; return r; } /* * This allocates a node with defined lnode and rnode. * This should only be used by yyparse+co while reading in the program */ NODE * node(left, op, right) NODE *left, *right; NODETYPE op; { register NODE *r; r = node_common(op); r->lnode = left; r->rnode = right; return r; } /* * This allocates a node with defined subnode and proc * Otherwise like node() */ static NODE * snode(subn, op, procp) NODETYPE op; NODE *(*procp) (); NODE *subn; { register NODE *r; r = node_common(op); r->subnode = subn; r->proc = procp; return r; } /* * This allocates a Node_line_range node with defined condpair and * zeroes the trigger word to avoid the temptation of assuming that calling * 'node( foo, Node_line_range, 0)' will properly initialize 'triggered'. */ /* Otherwise like node() */ static NODE * mkrangenode(cpair) NODE *cpair; { register NODE *r; r = newnode(Node_line_range); r->condpair = cpair; r->triggered = 0; return r; } /* Build a for loop */ static NODE * make_for_loop(init, cond, incr) NODE *init, *cond, *incr; { register FOR_LOOP_HEADER *r; NODE *n; emalloc(r, FOR_LOOP_HEADER *, sizeof(FOR_LOOP_HEADER), "make_for_loop"); n = newnode(Node_illegal); r->init = init; r->cond = cond; r->incr = incr; n->sub.nodep.r.hd = r; return n; } /* * Install a name in the hash table specified, even if it is already there. * Name stops with first non alphanumeric. Caller must check against * redefinition if that is desired. */ NODE * install(table, name, value) NODE **table; char *name; NODE *value; { register NODE *hp; register int len, bucket; register char *p; len = 0; p = name; while (is_identchar(*p)) p++; len = p - name; hp = newnode(Node_hashnode); bucket = hashf(name, len, HASHSIZE); hp->hnext = table[bucket]; table[bucket] = hp; hp->hlength = len; hp->hvalue = value; emalloc(hp->hname, char *, len + 1, "install"); memcpy(hp->hname, name, len); hp->hname[len] = '\0'; return hp->hvalue; } /* * find the most recent hash node for name name (ending with first * non-identifier char) installed by install */ NODE * lookup(table, name) NODE **table; char *name; { register char *bp; register NODE *bucket; register int len; for (bp = name; is_identchar(*bp); bp++) ; len = bp - name; bucket = table[hashf(name, len, HASHSIZE)]; while (bucket) { if (bucket->hlength == len && STREQN(bucket->hname, name, len)) return bucket->hvalue; bucket = bucket->hnext; } return NULL; } #define HASHSTEP(old, c) ((old << 1) + c) #define MAKE_POS(v) (v & ~0x80000000) /* make number positive */ /* * return hash function on name. */ static int hashf(name, len, hashsize) register char *name; register int len; int hashsize; { register int r = 0; while (len--) r = HASHSTEP(r, *name++); r = MAKE_POS(r) % hashsize; return r; } /* * Add new to the rightmost branch of LIST. This uses n^2 time, so we make * a simple attempt at optimizing it. */ static NODE * append_right(list, new) NODE *list, *new; { register NODE *oldlist; static NODE *savefront = NULL, *savetail = NULL; oldlist = list; if (savefront == oldlist) { savetail = savetail->rnode = new; return oldlist; } else savefront = oldlist; while (list->rnode != NULL) list = list->rnode; savetail = list->rnode = new; return oldlist; } /* * check if name is already installed; if so, it had better have Null value, * in which case def is added as the value. Otherwise, install name with def * as value. */ static void func_install(params, def) NODE *params; NODE *def; { NODE *r; pop_params(params->rnode); pop_var(params, 0); r = lookup(variables, params->param); if (r != NULL) { fatal("function name `%s' previously defined", params->param); } else (void) install(variables, params->param, node(params, Node_func, def)); } static void pop_var(np, freeit) NODE *np; int freeit; { register char *bp; register NODE *bucket, **save; register int len; char *name; name = np->param; for (bp = name; is_identchar(*bp); bp++) ; len = bp - name; save = &(variables[hashf(name, len, HASHSIZE)]); for (bucket = *save; bucket; bucket = bucket->hnext) { if (len == bucket->hlength && STREQN(bucket->hname, name, len)) { *save = bucket->hnext; freenode(bucket); free(bucket->hname); if (freeit) free(np->param); return; } save = &(bucket->hnext); } } static void pop_params(params) NODE *params; { register NODE *np; for (np = params; np != NULL; np = np->rnode) pop_var(np, 1); } static NODE * make_param(name) char *name; { NODE *r; r = newnode(Node_param_list); r->param = name; r->rnode = NULL; r->param_cnt = param_counter++; return (install(variables, name, r)); } /* Name points to a variable name. Make sure its in the symbol table */ NODE * variable(name) char *name; { register NODE *r; if ((r = lookup(variables, name)) == NULL) r = install(variables, name, node(Nnull_string, Node_var, (NODE *) NULL)); return r; } gawk-2.11/version.sh 644 11660 0 2745 4527633622 12610 0ustar hackwheel#! /bin/sh # version.sh --- create version.c if [ "x$1" = "x" ] then echo you must specify a release number on the command line exit 1 fi RELEASE="$1" cat << EOF char *version_string = "@(#)Gnu Awk (gawk) ${RELEASE}"; /* 1.02 fixed /= += *= etc to return the new Left Hand Side instead of the Right Hand Side */ /* 1.03 Fixed split() to treat strings of space and tab as FS if the split char is ' '. Added -v option to print version number Fixed bug that caused rounding when printing large numbers */ /* 2.00beta Incorporated the functionality of the "new" awk as described the book (reference not handy). Extensively tested, but no doubt still buggy. Badly needs tuning and cleanup, in particular in memory management which is currently almost non-existent. */ /* 2.01 JF: Modified to compile under GCC, and fixed a few bugs while I was at it. I hope I didn't add any more. I modified parse.y to reduce the number of reduce/reduce conflicts. There are still a few left. */ /* 2.02 Fixed JF's bugs; improved memory management, still needs lots of work. */ /* 2.10 Major grammar rework and lots of bug fixes from David. Major changes for performance enhancements from David. A number of minor bug fixes and new features from Arnold. Changes for MSDOS from Conrad Kwok and Scott Garfinkle. The gawk.texinfo and info files included! */ /* 2.11 Bug fix release to 2.10. Lots of changes for portability, speed, and configurability. */ EOF exit 0 gawk-2.11/patchlevel.h 644 11660 0 25 4527633616 13017 0ustar hackwheel#define PATCHLEVEL 1 gawk-2.11/alloca.c 644 11660 0 12520 4474611554 12177 0ustar hackwheel/* alloca -- (mostly) portable public-domain implementation -- D A Gwyn last edit: 86/05/30 rms include config.h, since on VMS it renames some symbols. Use xmalloc instead of malloc. This implementation of the PWB library alloca() function, which is used to allocate space off the run-time stack so that it is automatically reclaimed upon procedure exit, was inspired by discussions with J. Q. Johnson of Cornell. It should work under any C implementation that uses an actual procedure stack (as opposed to a linked list of frames). There are some preprocessor constants that can be defined when compiling for your specific system, for improved efficiency; however, the defaults should be okay. The general concept of this implementation is to keep track of all alloca()-allocated blocks, and reclaim any that are found to be deeper in the stack than the current invocation. This heuristic does not reclaim storage as soon as it becomes invalid, but it will do so eventually. As a special case, alloca(0) reclaims storage without allocating any. It is a good idea to use alloca(0) in your main control loop, etc. to force garbage collection. */ #ifndef lint static char SCCSid[] = "@(#)alloca.c 1.1"; /* for the "what" utility */ #endif #ifdef emacs #include "config.h" #ifdef static /* actually, only want this if static is defined as "" -- this is for usg, in which emacs must undefine static in order to make unexec workable */ #ifndef STACK_DIRECTION you lose -- must know STACK_DIRECTION at compile-time #endif /* STACK_DIRECTION undefined */ #endif /* static */ #endif /* emacs */ #ifdef X3J11 typedef void *pointer; /* generic pointer type */ #else typedef char *pointer; /* generic pointer type */ #endif #define NULL 0 /* null pointer constant */ extern void free(); extern pointer xmalloc(); /* Define STACK_DIRECTION if you know the direction of stack growth for your system; otherwise it will be automatically deduced at run-time. STACK_DIRECTION > 0 => grows toward higher addresses STACK_DIRECTION < 0 => grows toward lower addresses STACK_DIRECTION = 0 => direction of growth unknown */ #ifndef STACK_DIRECTION #define STACK_DIRECTION 0 /* direction unknown */ #endif #if STACK_DIRECTION != 0 #define STACK_DIR STACK_DIRECTION /* known at compile-time */ #else /* STACK_DIRECTION == 0; need run-time code */ static int stack_dir; /* 1 or -1 once known */ #define STACK_DIR stack_dir static void find_stack_direction (/* void */) { static char *addr = NULL; /* address of first `dummy', once known */ auto char dummy; /* to get stack address */ if (addr == NULL) { /* initial entry */ addr = &dummy; find_stack_direction (); /* recurse once */ } else /* second entry */ if (&dummy > addr) stack_dir = 1; /* stack grew upward */ else stack_dir = -1; /* stack grew downward */ } #endif /* STACK_DIRECTION == 0 */ /* An "alloca header" is used to: (a) chain together all alloca()ed blocks; (b) keep track of stack depth. It is very important that sizeof(header) agree with malloc() alignment chunk size. The following default should work okay. */ #ifndef ALIGN_SIZE #define ALIGN_SIZE sizeof(double) #endif typedef union hdr { char align[ALIGN_SIZE]; /* to force sizeof(header) */ struct { union hdr *next; /* for chaining headers */ char *deep; /* for stack depth measure */ } h; } header; /* alloca( size ) returns a pointer to at least `size' bytes of storage which will be automatically reclaimed upon exit from the procedure that called alloca(). Originally, this space was supposed to be taken from the current stack frame of the caller, but that method cannot be made to work for some implementations of C, for example under Gould's UTX/32. */ static header *last_alloca_header = NULL; /* -> last alloca header */ pointer alloca (size) /* returns pointer to storage */ unsigned size; /* # bytes to allocate */ { auto char probe; /* probes stack depth: */ register char *depth = &probe; #if STACK_DIRECTION == 0 if (STACK_DIR == 0) /* unknown growth direction */ find_stack_direction (); #endif /* Reclaim garbage, defined as all alloca()ed storage that was allocated from deeper in the stack than currently. */ { register header *hp; /* traverses linked list */ for (hp = last_alloca_header; hp != NULL;) if (STACK_DIR > 0 && hp->h.deep > depth || STACK_DIR < 0 && hp->h.deep < depth) { register header *np = hp->h.next; free ((pointer) hp); /* collect garbage */ hp = np; /* -> next header */ } else break; /* rest are not deeper */ last_alloca_header = hp; /* -> last valid storage */ } if (size == 0) return NULL; /* no allocation required */ /* Allocate combined header + user data storage. */ { register pointer new = xmalloc (sizeof (header) + size); /* address of header */ ((header *)new)->h.next = last_alloca_header; ((header *)new)->h.deep = depth; last_alloca_header = (header *)new; /* User storage begins just after header. */ return (pointer)((char *)new + sizeof(header)); } } pointer xmalloc(n) unsigned int n; { extern pointer malloc(); pointer cp; static char mesg[] = "xmalloc: no memory!\n"; cp = malloc(n); if (! cp) { write (2, mesg, sizeof(mesg) - 1); exit(1); } return cp; } gawk-2.11/alloca.s 644 11660 0 20312 4506173635 12214 0ustar hackwheel/* `alloca' standard 4.2 subroutine for 68000's and 16000's and others. Also has _setjmp and _longjmp for pyramids. Copyright (C) 1985, 1986, 1988 Free Software Foundation, Inc. This file is part of GNU Emacs. GNU Emacs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. No author or distributor accepts responsibility to anyone for the consequences of using it or for whether it serves any particular purpose or works at all, unless he says so in writing. Refer to the GNU Emacs General Public License for full details. Everyone is granted permission to copy, modify and redistribute GNU Emacs, but only under the conditions described in the GNU Emacs General Public License. A copy of this license is supposed to have been given to you along with GNU Emacs so you can know your rights and responsibilities. It should be in a file named COPYING. Among other things, the copyright notice and this notice must be preserved on all copies. */ /* Both 68000 systems I have run this on have had broken versions of alloca. Also, I am told that non-berkeley systems do not have it at all. So replace whatever system-provided alloca there may be on all 68000 systems. */ /* #include "config.h" */ #ifndef HAVE_ALLOCA /* define this to use system's alloca */ #ifndef hp9000s300 #ifndef mc68k #ifndef m68000 #ifndef WICAT #ifndef ns16000 #ifndef sequent #ifndef pyr #ifndef ATT3B5 #ifndef XENIX you lose!! #endif /* XENIX */ #endif /* ATT3B5 */ #endif /* pyr */ #endif /* sequent */ #endif /* ns16000 */ #endif /* WICAT */ #endif /* m68000 */ #endif /* mc68k */ #endif /* hp9000s300 */ #ifdef hp9000s300 #ifdef OLD_HP_ASSEMBLER data text globl _alloca _alloca move.l (sp)+,a0 ; pop return addr from top of stack move.l (sp)+,d0 ; pop size in bytes from top of stack add.l #ROUND,d0 ; round size up to long word and.l #MASK,d0 ; mask out lower two bits of size sub.l d0,sp ; allocate by moving stack pointer tst.b PROBE(sp) ; stack probe to allocate pages move.l sp,d0 ; return pointer add.l #-4,sp ; new top of stack jmp (a0) ; not a normal return MASK equ -4 ; Longword alignment ROUND equ 3 ; ditto PROBE equ -128 ; safety buffer for C compiler scratch data #else /* new hp assembler syntax */ /* The new compiler does "move.m (%sp)" to save registers, so we must copy the saved registers when we mung the sp. The old compiler did "move.m (%a6)", which gave us no trouble */ text set PROBE,-128 # safety for C frame temporaries set MAXREG,10 # d2-d7, a2-a5 may have been saved global _alloca _alloca: mov.l (%sp)+,%a0 # return addess mov.l (%sp)+,%d0 # number of bytes to allocate mov.l %sp,%a1 # save old sp for register copy mov.l %sp,%d1 # compute new sp sub.l %d0,%d1 # space requested and.l &-4,%d1 # round down to longword sub.l &MAXREG*4,%d1 # space for saving registers mov.l %d1,%sp # save new value of sp tst.b PROBE(%sp) # create pages (sigh) move.w &MAXREG-1,%d0 copy_regs_loop: /* save caller's saved registers */ mov.l (%a1)+,(%sp)+ dbra %d0,copy_regs_loop mov.l %sp,%d0 # return value mov.l %d1,%sp add.l &-4,%sp # adjust tos jmp (%a0) # rts #endif /* new hp assembler */ #else #ifdef mc68k /* SGS assembler totally different */ file "alloca.s" global alloca alloca: mov.l (%sp)+,%a1 # pop return addr from top of stack mov.l (%sp)+,%d0 # pop size in bytes from top of stack add.l &R%1,%d0 # round size up to long word and.l &-4,%d0 # mask out lower two bits of size sub.l %d0,%sp # allocate by moving stack pointer tst.b P%1(%sp) # stack probe to allocate pages mov.l %sp,%a0 # return pointer as pointer mov.l %sp,%d0 # return pointer as int to avoid disaster add.l &-4,%sp # new top of stack jmp (%a1) # not a normal return set S%1,64 # safety factor for C compiler scratch set R%1,3+S%1 # add to size for rounding set P%1,-132 # probe this far below current top of stack #else /* not mc68k */ #ifdef m68000 #ifdef WICAT /* * Registers are saved after the corresponding link so we have to explicitly * move them to the top of the stack where they are expected to be. * Since we do not know how many registers were saved in the calling function * we must assume the maximum possible (d2-d7,a2-a5). Hence, we end up * wasting some space on the stack. * * The large probe (tst.b) attempts to make up for the fact that we have * potentially used up the space that the caller probed for its own needs. */ .procss m0 .config "68000 1" .module _alloca MAXREG: .const 10 .sect text .global _alloca _alloca: move.l (sp)+,a1 ; pop return address move.l (sp)+,d0 ; pop allocation size move.l sp,d1 ; get current SP value sub.l d0,d1 ; adjust to reflect required size... sub.l #MAXREG*4,d1 ; ...and space needed for registers and.l #-4,d1 ; backup to longword boundry move.l sp,a0 ; save old SP value for register copy move.l d1,sp ; set the new SP value tst.b -4096(sp) ; grab an extra page (to cover caller) move.l a2,d1 ; save callers register move.l sp,a2 move.w #MAXREG-1,d0 ; # of longwords to copy loop: move.l (a0)+,(a2)+ ; copy registers... dbra d0,loop ; ...til there are no more move.l a2,d0 ; end of register area is addr for new space move.l d1,a2 ; restore saved a2. addq.l #4,sp ; caller will increment sp by 4 after return. move.l d0,a0 ; return value in both a0 and d0. jmp (a1) .end _alloca #else /* Some systems want the _, some do not. Win with both kinds. */ .globl _alloca _alloca: .globl alloca alloca: movl sp@+,a0 movl a7,d0 subl sp@,d0 andl #~3,d0 movl d0,sp tstb sp@(0) /* Make stack pages exist */ /* Needed on certain systems that lack true demand paging */ addql #4,d0 jmp a0@ #endif /* not WICAT */ #endif /* m68000 */ #endif /* not mc68k */ #endif /* not hp9000s300 */ #ifdef ns16000 .text .align 2 /* Some systems want the _, some do not. Win with both kinds. */ .globl _alloca _alloca: .globl alloca alloca: /* Two different assembler syntaxes are used for the same code on different systems. */ #ifdef sequent #define IM #define REGISTER(x) x #else #define IM $ #define REGISTER(x) 0(x) #endif /* * The ns16000 is a little more difficult, need to copy regs. * Also the code assumes direct linkage call sequence (no mod table crap). * We have to copy registers, and therefore waste 32 bytes. * * Stack layout: * new sp -> junk * registers (copy) * r0 -> new data * | (orig retval) * | (orig arg) * old sp -> regs (orig) * local data * fp -> old fp */ movd tos,r1 /* pop return addr */ negd tos,r0 /* pop amount to allocate */ sprd sp,r2 addd r2,r0 bicb IM/**/3,r0 /* 4-byte align */ lprd sp,r0 adjspb IM/**/36 /* space for regs, +4 for caller to pop */ movmd 0(r2),4(sp),IM/**/4 /* copy regs */ movmd 0x10(r2),0x14(sp),IM/**/4 jump REGISTER(r1) /* funky return */ #endif /* ns16000 */ #ifdef pyr .globl _alloca _alloca: addw $3,pr0 # add 3 (dec) to first argument bicw $3,pr0 # then clear its last 2 bits subw pr0,sp # subtract from SP the val in PR0 andw $-32,sp # keep sp aligned on multiple of 32. movw sp,pr0 # ret. current SP ret #ifdef PYRAMID_OLD /* This isn't needed in system version 4. */ .globl __longjmp .globl _longjmp .globl __setjmp .globl _setjmp __longjmp: jump _longjmp __setjmp: jump _setjmp #endif #endif /* pyr */ #ifdef ATT3B5 .align 4 .globl alloca alloca: movw %ap, %r8 subw2 $9*4, %r8 movw 0(%r8), %r1 /* pc */ movw 4(%r8), %fp movw 8(%r8), %sp addw2 %r0, %sp /* make room */ movw %sp, %r0 /* return value */ jmp (%r1) /* continue... */ #endif /* ATT3B5 */ #ifdef XENIX .386 _TEXT segment dword use32 public 'CODE' assume cs:_TEXT ;------------------------------------------------------------------------- public _alloca _alloca proc near pop ecx ; return address pop eax ; amount to alloc add eax,3 ; round it to 32-bit boundary and al,11111100B ; mov edx,esp ; current sp in edx sub edx,eax ; lower the stack xchg esp,edx ; start of allocation in esp, old sp in edx mov eax,esp ; return ptr to base in eax push [edx+8] ; save poss. stored reg. values (esi,edi,ebx) push [edx+4] ; on lowered stack push [edx] ; sub esp,4 ; allow for 'add esp, 4' jmp ecx ; jump to return address _alloca endp _TEXT ends end #endif /* XENIX */ #endif /* not HAVE_ALLOCA */ gawk-2.11/regex.c 644 11660 0 144522 4520716101 12070 0ustar hackwheel/* Extended regular expression matching and search. Copyright (C) 1985 Free Software Foundation, Inc. NO WARRANTY BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. GENERAL PUBLIC LICENSE TO COPY 1. You may copy and distribute verbatim copies of this source file as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy a valid copyright notice "Copyright (C) 1985 Free Software Foundation, Inc."; and include following the copyright notice a verbatim copy of the above disclaimer of warranty and of this License. You may charge a distribution fee for the physical act of transferring a copy. 2. You may modify your copy or copies of this source file or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains or is a derivative of this program or any part thereof, to be licensed at no charge to all third parties on terms identical to those contained in this License Agreement (except that you may choose to grant more extensive warranty protection to some or all third parties, at your option). c) You may charge a distribution fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another unrelated program with this program (or its derivative) on a volume of a storage or distribution medium does not bring the other program under the scope of these terms. 3. You may copy and distribute this program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal shipping charge) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs. 4. You may not copy, sublicense, distribute or transfer this program except as expressly provided under this License Agreement. Any attempt otherwise to copy, sublicense, distribute or transfer this program is void and your rights to use the program under this License agreement shall be automatically terminated. However, parties who have received computer software programs from you with this License Agreement will not have their licenses terminated so long as such parties remain in full compliance. 5. If you wish to incorporate parts of this program into other free programs whose distribution conditions are different, write to the Free Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet worked out a simple rule that can be stated here, but we will often permit this. We will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software. In other words, you are welcome to use, share and improve this program. You are forbidden to forbid anyone else to use, share and improve what you give them. Help stamp out software-hoarding! */ #ifdef MSDOS #include static void init_syntax_once(void ); extern int re_set_syntax(int syntax); extern char *re_compile_pattern(char *pattern,int size,struct re_pattern_buffer *bufp); static int store_jump(char *from,char opcode,char *to); static int insert_jump(char op,char *from,char *to,char *current_end); extern void re_compile_fastmap(struct re_pattern_buffer *bufp); extern int re_search(struct re_pattern_buffer *pbufp,char *string,int size,int startpos,int range,struct re_registers *regs); extern int re_search_2(struct re_pattern_buffer *pbufp,char *string1,int size1,char *string2,int size2,int startpos,int range,struct re_registers *regs,int mstop); extern int re_match(struct re_pattern_buffer *pbufp,char *string,int size,int pos,struct re_registers *regs); extern int re_match_2(struct re_pattern_buffer *pbufp,unsigned char *string1,int size1,unsigned char *string2,int size2,int pos,struct re_registers *regs,int mstop); static int bcmp_translate(unsigned char *s1,unsigned char *s2,int len,unsigned char *translate); extern char *re_comp(char *s); extern int re_exec(char *s); #endif /* To test, compile with -Dtest. This Dtestable feature turns this into a self-contained program which reads a pattern, describes how it compiles, then reads a string and searches for it. */ #ifdef emacs /* The `emacs' switch turns on certain special matching commands that make sense only in emacs. */ #include "config.h" #include "lisp.h" #include "buffer.h" #include "syntax.h" #else /* not emacs */ #ifdef BCOPY_MISSING #define bcopy(s,d,n) memcpy((d),(s),(n)) #define bcmp(s1,s2,n) memcmp((s1),(s2),(n)) #define bzero(s,n) memset((s),0,(n)) #else void bcopy(); int bcmp(); void bzero(); #endif /* Make alloca work the best possible way. */ #ifdef __GNUC__ #define alloca __builtin_alloca #else #ifdef sparc #include #endif #endif /* * Define the syntax stuff, so we can do the \<...\> things. */ #ifndef Sword /* must be non-zero in some of the tests below... */ #define Sword 1 #endif #define SYNTAX(c) re_syntax_table[c] #ifdef SYNTAX_TABLE char *re_syntax_table; #else static char re_syntax_table[256]; static void init_syntax_once () { register int c; static int done = 0; if (done) return; bzero (re_syntax_table, sizeof re_syntax_table); for (c = 'a'; c <= 'z'; c++) re_syntax_table[c] = Sword; for (c = 'A'; c <= 'Z'; c++) re_syntax_table[c] = Sword; for (c = '0'; c <= '9'; c++) re_syntax_table[c] = Sword; done = 1; } #endif /* SYNTAX_TABLE */ #endif /* not emacs */ #include "regex.h" /* Number of failure points to allocate space for initially, when matching. If this number is exceeded, more space is allocated, so it is not a hard limit. */ #ifndef NFAILURES #define NFAILURES 80 #endif /* NFAILURES */ /* width of a byte in bits */ #define BYTEWIDTH 8 #ifndef SIGN_EXTEND_CHAR #define SIGN_EXTEND_CHAR(x) (x) #endif static int obscure_syntax = 0; /* Specify the precise syntax of regexp for compilation. This provides for compatibility for various utilities which historically have different, incompatible syntaxes. The argument SYNTAX is a bit-mask containing the two bits RE_NO_BK_PARENS and RE_NO_BK_VBAR. */ int re_set_syntax (syntax) { int ret; ret = obscure_syntax; obscure_syntax = syntax; return ret; } /* re_compile_pattern takes a regular-expression string and converts it into a buffer full of byte commands for matching. PATTERN is the address of the pattern string SIZE is the length of it. BUFP is a struct re_pattern_buffer * which points to the info on where to store the byte commands. This structure contains a char * which points to the actual space, which should have been obtained with malloc. re_compile_pattern may use realloc to grow the buffer space. The number of bytes of commands can be found out by looking in the struct re_pattern_buffer that bufp pointed to, after re_compile_pattern returns. */ #define PATPUSH(ch) (*b++ = (char) (ch)) #define PATFETCH(c) \ {if (p == pend) goto end_of_pattern; \ c = * (unsigned char *) p++; \ if (translate) c = translate[c]; } #define PATFETCH_RAW(c) \ {if (p == pend) goto end_of_pattern; \ c = * (unsigned char *) p++; } #define PATUNFETCH p-- #ifdef MSDOS #define MaxAllocation (1<<14) #else #define MaxAllocation (1<<16) #endif #define EXTEND_BUFFER \ { char *old_buffer = bufp->buffer; \ if (bufp->allocated == MaxAllocation) goto too_big; \ bufp->allocated *= 2; \ if (bufp->allocated > MaxAllocation) bufp->allocated = MaxAllocation; \ if (!(bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated))) \ goto memory_exhausted; \ c = bufp->buffer - old_buffer; \ b += c; \ if (fixup_jump) \ fixup_jump += c; \ if (laststart) \ laststart += c; \ begalt += c; \ if (pending_exact) \ pending_exact += c; \ } #ifdef NEVER #define EXTEND_BUFFER \ { unsigned b_off = b - bufp->buffer, \ f_off, l_off, p_off, \ beg_off = begalt - bufp->buffer; \ if (fixup_jump) \ f_off = fixup_jump - bufp->buffer; \ if (laststart) \ l_off = laststart - bufp->buffer; \ if (pending_exact) \ p_off = pending_exact - bufp->buffer; \ if (bufp->allocated == MaxAllocation) goto too_big; \ bufp->allocated *= 2; \ if (bufp->allocated > MaxAllocation) bufp->allocated = MaxAllocation; \ if (!(bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated))) \ goto memory_exhausted; \ b = bufp->buffer + b_off; \ if (fixup_jump) \ fixup_jump = bufp->buffer + f_off; \ if (laststart) \ laststart = bufp->buffer + l_off; \ begalt = bufp->buffer + beg_off; \ if (pending_exact) \ pending_exact = bufp->buffer + p_off; \ } #endif static int store_jump (), insert_jump (); char * re_compile_pattern (pattern, size, bufp) char *pattern; int size; struct re_pattern_buffer *bufp; { register char *b = bufp->buffer; register char *p = pattern; char *pend = pattern + size; register unsigned c, c1; char *p1; unsigned char *translate = (unsigned char *) bufp->translate; /* address of the count-byte of the most recently inserted "exactn" command. This makes it possible to tell whether a new exact-match character can be added to that command or requires a new "exactn" command. */ char *pending_exact = 0; /* address of the place where a forward-jump should go to the end of the containing expression. Each alternative of an "or", except the last, ends with a forward-jump of this sort. */ char *fixup_jump = 0; /* address of start of the most recently finished expression. This tells postfix * where to find the start of its operand. */ char *laststart = 0; /* In processing a repeat, 1 means zero matches is allowed */ char zero_times_ok; /* In processing a repeat, 1 means many matches is allowed */ char many_times_ok; /* address of beginning of regexp, or inside of last \( */ char *begalt = b; /* Stack of information saved by \( and restored by \). Four stack elements are pushed by each \(: First, the value of b. Second, the value of fixup_jump. Third, the value of regnum. Fourth, the value of begalt. */ int stackb[40]; int *stackp = stackb; int *stacke = stackb + 40; int *stackt; /* Counts \('s as they are encountered. Remembered for the matching \), where it becomes the "register number" to put in the stop_memory command */ int regnum = 1; bufp->fastmap_accurate = 0; #ifndef emacs #ifndef SYNTAX_TABLE /* * Initialize the syntax table. */ init_syntax_once(); #endif #endif if (bufp->allocated == 0) { bufp->allocated = 28; if (bufp->buffer) /* EXTEND_BUFFER loses when bufp->allocated is 0 */ bufp->buffer = (char *) realloc (bufp->buffer, 28); else /* Caller did not allocate a buffer. Do it for him */ bufp->buffer = (char *) malloc (28); if (!bufp->buffer) goto memory_exhausted; begalt = b = bufp->buffer; } while (p != pend) { if (b - bufp->buffer > bufp->allocated - 10) /* Note that EXTEND_BUFFER clobbers c */ EXTEND_BUFFER; PATFETCH (c); switch (c) { case '$': if (obscure_syntax & RE_TIGHT_VBAR) { if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS) && p != pend) goto normal_char; /* Make operand of last vbar end before this `$'. */ if (fixup_jump) store_jump (fixup_jump, jump, b); fixup_jump = 0; PATPUSH (endline); break; } /* $ means succeed if at end of line, but only in special contexts. If randomly in the middle of a pattern, it is a normal character. */ if (p == pend || *p == '\n' || (obscure_syntax & RE_CONTEXT_INDEP_OPS) || (obscure_syntax & RE_NO_BK_PARENS ? *p == ')' : *p == '\\' && p[1] == ')') || (obscure_syntax & RE_NO_BK_VBAR ? *p == '|' : *p == '\\' && p[1] == '|')) { PATPUSH (endline); break; } goto normal_char; case '^': /* ^ means succeed if at beg of line, but only if no preceding pattern. */ if (laststart && p[-2] != '\n' && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS)) goto normal_char; if (obscure_syntax & RE_TIGHT_VBAR) { if (p != pattern + 1 && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS)) goto normal_char; PATPUSH (begline); begalt = b; } else PATPUSH (begline); break; case '+': case '?': if (obscure_syntax & RE_BK_PLUS_QM) goto normal_char; handle_plus: case '*': /* If there is no previous pattern, char not special. */ if (!laststart && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS)) goto normal_char; /* If there is a sequence of repetition chars, collapse it down to equivalent to just one. */ zero_times_ok = 0; many_times_ok = 0; while (1) { zero_times_ok |= c != '+'; many_times_ok |= c != '?'; if (p == pend) break; PATFETCH (c); if (c == '*') ; else if (!(obscure_syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')) ; else if ((obscure_syntax & RE_BK_PLUS_QM) && c == '\\') { int c1; PATFETCH (c1); if (!(c1 == '+' || c1 == '?')) { PATUNFETCH; PATUNFETCH; break; } c = c1; } else { PATUNFETCH; break; } } /* Star, etc. applied to an empty pattern is equivalent to an empty pattern. */ if (!laststart) break; /* Now we know whether 0 matches is allowed, and whether 2 or more matches is allowed. */ if (many_times_ok) { /* If more than one repetition is allowed, put in a backward jump at the end. */ store_jump (b, maybe_finalize_jump, laststart - 3); b += 3; } insert_jump (on_failure_jump, laststart, b + 3, b); pending_exact = 0; b += 3; if (!zero_times_ok) { /* At least one repetition required: insert before the loop a skip over the initial on-failure-jump instruction */ insert_jump (dummy_failure_jump, laststart, laststart + 6, b); b += 3; } break; case '.': laststart = b; PATPUSH (anychar); break; case '[': while (b - bufp->buffer > bufp->allocated - 3 - (1 << BYTEWIDTH) / BYTEWIDTH) /* Note that EXTEND_BUFFER clobbers c */ EXTEND_BUFFER; laststart = b; if (*p == '^') PATPUSH (charset_not), p++; else PATPUSH (charset); p1 = p; PATPUSH ((1 << BYTEWIDTH) / BYTEWIDTH); /* Clear the whole map */ bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH); /* Read in characters and ranges, setting map bits */ while (1) { PATFETCH (c); /* If awk, \ escapes characters inside [...]. */ if ((obscure_syntax & RE_AWK_CLASS_HACK) && c == '\\') { PATFETCH(c1); b[c1 / BYTEWIDTH] |= 1 << (c1 % BYTEWIDTH); continue; } if (c == ']' && p != p1 + 1) break; if (*p == '-' && p[1] != ']') { PATFETCH (c1); PATFETCH (c1); while (c <= c1) b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH), c++; } else { b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH); } } /* Discard any bitmap bytes that are all 0 at the end of the map. Decrement the map-length byte too. */ while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) b[-1]--; b += b[-1]; break; case '(': if (! (obscure_syntax & RE_NO_BK_PARENS)) goto normal_char; else goto handle_open; case ')': if (! (obscure_syntax & RE_NO_BK_PARENS)) goto normal_char; else goto handle_close; case '\n': if (! (obscure_syntax & RE_NEWLINE_OR)) goto normal_char; else goto handle_bar; case '|': if (! (obscure_syntax & RE_NO_BK_VBAR)) goto normal_char; else goto handle_bar; case '\\': if (p == pend) goto invalid_pattern; PATFETCH_RAW (c); switch (c) { case '(': if (obscure_syntax & RE_NO_BK_PARENS) goto normal_backsl; handle_open: if (stackp == stacke) goto nesting_too_deep; if (regnum < RE_NREGS) { PATPUSH (start_memory); PATPUSH (regnum); } *stackp++ = b - bufp->buffer; *stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0; *stackp++ = regnum++; *stackp++ = begalt - bufp->buffer; fixup_jump = 0; laststart = 0; begalt = b; break; case ')': if (obscure_syntax & RE_NO_BK_PARENS) goto normal_backsl; handle_close: if (stackp == stackb) goto unmatched_close; begalt = *--stackp + bufp->buffer; if (fixup_jump) store_jump (fixup_jump, jump, b); if (stackp[-1] < RE_NREGS) { PATPUSH (stop_memory); PATPUSH (stackp[-1]); } stackp -= 2; fixup_jump = 0; if (*stackp) fixup_jump = *stackp + bufp->buffer - 1; laststart = *--stackp + bufp->buffer; break; case '|': if (obscure_syntax & RE_NO_BK_VBAR) goto normal_backsl; handle_bar: insert_jump (on_failure_jump, begalt, b + 6, b); pending_exact = 0; b += 3; if (fixup_jump) store_jump (fixup_jump, jump, b); fixup_jump = b; b += 3; laststart = 0; begalt = b; break; #ifdef emacs case '=': PATPUSH (at_dot); break; case 's': laststart = b; PATPUSH (syntaxspec); PATFETCH (c); PATPUSH (syntax_spec_code[c]); break; case 'S': laststart = b; PATPUSH (notsyntaxspec); PATFETCH (c); PATPUSH (syntax_spec_code[c]); break; #endif /* emacs */ case 'w': laststart = b; PATPUSH (wordchar); break; case 'W': laststart = b; PATPUSH (notwordchar); break; case '<': PATPUSH (wordbeg); break; case '>': PATPUSH (wordend); break; case 'b': PATPUSH (wordbound); break; case 'B': PATPUSH (notwordbound); break; case '`': PATPUSH (begbuf); break; case '\'': PATPUSH (endbuf); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c1 = c - '0'; if (c1 >= regnum) goto normal_char; for (stackt = stackp - 2; stackt > stackb; stackt -= 4) if (*stackt == c1) goto normal_char; laststart = b; PATPUSH (duplicate); PATPUSH (c1); break; case '+': case '?': if (obscure_syntax & RE_BK_PLUS_QM) goto handle_plus; default: normal_backsl: /* You might think it would be useful for \ to mean not to translate; but if we don't translate it it will never match anything. */ if (translate) c = translate[c]; goto normal_char; } break; default: normal_char: if (!pending_exact || pending_exact + *pending_exact + 1 != b || *pending_exact == 0177 || *p == '*' || *p == '^' || ((obscure_syntax & RE_BK_PLUS_QM) ? *p == '\\' && (p[1] == '+' || p[1] == '?') : (*p == '+' || *p == '?'))) { laststart = b; PATPUSH (exactn); pending_exact = b; PATPUSH (0); } PATPUSH (c); (*pending_exact)++; } } if (fixup_jump) store_jump (fixup_jump, jump, b); if (stackp != stackb) goto unmatched_open; bufp->used = b - bufp->buffer; return 0; invalid_pattern: return "Invalid regular expression"; unmatched_open: return "Unmatched \\("; unmatched_close: return "Unmatched \\)"; end_of_pattern: return "Premature end of regular expression"; nesting_too_deep: return "Nesting too deep"; too_big: return "Regular expression too big"; memory_exhausted: return "Memory exhausted"; } /* Store where `from' points a jump operation to jump to where `to' points. `opcode' is the opcode to store. */ static int store_jump (from, opcode, to) char *from, *to; char opcode; { from[0] = opcode; from[1] = (to - (from + 3)) & 0377; from[2] = (to - (from + 3)) >> 8; } /* Open up space at char FROM, and insert there a jump to TO. CURRENT_END gives te end of the storage no in use, so we know how much data to copy up. OP is the opcode of the jump to insert. If you call this function, you must zero out pending_exact. */ static int insert_jump (op, from, to, current_end) char op; char *from, *to, *current_end; { register char *pto = current_end + 3; register char *pfrom = current_end; while (pfrom != from) *--pto = *--pfrom; store_jump (from, op, to); } /* Given a pattern, compute a fastmap from it. The fastmap records which of the (1 << BYTEWIDTH) possible characters can start a string that matches the pattern. This fastmap is used by re_search to skip quickly over totally implausible text. The caller must supply the address of a (1 << BYTEWIDTH)-byte data area as bufp->fastmap. The other components of bufp describe the pattern to be used. */ void re_compile_fastmap (bufp) struct re_pattern_buffer *bufp; { unsigned char *pattern = (unsigned char *) bufp->buffer; int size = bufp->used; register char *fastmap = bufp->fastmap; register unsigned char *p = pattern; register unsigned char *pend = pattern + size; register int j, k; unsigned char *translate = (unsigned char *) bufp->translate; unsigned char *stackb[NFAILURES]; unsigned char **stackp = stackb; bzero (fastmap, (1 << BYTEWIDTH)); bufp->fastmap_accurate = 1; bufp->can_be_null = 0; while (p) { if (p == pend) { bufp->can_be_null = 1; break; } #ifdef SWITCH_ENUM_BUG switch ((int) ((enum regexpcode) *p++)) #else switch ((enum regexpcode) *p++) #endif { case exactn: if (translate) fastmap[translate[p[1]]] = 1; else fastmap[p[1]] = 1; break; case begline: case before_dot: case at_dot: case after_dot: case begbuf: case endbuf: case wordbound: case notwordbound: case wordbeg: case wordend: continue; case endline: if (translate) fastmap[translate['\n']] = 1; else fastmap['\n'] = 1; if (bufp->can_be_null != 1) bufp->can_be_null = 2; break; case finalize_jump: case maybe_finalize_jump: case jump: case dummy_failure_jump: bufp->can_be_null = 1; j = *p++ & 0377; j += SIGN_EXTEND_CHAR (*(char *)p) << 8; p += j + 1; /* The 1 compensates for missing ++ above */ if (j > 0) continue; /* Jump backward reached implies we just went through the body of a loop and matched nothing. Opcode jumped to should be an on_failure_jump. Just treat it like an ordinary jump. For a * loop, it has pushed its failure point already; if so, discard that as redundant. */ if ((enum regexpcode) *p != on_failure_jump) continue; p++; j = *p++ & 0377; j += SIGN_EXTEND_CHAR (*(char *)p) << 8; p += j + 1; /* The 1 compensates for missing ++ above */ if (stackp != stackb && *stackp == p) stackp--; continue; case on_failure_jump: j = *p++ & 0377; j += SIGN_EXTEND_CHAR (*(char *)p) << 8; p++; *++stackp = p + j; continue; case start_memory: case stop_memory: p++; continue; case duplicate: bufp->can_be_null = 1; fastmap['\n'] = 1; case anychar: for (j = 0; j < (1 << BYTEWIDTH); j++) if (j != '\n') fastmap[j] = 1; if (bufp->can_be_null) return; /* Don't return; check the alternative paths so we can set can_be_null if appropriate. */ break; case wordchar: for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) == Sword) fastmap[j] = 1; break; case notwordchar: for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) != Sword) fastmap[j] = 1; break; #ifdef emacs case syntaxspec: k = *p++; for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) == (enum syntaxcode) k) fastmap[j] = 1; break; case notsyntaxspec: k = *p++; for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) != (enum syntaxcode) k) fastmap[j] = 1; break; #endif /* emacs */ case charset: for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) { if (translate) fastmap[translate[j]] = 1; else fastmap[j] = 1; } break; case charset_not: /* Chars beyond end of map must be allowed */ for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++) if (translate) fastmap[translate[j]] = 1; else fastmap[j] = 1; for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) { if (translate) fastmap[translate[j]] = 1; else fastmap[j] = 1; } break; } /* Get here means we have successfully found the possible starting characters of one path of the pattern. We need not follow this path any farther. Instead, look at the next alternative remembered in the stack. */ if (stackp != stackb) p = *stackp--; else break; } } /* Like re_search_2, below, but only one string is specified. */ int re_search (pbufp, string, size, startpos, range, regs) struct re_pattern_buffer *pbufp; char *string; int size, startpos, range; struct re_registers *regs; { return re_search_2 (pbufp, 0, 0, string, size, startpos, range, regs, size); } /* Like re_match_2 but tries first a match starting at index STARTPOS, then at STARTPOS + 1, and so on. RANGE is the number of places to try before giving up. If RANGE is negative, the starting positions tried are STARTPOS, STARTPOS - 1, etc. It is up to the caller to make sure that range is not so large as to take the starting position outside of the input strings. The value returned is the position at which the match was found, or -1 if no match was found, or -2 if error (such as failure stack overflow). */ int re_search_2 (pbufp, string1, size1, string2, size2, startpos, range, regs, mstop) struct re_pattern_buffer *pbufp; char *string1, *string2; int size1, size2; int startpos; register int range; struct re_registers *regs; int mstop; { register char *fastmap = pbufp->fastmap; register unsigned char *translate = (unsigned char *) pbufp->translate; int total = size1 + size2; int val; /* Update the fastmap now if not correct already */ if (fastmap && !pbufp->fastmap_accurate) re_compile_fastmap (pbufp); /* Don't waste time in a long search for a pattern that says it is anchored. */ if (pbufp->used > 0 && (enum regexpcode) pbufp->buffer[0] == begbuf && range > 0) { if (startpos > 0) return -1; else range = 1; } while (1) { /* If a fastmap is supplied, skip quickly over characters that cannot possibly be the start of a match. Note, however, that if the pattern can possibly match the null string, we must test it at each starting point so that we take the first null string we get. */ if (fastmap && startpos < total && pbufp->can_be_null != 1) { if (range > 0) { register int lim = 0; register unsigned char *p; int irange = range; if (startpos < size1 && startpos + range >= size1) lim = range - (size1 - startpos); p = ((unsigned char *) &(startpos >= size1 ? string2 - size1 : string1)[startpos]); if (translate) { while (range > lim && !fastmap[translate[*p++]]) range--; } else { while (range > lim && !fastmap[*p++]) range--; } startpos += irange - range; } else { register unsigned char c; if (startpos >= size1) c = string2[startpos - size1]; else c = string1[startpos]; c &= 0xff; if (translate ? !fastmap[translate[c]] : !fastmap[c]) goto advance; } } if (range >= 0 && startpos == total && fastmap && pbufp->can_be_null == 0) return -1; val = re_match_2 (pbufp, string1, size1, string2, size2, startpos, regs, mstop); if (0 <= val) { if (val == -2) return -2; return startpos; } #ifdef C_ALLOCA alloca (0); #endif /* C_ALLOCA */ advance: if (!range) break; if (range > 0) range--, startpos++; else range++, startpos--; } return -1; } #ifndef emacs /* emacs never uses this */ int re_match (pbufp, string, size, pos, regs) struct re_pattern_buffer *pbufp; char *string; int size, pos; struct re_registers *regs; { return re_match_2 (pbufp, 0, 0, string, size, pos, regs, size); } #endif /* emacs */ /* Maximum size of failure stack. Beyond this, overflow is an error. */ int re_max_failures = 2000; static int bcmp_translate(); /* Match the pattern described by PBUFP against data which is the virtual concatenation of STRING1 and STRING2. SIZE1 and SIZE2 are the sizes of the two data strings. Start the match at position POS. Do not consider matching past the position MSTOP. If pbufp->fastmap is nonzero, then it had better be up to date. The reason that the data to match are specified as two components which are to be regarded as concatenated is so this function can be used directly on the contents of an Emacs buffer. -1 is returned if there is no match. -2 is returned if there is an error (such as match stack overflow). Otherwise the value is the length of the substring which was matched. */ int re_match_2 (pbufp, string1, size1, string2, size2, pos, regs, mstop) struct re_pattern_buffer *pbufp; unsigned char *string1, *string2; int size1, size2; int pos; struct re_registers *regs; int mstop; { register unsigned char *p = (unsigned char *) pbufp->buffer; register unsigned char *pend = p + pbufp->used; /* End of first string */ unsigned char *end1; /* End of second string */ unsigned char *end2; /* Pointer just past last char to consider matching */ unsigned char *end_match_1, *end_match_2; register unsigned char *d, *dend; register int mcnt; unsigned char *translate = (unsigned char *) pbufp->translate; /* Failure point stack. Each place that can handle a failure further down the line pushes a failure point on this stack. It consists of two char *'s. The first one pushed is where to resume scanning the pattern; the second pushed is where to resume scanning the strings. If the latter is zero, the failure point is a "dummy". If a failure happens and the innermost failure point is dormant, it discards that failure point and tries the next one. */ unsigned char *initial_stack[2 * NFAILURES]; unsigned char **stackb = initial_stack; unsigned char **stackp = stackb, **stacke = &stackb[2 * NFAILURES]; /* Information on the "contents" of registers. These are pointers into the input strings; they record just what was matched (on this attempt) by some part of the pattern. The start_memory command stores the start of a register's contents and the stop_memory command stores the end. At that point, regstart[regnum] points to the first character in the register, regend[regnum] points to the first character beyond the end of the register, regstart_seg1[regnum] is true iff regstart[regnum] points into string1, and regend_seg1[regnum] is true iff regend[regnum] points into string1. */ unsigned char *regstart[RE_NREGS]; unsigned char *regend[RE_NREGS]; unsigned char regstart_seg1[RE_NREGS], regend_seg1[RE_NREGS]; /* Set up pointers to ends of strings. Don't allow the second string to be empty unless both are empty. */ if (!size2) { string2 = string1; size2 = size1; string1 = 0; size1 = 0; } end1 = string1 + size1; end2 = string2 + size2; /* Compute where to stop matching, within the two strings */ if (mstop <= size1) { end_match_1 = string1 + mstop; end_match_2 = string2; } else { end_match_1 = end1; end_match_2 = string2 + mstop - size1; } /* Initialize \) text positions to -1 to mark ones that no \( or \) has been seen for. */ for (mcnt = 0; mcnt < sizeof (regend) / sizeof (*regend); mcnt++) regend[mcnt] = (unsigned char *) -1; /* `p' scans through the pattern as `d' scans through the data. `dend' is the end of the input string that `d' points within. `d' is advanced into the following input string whenever necessary, but this happens before fetching; therefore, at the beginning of the loop, `d' can be pointing at the end of a string, but it cannot equal string2. */ if (pos <= size1) d = string1 + pos, dend = end_match_1; else d = string2 + pos - size1, dend = end_match_2; /* Write PREFETCH; just before fetching a character with *d. */ #define PREFETCH \ while (d == dend) \ { if (dend == end_match_2) goto fail; /* end of string2 => failure */ \ d = string2; /* end of string1 => advance to string2. */ \ dend = end_match_2; } /* This loop loops over pattern commands. It exits by returning from the function if match is complete, or it drops through if match fails at this starting point in the input data. */ while (1) { if (p == pend) /* End of pattern means we have succeeded! */ { /* If caller wants register contents data back, convert it to indices */ if (regs) { regs->start[0] = pos; if (dend == end_match_1) regs->end[0] = d - string1; else regs->end[0] = d - string2 + size1; for (mcnt = 1; mcnt < RE_NREGS; mcnt++) { if (regend[mcnt] == (unsigned char *) -1) { regs->start[mcnt] = -1; regs->end[mcnt] = -1; continue; } if (regstart_seg1[mcnt]) regs->start[mcnt] = regstart[mcnt] - string1; else regs->start[mcnt] = regstart[mcnt] - string2 + size1; if (regend_seg1[mcnt]) regs->end[mcnt] = regend[mcnt] - string1; else regs->end[mcnt] = regend[mcnt] - string2 + size1; } } if (dend == end_match_1) return (d - string1 - pos); else return d - string2 + size1 - pos; } /* Otherwise match next pattern command */ #ifdef SWITCH_ENUM_BUG switch ((int) ((enum regexpcode) *p++)) #else switch ((enum regexpcode) *p++) #endif { /* \( is represented by a start_memory, \) by a stop_memory. Both of those commands contain a "register number" argument. The text matched within the \( and \) is recorded under that number. Then, \ turns into a `duplicate' command which is followed by the numeric value of as the register number. */ case start_memory: regstart[*p] = d; regstart_seg1[*p++] = (dend == end_match_1); break; case stop_memory: regend[*p] = d; regend_seg1[*p++] = (dend == end_match_1); break; case duplicate: { int regno = *p++; /* Get which register to match against */ register unsigned char *d2, *dend2; d2 = regstart[regno]; dend2 = ((regstart_seg1[regno] == regend_seg1[regno]) ? regend[regno] : end_match_1); while (1) { /* Advance to next segment in register contents, if necessary */ while (d2 == dend2) { if (dend2 == end_match_2) break; if (dend2 == regend[regno]) break; d2 = string2, dend2 = regend[regno]; /* end of string1 => advance to string2. */ } /* At end of register contents => success */ if (d2 == dend2) break; /* Advance to next segment in data being matched, if necessary */ PREFETCH; /* mcnt gets # consecutive chars to compare */ mcnt = dend - d; if (mcnt > dend2 - d2) mcnt = dend2 - d2; /* Compare that many; failure if mismatch, else skip them. */ if (translate ? bcmp_translate (d, d2, mcnt, translate) : bcmp (d, d2, mcnt)) goto fail; d += mcnt, d2 += mcnt; } } break; case anychar: /* fetch a data character */ PREFETCH; /* Match anything but a newline. */ if ((translate ? translate[*d++] : *d++) == '\n') goto fail; break; case charset: case charset_not: { /* Nonzero for charset_not */ int not = 0; register int c; if (*(p - 1) == (unsigned char) charset_not) not = 1; /* fetch a data character */ PREFETCH; if (translate) c = translate [*d]; else c = *d; if (c < *p * BYTEWIDTH && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) not = !not; p += 1 + *p; if (!not) goto fail; d++; break; } case begline: if (d == string1 || d[-1] == '\n') break; goto fail; case endline: if (d == end2 || (d == end1 ? (size2 == 0 || *string2 == '\n') : *d == '\n')) break; goto fail; /* "or" constructs ("|") are handled by starting each alternative with an on_failure_jump that points to the start of the next alternative. Each alternative except the last ends with a jump to the joining point. (Actually, each jump except for the last one really jumps to the following jump, because tensioning the jumps is a hassle.) */ /* The start of a stupid repeat has an on_failure_jump that points past the end of the repeat text. This makes a failure point so that, on failure to match a repetition, matching restarts past as many repetitions have been found with no way to fail and look for another one. */ /* A smart repeat is similar but loops back to the on_failure_jump so that each repetition makes another failure point. */ case on_failure_jump: if (stackp == stacke) { unsigned char **stackx; if (stacke - stackb > re_max_failures * 2) return -2; stackx = (unsigned char **) alloca (2 * (stacke - stackb) * sizeof (char *)); bcopy (stackb, stackx, (stacke - stackb) * sizeof (char *)); stackp = stackx + (stackp - stackb); stacke = stackx + 2 * (stacke - stackb); stackb = stackx; } mcnt = *p++ & 0377; mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8; p++; *stackp++ = mcnt + p; *stackp++ = d; break; /* The end of a smart repeat has an maybe_finalize_jump back. Change it either to a finalize_jump or an ordinary jump. */ case maybe_finalize_jump: mcnt = *p++ & 0377; mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8; p++; { register unsigned char *p2 = p; /* Compare what follows with the begining of the repeat. If we can establish that there is nothing that they would both match, we can change to finalize_jump */ while (p2 != pend && (*p2 == (unsigned char) stop_memory || *p2 == (unsigned char) start_memory)) p2++; if (p2 == pend) p[-3] = (unsigned char) finalize_jump; else if (*p2 == (unsigned char) exactn || *p2 == (unsigned char) endline) { register int c = *p2 == (unsigned char) endline ? '\n' : p2[2]; register unsigned char *p1 = p + mcnt; /* p1[0] ... p1[2] are an on_failure_jump. Examine what follows that */ if (p1[3] == (unsigned char) exactn && p1[5] != c) p[-3] = (unsigned char) finalize_jump; else if (p1[3] == (unsigned char) charset || p1[3] == (unsigned char) charset_not) { int not = p1[3] == (unsigned char) charset_not; if (c < p1[4] * BYTEWIDTH && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) not = !not; /* not is 1 if c would match */ /* That means it is not safe to finalize */ if (!not) p[-3] = (unsigned char) finalize_jump; } } } p -= 2; if (p[-1] != (unsigned char) finalize_jump) { p[-1] = (unsigned char) jump; goto nofinalize; } /* The end of a stupid repeat has a finalize-jump back to the start, where another failure point will be made which will point after all the repetitions found so far. */ case finalize_jump: stackp -= 2; case jump: nofinalize: mcnt = *p++ & 0377; mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8; p += mcnt + 1; /* The 1 compensates for missing ++ above */ break; case dummy_failure_jump: if (stackp == stacke) { unsigned char **stackx = (unsigned char **) alloca (2 * (stacke - stackb) * sizeof (char *)); bcopy (stackb, stackx, (stacke - stackb) * sizeof (char *)); stackp = stackx + (stackp - stackb); stacke = stackx + 2 * (stacke - stackb); stackb = stackx; } *stackp++ = 0; *stackp++ = 0; goto nofinalize; case wordbound: if (d == string1 /* Points to first char */ || d == end2 /* Points to end */ || (d == end1 && size2 == 0)) /* Points to end */ break; if ((SYNTAX (d[-1]) == Sword) != (SYNTAX (d == end1 ? *string2 : *d) == Sword)) break; goto fail; case notwordbound: if (d == string1 /* Points to first char */ || d == end2 /* Points to end */ || (d == end1 && size2 == 0)) /* Points to end */ goto fail; if ((SYNTAX (d[-1]) == Sword) != (SYNTAX (d == end1 ? *string2 : *d) == Sword)) goto fail; break; case wordbeg: if (d == end2 /* Points to end */ || (d == end1 && size2 == 0) /* Points to end */ || SYNTAX (* (d == end1 ? string2 : d)) != Sword) /* Next char not a letter */ goto fail; if (d == string1 /* Points to first char */ || SYNTAX (d[-1]) != Sword) /* prev char not letter */ break; goto fail; case wordend: if (d == string1 /* Points to first char */ || SYNTAX (d[-1]) != Sword) /* prev char not letter */ goto fail; if (d == end2 /* Points to end */ || (d == end1 && size2 == 0) /* Points to end */ || SYNTAX (d == end1 ? *string2 : *d) != Sword) /* Next char not a letter */ break; goto fail; #ifdef emacs case before_dot: if (((d - string2 <= (unsigned) size2) ? d - bf_p2 : d - bf_p1) <= point) goto fail; break; case at_dot: if (((d - string2 <= (unsigned) size2) ? d - bf_p2 : d - bf_p1) == point) goto fail; break; case after_dot: if (((d - string2 <= (unsigned) size2) ? d - bf_p2 : d - bf_p1) >= point) goto fail; break; case wordchar: mcnt = (int) Sword; goto matchsyntax; case syntaxspec: mcnt = *p++; matchsyntax: PREFETCH; if (SYNTAX (*d++) != (enum syntaxcode) mcnt) goto fail; break; case notwordchar: mcnt = (int) Sword; goto matchnotsyntax; case notsyntaxspec: mcnt = *p++; matchnotsyntax: PREFETCH; if (SYNTAX (*d++) == (enum syntaxcode) mcnt) goto fail; break; #else case wordchar: PREFETCH; if (SYNTAX (*d++) == 0) goto fail; break; case notwordchar: PREFETCH; if (SYNTAX (*d++) != 0) goto fail; break; #endif /* not emacs */ case begbuf: if (d == string1) /* Note, d cannot equal string2 */ break; /* unless string1 == string2. */ goto fail; case endbuf: if (d == end2 || (d == end1 && size2 == 0)) break; goto fail; case exactn: /* Match the next few pattern characters exactly. mcnt is how many characters to match. */ mcnt = *p++; if (translate) { do { PREFETCH; if (translate[*d++] != *p++) goto fail; } while (--mcnt); } else { do { PREFETCH; if (*d++ != *p++) goto fail; } while (--mcnt); } break; } continue; /* Successfully matched one pattern command; keep matching */ /* Jump here if any matching operation fails. */ fail: if (stackp != stackb) /* A restart point is known. Restart there and pop it. */ { if (!stackp[-2]) { /* If innermost failure point is dormant, flush it and keep looking */ stackp -= 2; goto fail; } d = *--stackp; p = *--stackp; if (d >= string1 && d <= end1) dend = end_match_1; } else break; /* Matching at this starting point really fails! */ } return -1; /* Failure to match */ } static int bcmp_translate (s1, s2, len, translate) unsigned char *s1, *s2; register int len; unsigned char *translate; { register unsigned char *p1 = s1, *p2 = s2; while (len) { if (translate [*p1++] != translate [*p2++]) return 1; len--; } return 0; } /* Entry points compatible with bsd4.2 regex library */ #ifndef emacs static struct re_pattern_buffer re_comp_buf; char * re_comp (s) char *s; { if (!s) { if (!re_comp_buf.buffer) return "No previous regular expression"; return 0; } if (!re_comp_buf.buffer) { if (!(re_comp_buf.buffer = (char *) malloc (200))) return "Memory exhausted"; re_comp_buf.allocated = 200; if (!(re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH))) return "Memory exhausted"; } return re_compile_pattern (s, strlen (s), &re_comp_buf); } int re_exec (s) char *s; { int len = strlen (s); return 0 <= re_search (&re_comp_buf, s, len, 0, len, 0); } #endif /* emacs */ #ifdef test #include /* Indexed by a character, gives the upper case equivalent of the character */ static char upcase[0400] = { 000, 001, 002, 003, 004, 005, 006, 007, 010, 011, 012, 013, 014, 015, 016, 017, 020, 021, 022, 023, 024, 025, 026, 027, 030, 031, 032, 033, 034, 035, 036, 037, 040, 041, 042, 043, 044, 045, 046, 047, 050, 051, 052, 053, 054, 055, 056, 057, 060, 061, 062, 063, 064, 065, 066, 067, 070, 071, 072, 073, 074, 075, 076, 077, 0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117, 0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127, 0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137, 0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117, 0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127, 0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177, 0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207, 0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217, 0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227, 0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237, 0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247, 0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257, 0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267, 0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277, 0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307, 0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317, 0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327, 0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337, 0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347, 0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357, 0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367, 0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377 }; main (argc, argv) int argc; char **argv; { char pat[80]; struct re_pattern_buffer buf; int i; char c; char fastmap[(1 << BYTEWIDTH)]; /* Allow a command argument to specify the style of syntax. */ if (argc > 1) obscure_syntax = atoi (argv[1]); buf.allocated = 40; buf.buffer = (char *) malloc (buf.allocated); buf.fastmap = fastmap; buf.translate = upcase; while (1) { gets (pat); if (*pat) { re_compile_pattern (pat, strlen(pat), &buf); for (i = 0; i < buf.used; i++) printchar (buf.buffer[i]); putchar ('\n'); printf ("%d allocated, %d used.\n", buf.allocated, buf.used); re_compile_fastmap (&buf); printf ("Allowed by fastmap: "); for (i = 0; i < (1 << BYTEWIDTH); i++) if (fastmap[i]) printchar (i); putchar ('\n'); } gets (pat); /* Now read the string to match against */ i = re_match (&buf, pat, strlen (pat), 0, 0); printf ("Match value %d.\n", i); } } #ifdef NOTDEF print_buf (bufp) struct re_pattern_buffer *bufp; { int i; printf ("buf is :\n----------------\n"); for (i = 0; i < bufp->used; i++) printchar (bufp->buffer[i]); printf ("\n%d allocated, %d used.\n", bufp->allocated, bufp->used); printf ("Allowed by fastmap: "); for (i = 0; i < (1 << BYTEWIDTH); i++) if (bufp->fastmap[i]) printchar (i); printf ("\nAllowed by translate: "); if (bufp->translate) for (i = 0; i < (1 << BYTEWIDTH); i++) if (bufp->translate[i]) printchar (i); printf ("\nfastmap is%s accurate\n", bufp->fastmap_accurate ? "" : "n't"); printf ("can %s be null\n----------", bufp->can_be_null ? "" : "not"); } #endif printchar (c) char c; { if (c < 041 || c >= 0177) { putchar ('\\'); putchar (((c >> 6) & 3) + '0'); putchar (((c >> 3) & 7) + '0'); putchar ((c & 7) + '0'); } else putchar (c); } #endif /* test */ gawk-2.11/regex.h 644 11660 0 30764 4505764061 12072 0ustar hackwheel/* Definitions for data structures callers pass the regex library. Copyright (C) 1985 Free Software Foundation, Inc. NO WARRANTY BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. GENERAL PUBLIC LICENSE TO COPY 1. You may copy and distribute verbatim copies of this source file as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy a valid copyright notice "Copyright (C) 1985 Free Software Foundation, Inc."; and include following the copyright notice a verbatim copy of the above disclaimer of warranty and of this License. You may charge a distribution fee for the physical act of transferring a copy. 2. You may modify your copy or copies of this source file or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains or is a derivative of this program or any part thereof, to be licensed at no charge to all third parties on terms identical to those contained in this License Agreement (except that you may choose to grant more extensive warranty protection to some or all third parties, at your option). c) You may charge a distribution fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another unrelated program with this program (or its derivative) on a volume of a storage or distribution medium does not bring the other program under the scope of these terms. 3. You may copy and distribute this program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal shipping charge) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs. 4. You may not copy, sublicense, distribute or transfer this program except as expressly provided under this License Agreement. Any attempt otherwise to copy, sublicense, distribute or transfer this program is void and your rights to use the program under this License agreement shall be automatically terminated. However, parties who have received computer software programs from you with this License Agreement will not have their licenses terminated so long as such parties remain in full compliance. 5. If you wish to incorporate parts of this program into other free programs whose distribution conditions are different, write to the Free Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet worked out a simple rule that can be stated here, but we will often permit this. We will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software. In other words, you are welcome to use, share and improve this program. You are forbidden to forbid anyone else to use, share and improve what you give them. Help stamp out software-hoarding! */ /* Define number of parens for which we record the beginnings and ends. This affects how much space the `struct re_registers' type takes up. */ #ifndef RE_NREGS #define RE_NREGS 10 #endif /* These bits are used in the obscure_syntax variable to choose among alternative regexp syntaxes. */ /* 1 means plain parentheses serve as grouping, and backslash parentheses are needed for literal searching. 0 means backslash-parentheses are grouping, and plain parentheses are for literal searching. */ #define RE_NO_BK_PARENS 1 /* 1 means plain | serves as the "or"-operator, and \| is a literal. 0 means \| serves as the "or"-operator, and | is a literal. */ #define RE_NO_BK_VBAR 2 /* 0 means plain + or ? serves as an operator, and \+, \? are literals. 1 means \+, \? are operators and plain +, ? are literals. */ #define RE_BK_PLUS_QM 4 /* 1 means | binds tighter than ^ or $. 0 means the contrary. */ #define RE_TIGHT_VBAR 8 /* 1 means treat \n as an _OR operator 0 means treat it as a normal character */ #define RE_NEWLINE_OR 16 /* 0 means that a special characters (such as *, ^, and $) always have their special meaning regardless of the surrounding context. 1 means that special characters may act as normal characters in some contexts. Specifically, this applies to: ^ - only special at the beginning, or after ( or | $ - only special at the end, or before ) or | *, +, ? - only special when not after the beginning, (, or | */ #define RE_CONTEXT_INDEP_OPS 32 /* 0 means that \ before anything inside [ and ] is taken as a real \. 1 means that such a \ escapes the following character This is a special case for AWK. */ #define RE_AWK_CLASS_HACK 64 /* Now define combinations of bits for the standard possibilities. */ #define RE_SYNTAX_POSIX_EGREP (RE_NO_BK_PARENS | RE_NO_BK_VBAR \ | RE_CONTEXT_INDEP_OPS) #define RE_SYNTAX_AWK (RE_SYNTAX_POSIX_EGREP | RE_AWK_CLASS_HACK) #define RE_SYNTAX_EGREP (RE_SYNTAX_POSIX_EGREP | RE_NEWLINE_OR) #define RE_SYNTAX_GREP (RE_BK_PLUS_QM | RE_NEWLINE_OR) #define RE_SYNTAX_EMACS 0 /* This data structure is used to represent a compiled pattern. */ struct re_pattern_buffer { char *buffer; /* Space holding the compiled pattern commands. */ int allocated; /* Size of space that buffer points to */ int used; /* Length of portion of buffer actually occupied */ char *fastmap; /* Pointer to fastmap, if any, or zero if none. */ /* re_search uses the fastmap, if there is one, to skip quickly over totally implausible characters */ char *translate; /* Translate table to apply to all characters before comparing. Or zero for no translation. The translation is applied to a pattern when it is compiled and to data when it is matched. */ char fastmap_accurate; /* Set to zero when a new pattern is stored, set to one when the fastmap is updated from it. */ char can_be_null; /* Set to one by compiling fastmap if this pattern might match the null string. It does not necessarily match the null string in that case, but if this is zero, it cannot. 2 as value means can match null string but at end of range or before a character listed in the fastmap. */ }; /* Structure to store "register" contents data in. Pass the address of such a structure as an argument to re_match, etc., if you want this information back. start[i] and end[i] record the string matched by \( ... \) grouping i, for i from 1 to RE_NREGS - 1. start[0] and end[0] record the entire string matched. */ struct re_registers { int start[RE_NREGS]; int end[RE_NREGS]; }; /* These are the command codes that appear in compiled regular expressions, one per byte. Some command codes are followed by argument bytes. A command code can specify any interpretation whatever for its arguments. Zero-bytes may appear in the compiled regular expression. */ enum regexpcode { unused, exactn, /* followed by one byte giving n, and then by n literal bytes */ begline, /* fails unless at beginning of line */ endline, /* fails unless at end of line */ jump, /* followed by two bytes giving relative address to jump to */ on_failure_jump, /* followed by two bytes giving relative address of place to resume at in case of failure. */ finalize_jump, /* Throw away latest failure point and then jump to address. */ maybe_finalize_jump, /* Like jump but finalize if safe to do so. This is used to jump back to the beginning of a repeat. If the command that follows this jump is clearly incompatible with the one at the beginning of the repeat, such that we can be sure that there is no use backtracking out of repetitions already completed, then we finalize. */ dummy_failure_jump, /* jump, and push a dummy failure point. This failure point will be thrown away if an attempt is made to use it for a failure. A + construct makes this before the first repeat. */ anychar, /* matches any one character */ charset, /* matches any one char belonging to specified set. First following byte is # bitmap bytes. Then come bytes for a bit-map saying which chars are in. Bits in each byte are ordered low-bit-first. A character is in the set if its bit is 1. A character too large to have a bit in the map is automatically not in the set */ charset_not, /* similar but match any character that is NOT one of those specified */ start_memory, /* starts remembering the text that is matched and stores it in a memory register. followed by one byte containing the register number. Register numbers must be in the range 0 through NREGS. */ stop_memory, /* stops remembering the text that is matched and stores it in a memory register. followed by one byte containing the register number. Register numbers must be in the range 0 through NREGS. */ duplicate, /* match a duplicate of something remembered. Followed by one byte containing the index of the memory register. */ before_dot, /* Succeeds if before dot */ at_dot, /* Succeeds if at dot */ after_dot, /* Succeeds if after dot */ begbuf, /* Succeeds if at beginning of buffer */ endbuf, /* Succeeds if at end of buffer */ wordchar, /* Matches any word-constituent character */ notwordchar, /* Matches any char that is not a word-constituent */ wordbeg, /* Succeeds if at word beginning */ wordend, /* Succeeds if at word end */ wordbound, /* Succeeds if at a word boundary */ notwordbound, /* Succeeds if not at a word boundary */ syntaxspec, /* Matches any character whose syntax is specified. followed by a byte which contains a syntax code, Sword or such like */ notsyntaxspec /* Matches any character whose syntax differs from the specified. */ }; extern char *re_compile_pattern (); /* Is this really advertised? */ extern void re_compile_fastmap (); extern int re_search (), re_search_2 (); extern int re_match (), re_match_2 (); /* 4.2 bsd compatibility (yuck) */ extern char *re_comp (); extern int re_exec (); #ifdef SYNTAX_TABLE extern char *re_syntax_table; #endif gawk-2.11/gawk.1 644 11660 0 101415 4516371214 11626 0ustar hackwheel.TH GAWK 1 "August 24 1989" "Free Software Foundation" .SH NAME gawk \- pattern scanning and processing language .SH SYNOPSIS .B gawk .ig [ .B \-d ] [ .B \-D ] .. [ .B \-a ] [ .B \-e ] [ .B \-c ] [ .B \-C ] [ .B \-V ] [ .BI \-F\^ fs ] [ .B \-v .IR var = val ] .B \-f .I program-file [ .B \-\^\- ] file .\^.\^. .br .B gawk .ig [ .B \-d ] [ .B \-D ] .. [ .B \-a ] [ .B \-e ] [ .B \-c ] [ .B \-C ] [ .B \-V ] [ .BI \-F\^ fs ] [ .B \-v .IR var = val ] [ .B \-\^\- ] .I program-text file .\^.\^. .SH DESCRIPTION .I Gawk is the GNU Project's implementation of the AWK programming language. It conforms to the definition and description of the language in .IR "The AWK Programming Language" , by Aho, Kernighan, and Weinberger, with the additional features defined in the System V Release 4 version of \s-1UNIX\s+1 .IR awk , and some GNU-specific extensions. .PP The command line consists of options to .I gawk itself, the AWK program text (if not supplied via the .B \-f option), and values to be made available in the .B ARGC and .B ARGV pre-defined AWK variables. .PP .I Gawk accepts the following options, which should be available on any implementation of the AWK language. .TP .BI \-F fs Use .I fs for the input field separator (the value of the .B FS predefined variable). .TP \fB\-v\fI var\fR\^=\^\fIval\fR Assign the value .IR val , to the variable .IR var , before execution of the program begins. Such variable values are available to the .B BEGIN block of an AWK program. .TP .BI \-f " program-file" Read the AWK program source from the file .IR program-file , instead of from the first command line argument. Multiple .B \-f options may be used. .TP .B \-\^\- Signal the end of options. This is useful to allow further arguments to the AWK program itself to start with a ``\-''. This is mainly for consistency with the argument parsing convention used by most other System V programs. .PP The following options are specific to the GNU implementation. .TP .B \-a Use AWK style regular expressions as described in the book. This is the current default, but may not be when the POSIX P1003.2 standard is finalized. It is orthogonal to .BR \-c . .TP .B \-e Use .IR egrep (1) style regular expressions as described in POSIX standard. This may become the default when the POSIX P1003.2 standard is finalized. It is orthogonal to .BR \-c . .TP .B \-c Run in .I compatibility mode. In compatibility mode, .I gawk behaves identically to \s-1UNIX\s+1 .IR awk ; none of the GNU-specific extensions are recognized. .TP .B \-C Print the short version of the GNU copyright information message on the error output. This option may disappear in a future version of .IR gawk . .TP .B \-V Print version information for this particular copy of .I gawk on the error output. This is useful mainly for knowing if the current copy of .I gawk on your system is up to date with respect to whatever the Free Software Foundation is distributing. This option may disappear in a future version of .IR gawk . .PP Any other options are flagged as illegal, but are otherwise ignored. .PP An AWK program consists of a sequence of pattern-action statements and optional function definitions. .RS .PP \fIpattern\fB { \fIaction statements\fB }\fR .br \fBfunction \fIname\fB(\fIparameter list\fB) { \fIstatements\fB }\fR .RE .PP .I Gawk first reads the program source from the .IR program-file (s) if specified, or from the first non-option argument on the command line. The .B \-f option may be used multiple times on the command line. .I Gawk will read the program text as if all the .IR program-file s had been concatenated together. This is useful for building libraries of AWK functions, without having to include them in each new AWK program that uses them. To use a library function in a file from a program typed in on the command line, specify .B /dev/tty as one of the .IR program-file s, type your program, and end it with a .B ^D (control-d). .PP The environment variable .B AWKPATH specifies a search path to use when finding source files named with the .B \-f option. If this variable does not exist, the default path is \fB".:/usr/lib/awk:/usr/local/lib/awk"\fR. If a file name given to the .B \-f option contains a ``/'' character, no path search is performed. .PP .I Gawk compiles the program into an internal form, executes the code in the .B BEGIN block(s) (if any), and then proceeds to read each file named in the .B ARGV array. If there are no files named on the command line, .I gawk reads the standard input. .PP If a ``file'' named on the command line has the form .IB var = val it is treated as a variable assignment. The variable .I var will be assigned the value .IR val . This is most useful for dynamically assigning values to the variables AWK uses to control how input is broken into fields and records. It is also useful for controlling state if multiple passes are needed over a single data file. .PP For each line in the input, .I gawk tests to see if it matches any .I pattern in the AWK program. For each pattern that the line matches, the associated .I action is executed. .SH VARIABLES AND FIELDS AWK variables are dynamic; they come into existence when they are first used. Their values are either floating-point numbers or strings, depending upon how they are used. AWK also has one dimension arrays; multiply dimensioned arrays may be simulated. There are several pre-defined variables that AWK sets as a program runs; these will be described as needed and summarized below. .SS Fields .PP As each input line is read, .I gawk splits the line into .IR fields , using the value of the .B FS variable as the field separator. If .B FS is a single character, fields are separated by that character. Otherwise, .B FS is expected to be a full regular expression. In the special case that .B FS is a single blank, fields are separated by runs of blanks and/or tabs. Note that the value of .B IGNORECASE (see below) will also affect how fields are split when .B FS is a regular expression. .PP Each field in the input line may be referenced by its position, .BR $1 , .BR $2 , and so on. .B $0 is the whole line. The value of a field may be assigned to as well. Fields need not be referenced by constants: .RS .PP .ft B n = 5 .br print $n .ft R .RE .PP prints the fifth field in the input line. The variable .B NF is set to the total number of fields in the input line. .PP References to non-existent fields (i.e. fields after .BR $NF ), produce the null-string. However, assigning to a non-existent field (e.g., .BR "$(NF+2) = 5" ) will increase the value of .BR NF , create any intervening fields with the null string as their value, and cause the value of .B $0 to be recomputed, with the fields being separated by the value of .BR OFS . .SS Built-in Variables .PP AWK's built-in variables are: .PP .RS .TP \l'\fBIGNORECASE\fR' .B ARGC the number of command line arguments (does not include options to .IR gawk , or the program source). .TP \l'\fBIGNORECASE\fR' .B ARGV array of command line arguments. The array is indexed from 0 to .B ARGC \- 1. Dynamically changing the contents of .B ARGV can control the files used for data. .TP \l'\fBIGNORECASE\fR' .B ENVIRON An array containing the values of the current environment. The array is indexed by the environment variables, each element being the value of that variable (e.g., \fBENVIRON["HOME"]\fP might be .BR /u/arnold ). Changing this array does not affect the environment seen by programs which .I gawk spawns via redirection or the .B system function. (This may change in a future version of .IR gawk .) .TP \l'\fBIGNORECASE\fR' .B FILENAME the name of the current input file. If no files are specified on the command line, the value of .B FILENAME is ``\-''. .TP \l'\fBIGNORECASE\fR' .B FNR the input record number in the current input file. .TP \l'\fBIGNORECASE\fR' .B FS the input field separator, a blank by default. .TP \l'\fBIGNORECASE\fR' .B IGNORECASE Controls the case-sensitivity of all regular expression operations. If .B IGNORECASE has a non-zero value, then pattern matching in rules, field splitting with .BR FS , regular expression matching with .B ~ and .BR !~ , and the .BR gsub() , .BR index() , .BR match() , .BR split() , and .B sub() pre-defined functions will all ignore case when doing regular expression operations. Thus, if .B IGNORECASE is not equal to zero, .B /aB/ matches all of the strings \fB"ab"\fP, \fB"aB"\fP, \fB"Ab"\fP, and \fB"AB"\fP. As with all AWK variables, the initial value of .B IGNORECASE is zero, so all regular expression operations are normally case-sensitive. .TP \l'\fBIGNORECASE\fR' .B NF the number of fields in the current input record. .TP \l'\fBIGNORECASE\fR' .B NR the total number of input records seen so far. .TP \l'\fBIGNORECASE\fR' .B OFMT the output format for numbers, .B %.6g by default. .TP \l'\fBIGNORECASE\fR' .B OFS the output field separator, a blank by default. .TP \l'\fBIGNORECASE\fR' .B ORS the output record separator, by default a newline. .TP \l'\fBIGNORECASE\fR' .B RS the input record separator, by default a newline. .B RS is exceptional in that only the first character of its string value is used for separating records. If .B RS is set to the null string, then records are separated by blank lines. When .B RS is set to the null string, then the newline character always acts as a field separator, in addition to whatever value .B FS may have. .TP \l'\fBIGNORECASE\fR' .B RSTART the index of the first character matched by .BR match() ; 0 if no match. .TP \l'\fBIGNORECASE\fR' .B RLENGTH the length of the string matched by .BR match() ; \-1 if no match. .TP \l'\fBIGNORECASE\fR' .B SUBSEP the character used to separate multiple subscripts in array elements, by default \fB"\e034"\fR. .RE .SS Arrays .PP Arrays are subscripted with an expression between square brackets .RB ( [ " and " ] ). If the expression is an expression list .RI ( expr ", " expr " ...)" then the array subscript is a string consisting of the concatenation of the (string) value of each expression, separated by the value of the .B SUBSEP variable. This facility is used to simulate multiply dimensioned arrays. For example: .PP .RS .ft B i = "A" ;\^ j = "B" ;\^ k = "C" .br x[i, j, k] = "hello, world\en" .ft R .RE .PP assigns the string \fB"hello, world\en"\fR to the element of the array .B x which is indexed by the string \fB"A\e034B\e034C"\fR. All arrays in AWK are associative, i.e. indexed by string values. .PP The special operator .B in may be used in an .B if or .B while statement to see if an array has an index consisting of a particular value. .PP .RS .ft B .nf if (val in array) print array[val] .fi .ft .RE .PP If the array has multiple subscripts, use .BR "(i, j) in array" . .PP The .B in construct may also be used in a .B for loop to iterate over all the elements of an array. .PP An element may be deleted from an array using the .B delete statement. .SS Variable Typing .PP Variables and fields may be (floating point) numbers, or strings, or both. How the value of a variable is interpreted depends upon its context. If used in a numeric expression, it will be treated as a number, if used as a string it will be treated as a string. .PP To force a variable to be treated as a number, add 0 to it; to force it to be treated as a string, concatenate it with the null string. .PP The AWK language defines comparisons as being done numerically if possible, otherwise one or both operands are converted to strings and a string comparison is performed. .PP Uninitialized variables have the numeric value 0 and the string value "" (the null, or empty, string). .SH PATTERNS AND ACTIONS AWK is a line oriented language. The pattern comes first, and then the action. Action statements are enclosed in .B { and .BR } . Either the pattern may be missing, or the action may be missing, but, of course, not both. If the pattern is missing, the action will be executed for every single line of input. A missing action is equivalent to .RS .PP .B "{ print }" .RE .PP which prints the entire line. .PP Comments begin with the ``#'' character, and continue until the end of the line. Blank lines may be used to separate statements. Normally, a statement ends with a newline, however, this is not the case for lines ending in a ``,'', ``{'', ``?'', ``:'', ``&&'', or ``||''. Lines ending in .B do or .B else also have their statements automatically continued on the following line. In other cases, a line can be continued by ending it with a ``\e'', in which case the newline will be ignored. .PP Multiple statements may be put on one line by separating them with a ``;''. This applies to both the statements within the action part of a pattern-action pair (the usual case), and to the pattern-action statements themselves. .SS Patterns AWK patterns may be one of the following: .PP .RS .nf .B BEGIN .B END .BI / "regular expression" / .I "relational expression" .IB pattern " && " pattern .IB pattern " || " pattern .IB pattern " ? " pattern " : " pattern .BI ( pattern ) .BI ! " pattern" .IB pattern1 ", " pattern2" .fi .RE .PP .B BEGIN and .B END are two special kinds of patterns which are not tested against the input. The action parts of all .B BEGIN patterns are merged as if all the statements had been written in a single .B BEGIN block. They are executed before any of the input is read. Similarly, all the .B END blocks are merged, and executed when all the input is exhausted (or when an .B exit statement is executed). .B BEGIN and .B END patterns cannot be combined with other patterns in pattern expressions. .B BEGIN and .B END patterns cannot have missing action parts. .PP For .BI / "regular expression" / patterns, the associated statement is executed for each input line that matches the regular expression. Regular expressions are the same as those in .IR egrep (1), and are summarized below. .PP A .I "relational expression" may use any of the operators defined below in the section on actions. These generally test whether certain fields match certain regular expressions. .PP The .BR && , .BR || , and .B ! operators are logical AND, logical OR, and logical NOT, respectively, as in C. They do short-circuit evaluation, also as in C, and are used for combining more primitive pattern expressions. As in most languages, parentheses may be used to change the order of evaluation. .PP The .B ?\^: operator is like the same operator in C. If the first pattern is true then the pattern used for testing is the second pattern, otherwise it is the third. Only one of the second and third patterns is evaluated. .PP The .IB pattern1 ", " pattern2" form of an expression is called a range pattern. It matches all input lines starting with a line that matches .IR pattern1 , and continuing until a line that matches .IR pattern2 , inclusive. It does not combine with any other sort of pattern expression. .SS Regular Expressions Regular expressions are the extended kind found in .IR egrep . They are composed of characters as follows: .RS .TP \l'[^abc...]' .I c matches the non-metacharacter .IR c . .TP \l'[^abc...]' .I \ec matches the literal character .IR c . .TP \l'[^abc...]' .B . matches any character except newline. .TP \l'[^abc...]' .B ^ matches the beginning of a line or a string. .TP \l'[^abc...]' .B $ matches the end of a line or a string. .TP \l'[^abc...]' .BI [ abc... ] character class, matches any of the characters .IR abc... . .TP \l'[^abc...]' .BI [^ abc... ] negated character class, matches any character except .I abc... and newline. .TP \l'[^abc...]' .IB r1 | r2 alternation: matches either .I r1 or .IR r2 . .TP \l'[^abc...]' .I r1r2 concatenation: matches .IR r1 , and then .IR r2 . .TP \l'[^abc...]' .IB r + matches one or more .IR r 's. .TP \l'[^abc...]' .IB r * matches zero or more .IR r 's. .TP \l'[^abc...]' .IB r ? matches zero or one .IR r 's. .TP \l'[^abc...]' .BI ( r ) grouping: matches .IR r . .RE The escape sequences that are valid in string constants (see below) are also legal in regular expressions. .SS Actions Action statements are enclosed in braces, .B { and .BR } . Action statements consist of the usual assignment, conditional, and looping statements found in most languages. The operators, control statements, and input/output statements available are patterned after those in C. .SS Operators .PP The operators in AWK, in order of increasing precedence, are .PP .RS .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "= += \-= *= /= %= ^=" Assignment. Both absolute assignment .BI ( var " = " value ) and operator-assignment (the other forms) are supported. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B ?: The C conditional expression. This has the form .IB expr1 " ? " expr2 " : " expr3\c \&. If .I expr1 is true, the value of the expression is .IR expr2 , otherwise it is .IR expr3 . Only one of .I expr2 and .I expr3 is evaluated. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B || logical OR. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B && logical AND. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "~ !~" regular expression match, negated match. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "< <= > >= != ==" the regular relational operators. .TP \l'\fB= += \-= *= /= %= ^=\fR' .I blank string concatenation. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "+ \-" addition and subtraction. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "* / %" multiplication, division, and modulus. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "+ \- !" unary plus, unary minus, and logical negation. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B ^ exponentiation (\fB**\fR may also be used, and \fB**=\fR for the assignment operator). .TP \l'\fB= += \-= *= /= %= ^=\fR' .B "++ \-\^\-" increment and decrement, both prefix and postfix. .TP \l'\fB= += \-= *= /= %= ^=\fR' .B $ field reference. .RE .SS Control Statements .PP The control statements are as follows: .PP .RS .nf \fBif (\fIcondition\fB) \fIstatement\fR [ \fBelse\fI statement \fR] \fBwhile (\fIcondition\fB) \fIstatement \fR \fBdo \fIstatement \fBwhile (\fIcondition\fB)\fR \fBfor (\fIexpr1\fB; \fIexpr2\fB; \fIexpr3\fB) \fIstatement\fR \fBfor (\fIvar \fBin\fI array\fB) \fIstatement\fR \fBbreak\fR \fBcontinue\fR \fBdelete \fIarray\^\fB[\^\fIindex\^\fB]\fR \fBexit\fR [ \fIexpression\fR ] \fB{ \fIstatements \fB} .fi .RE .SS "I/O Statements" .PP The input/output statements are as follows: .PP .RS .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI close( filename ) close file (or pipe, see below). .TP \l'\fBprintf \fIfmt, expr-list\fR' .B getline set .B $0 from next input record; set .BR NF , .BR NR , .BR FNR . .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI "getline <" file set .B $0 from next record of .IR file ; set .BR NF . .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI getline " var" set .I var from next input record; set .BR NF , .BR FNR . .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI getline " var" " <" file set .I var from next record of .IR file . .TP \l'\fBprintf \fIfmt, expr-list\fR' .B next Stop processing the current input record. The next input record is read and processing starts over with the first pattern in the AWK program. If the end of the input data is reached, the .B END block(s), if any, are executed. .TP \l'\fBprintf \fIfmt, expr-list\fR' .B print prints the current record. .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI print " expr-list" prints expressions. .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI print " expr-list" " >" file prints expressions on .IR file . .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI printf " fmt, expr-list" format and print. .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI printf " fmt, expr-list" " >" file format and print on .IR file . .TP \l'\fBprintf \fIfmt, expr-list\fR' .BI system( cmd-line ) execute the command .IR cmd-line , and return the exit status. (This may not be available on systems besides \s-1UNIX\s+1 and \s-1GNU\s+1.) .RE .PP Other input/output redirections are also allowed. For .B print and .BR printf , .BI >> file appends output to the .IR file , while .BI | " command" writes on a pipe. In a similar fashion, .IB command " | getline" pipes into .BR getline . .BR Getline will return 0 on end of file, and \-1 on an error. .SS The \fIprintf\fP Statement .PP The AWK versions of the .B printf and .B sprintf (see below) functions accept the following conversion specification formats: .RS .TP .B %c An ASCII character. If the argument used for .B %c is numeric, it is treated as a character and printed. Otherwise, the argument is assumed to be a string, and the only first character of that string is printed. .TP .B %d A decimal number (the integer part). .TP .B %i Just like .BR %d . .TP .B %e A floating point number of the form .BR [\-]d.ddddddE[+\^\-]dd . .TP .B %f A floating point number of the form .BR [\-]ddd.dddddd . .TP .B %g Use .B e or .B f conversion, whichever is shorter, with nonsignificant zeros suppressed. .TP .B %o An unsigned octal number (again, an integer). .TP .B %s A character string. .TP .B %x An unsigned hexadecimal number (an integer). .TP .B %X Like .BR %x , but using .B ABCDEF instead of .BR abcdef . .TP .B %% A single .B % character; no argument is converted. .RE .PP There are optional, additional parameters that may lie between the .B % and the control letter: .RS .TP .B \- The expression should be left-justified within its field. .TP .I width The field should be padded to this width. If the number has a leading zero, then the field will be padded with zeros. Otherwise it is padded with blanks. .TP .BI . prec A number indicating the maximum width of strings or digits to the right of the decimal point. .RE .PP The dynamic .I width and .I prec capabilities of the C library .B printf routines are not supported. However, they may be simulated by using the AWK concatenation operation to build up a format specification dynamically. .SS Special File Names .PP When doing I/O redirection from either .B print or .B printf into a file, or via .B getline from a file, .I gawk recognizes certain special filenames internally. These filenames allow access to open file descriptors inherited from .IR gawk 's parent process (usually the shell). The filenames are: .RS .TP .B /dev/stdin The standard input. .TP .B /dev/stdout The standard output. .TP .B /dev/stderr The standard error output. .TP .BI /dev/fd/\^ n The file denoted by the open file descriptor .IR n . .RE .PP These are particularly useful for error messages. For example: .PP .RS .ft B print "You blew it!" > "/dev/stderr" .ft R .RE .PP whereas you would otherwise have to use .PP .RS .ft B print "You blew it!" | "cat 1>&2" .ft R .RE .PP These file names may also be used on the command line to name data files. .SS Numeric Functions .PP AWK has the following pre-defined arithmetic functions: .PP .RS .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI atan2( y , " x" ) returns the arctangent of .I y/x in radians. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI cos( expr ) returns the cosine in radians. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI exp( expr ) the exponential function. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI int( expr ) truncates to integer. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI log( expr ) the natural logarithm function. .TP \l'\fBsrand(\fIexpr\fB)\fR' .B rand() returns a random number between 0 and 1. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI sin( expr ) returns the sine in radians. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI sqrt( expr ) the square root function. .TP \l'\fBsrand(\fIexpr\fB)\fR' .BI srand( expr ) use .I expr as a new seed for the random number generator. If no .I expr is provided, the time of day will be used. The return value is the previous seed for the random number generator. .RE .SS String Functions .PP AWK has the following pre-defined string functions: .PP .RS .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' \fBgsub(\fIr\fB, \fIs\fB, \fIt\fB)\fR for each substring matching the regular expression .I r in the string .IR t , substitute the string .IR s , and return the number of substitutions. If .I t is not supplied, use .BR $0 . .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' .BI index( s , " t" ) returns the index of the string .I t in the string .IR s , or 0 if .I t is not present. .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' .BI length( s ) returns the length of the string .IR s . .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' .BI match( s , " r" ) returns the position in .I s where the regular expression .I r occurs, or 0 if .I r is not present, and sets the values of .B RSTART and .BR RLENGTH . .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' \fBsplit(\fIs\fB, \fIa\fB, \fIr\fB)\fR splits the string .I s into the array .I a on the regular expression .IR r , and returns the number of fields. If .I r is omitted, .B FS is used instead. .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' .BI sprintf( fmt , " expr-list" ) prints .I expr-list according to .IR fmt , and returns the resulting string. .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' \fBsub(\fIr\fB, \fIs\fB, \fIt\fB)\fR this is just like .BR gsub , but only the first matching substring is replaced. .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' \fBsubstr(\fIs\fB, \fIi\fB, \fIn\fB)\fR returns the .IR n -character substring of .I s starting at .IR i . If .I n is omitted, the rest of .I s is used. .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' .BI tolower( str ) returns a copy of the string .IR str , with all the upper-case characters in .I str translated to their corresponding lower-case counterparts. Non-alphabetic characters are left unchanged. .TP \l'\fBsprintf(\fIfmt\fB, \fIexpr-list\fB)\fR' .BI toupper( str ) returns a copy of the string .IR str , with all the lower-case characters in .I str translated to their corresponding upper-case counterparts. Non-alphabetic characters are left unchanged. .RE .SS String Constants .PP String constants in AWK are sequences of characters enclosed between double quotes (\fB"\fR). Within strings, certain .I "escape sequences" are recognized, as in C. These are: .PP .RS .TP \l'\fB\e\fIddd\fR' .B \e\e A literal backslash. .TP \l'\fB\e\fIddd\fR' .B \ea The ``alert'' character; usually the ASCII BEL character. .TP \l'\fB\e\fIddd\fR' .B \eb backspace. .TP \l'\fB\e\fIddd\fR' .B \ef form-feed. .TP \l'\fB\e\fIddd\fR' .B \en new line. .TP \l'\fB\e\fIddd\fR' .B \er carriage return. .TP \l'\fB\e\fIddd\fR' .B \et horizontal tab. .TP \l'\fB\e\fIddd\fR' .B \ev vertical tab. .TP \l'\fB\e\fIddd\fR' .BI \ex "\^hex digits" The character represented by the string of hexadecimal digits following the .BR \ex . As in ANSI C, all following hexadecimal digits are considered part of the escape sequence. (This feature should tell us something about language design by committee.) E.g., "\ex1B" is the ASCII ESC (escape) character. .TP \l'\fB\e\fIddd\fR' .BI \e ddd The character represented by the 1-, 2-, or 3-digit sequence of octal digits. E.g. "\e033" is the ASCII ESC (escape) character. .TP \l'\fB\e\fIddd\fR' .BI \e c The literal character .IR c\^ . .RE .PP The escape sequences may also be used inside constant regular expressions (e.g., .B "/[\ \et\ef\en\er\ev]/" matches whitespace characters). .SH FUNCTIONS Functions in AWK are defined as follows: .PP .RS \fBfunction \fIname\fB(\fIparameter list\fB) { \fIstatements \fB}\fR .RE .PP Functions are executed when called from within the action parts of regular pattern-action statements. Actual parameters supplied in the function call are used to instantiate the formal parameters declared in the function. Arrays are passed by reference, other variables are passed by value. .PP Since functions were not originally part of the AWK language, the provision for local variables is rather clumsy: they are declared as extra parameters in the parameter list. The convention is to separate local variables from real parameters by extra spaces in the parameter list. For example: .PP .RS .ft B .nf function f(p, q, a, b) { # a & b are local ..... } /abc/ { ... ; f(1, 2) ; ... } .fi .ft R .RE .PP The left parenthesis in a function call is required to immediately follow the function name, without any intervening white space. This is to avoid a syntactic ambiguity with the concatenation operator. This restriction does not apply to the built-in functions listed above. .PP Functions may call each other and may be recursive. Function parameters used as local variables are initialized to the null string and the number zero upon function invocation. .PP The word .B func may be used in place of .BR function . .SH EXAMPLES .nf Print and sort the login names of all users: .ft B BEGIN { FS = ":" } { print $1 | "sort" } .ft R Count lines in a file: .ft B { nlines++ } END { print nlines } .ft R Precede each line by its number in the file: .ft B { print FNR, $0 } .ft R Concatenate and line number (a variation on a theme): .ft B { print NR, $0 } .ft R .fi .SH SEE ALSO .IR egrep (1) .PP .IR "The AWK Programming Language" , Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger, Addison-Wesley, 1988. ISBN 0-201-07981-X. .PP .IR "The GAWK Manual" , published by the Free Software Foundation, 1989. .SH SYSTEM V RELEASE 4 COMPATIBILITY A primary goal for .I gawk is compatibility with the latest version of \s-1UNIX\s+1 .IR awk . To this end, .I gawk incorporates the following user visible features which are not described in the AWK book, but are part of .I awk in System V Release 4. .PP The .B \-v option for assigning variables before program execution starts is new. The book indicates that command line variable assignment happens when .I awk would otherwise open the argument as a file, which is after the .B BEGIN block is executed. However, in earlier implementations, when such an assignment appeared before any file names, the assignment would happen .I before the .B BEGIN block was run. Applications came to depend on this ``feature.'' When .I awk was changed to match its documentation, this option was added to accomodate applications that depended upon the old behaviour. .PP When processing arguments, .I gawk uses the special option ``\fB\-\^\-\fP'' to signal the end of arguments, and warns about, but otherwise ignores, undefined options. .PP The AWK book does not define the return value of .BR srand() . The System V Release 4 version of \s-1UNIX\s+1 .I awk has it return the seed it was using, to allow keeping track of random number sequences. Therefore .B srand() in .I gawk also returns its current seed. .PP Other new features are: The use of multiple .B \-f options; the .B ENVIRON array; the .BR \ea , and .BR \ev , .B \ex escape sequences; the .B tolower and .B toupper built-in functions; and the ANSI C conversion specifications in .BR printf . .SH GNU EXTENSIONS .I Gawk has some extensions to System V .IR awk . They are described in this section. All the extensions described here can be disabled by compiling .I gawk with .BR \-DSTRICT , or by invoking .I gawk with the .B \-c option. If the underlying operating system supports the .B /dev/fd directory and corresponding files, then .I gawk can be compiled with .B \-DNO_DEV_FD to disable the special filename processing. .PP The following features of .I gawk are not available in System V .IR awk . .RS .TP \l'\(bu' \(bu The special file names available for I/O redirection are not recognized. .TP \l'\(bu' \(bu The .B IGNORECASE variable and its side-effects are not available. .TP \l'\(bu' \(bu No path search is performed for files named via the .B \-f option. Therefore the .B AWKPATH environment variable is not special. .TP \l'\(bu' \(bu The .BR \-a , .BR \-e , .BR \-c , .BR \-C , and .B \-V command line options. .RE .PP The AWK book does not define the return value of the .B close function. .IR Gawk\^ 's .B close returns the value from .IR fclose (3), or .IR pclose (3), when closing a file or pipe, respectively. .PP When .I gawk is invoked with the .B \-c option, if the .I fs argument to the .B \-F option is ``t'', then .B FS will be set to the tab character. Since this is a rather ugly special case, it is not the default behavior. .ig .PP The rest of the features described in this section may change at some time in the future, or may go away entirely. You should not write programs that depend upon them. .PP .I Gawk accepts the following additional options: .TP .B \-D Turn on general debugging and turn on .IR yacc (1) or .IR bison (1) debugging output during program parsing. This option should only be of interest to the .I gawk maintainers, and may not even be compiled into .IR gawk . .TP .B \-d Turn on general debugging and print the .I gawk internal tree as the program is executed. This option should only be of interest to the .I gawk maintainers, and may not even be compiled into .IR gawk . .. .SH BUGS The .B \-F option is not necessary given the command line variable assignment feature; it remains only for backwards compatibility. .PP There are now too many options. Fortunately, most of them are rarely needed. .SH AUTHORS The original version of \s-1UNIX\s+1 .I awk was designed and implemented by Alfred Aho, Peter Weinberger, and Brian Kernighan of AT&T Bell Labs. Brian Kernighan continues to maintain and enhance it. .PP Paul Rubin and Jay Fenlason, of the Free Software Foundation, wrote .IR gawk , to be compatible with the original version of .I awk distributed in Seventh Edition \s-1UNIX\s+1. John Woods contributed a number of bug fixes. David Trueman of Dalhousie University, with contributions from Arnold Robbins at Emory University, made .I gawk compatible with the new version of \s-1UNIX\s+1 .IR awk . .SH ACKNOWLEDGEMENTS Brian Kernighan of Bell Labs provided valuable assistance during testing and debugging. We thank him. gawk-2.11/gawk.texinfo 644 11660 0 1123174 4527633604 13177 0ustar hackwheel\input texinfo @c -*-texinfo-*- @c %**start of header (This is for running Texinfo on a region.) @setfilename gawk-info @settitle The GAWK Manual @c %**end of header (This is for running Texinfo on a region.) @syncodeindex fn cp @syncodeindex vr cp @iftex @finalout @end iftex @ifinfo This file documents @code{awk}, a program that you can use to select particular records in a file and perform operations upon them. Copyright (C) 1989 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). @end ignore Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. @end ifinfo @c @smallbook @c For printing as a small manual, uncomment the above line. Then change @c every `@example' to `@smallexample' and every `@end example' to @c `@end smallexample'. That's all. @setchapternewpage odd @titlepage @sp 11 @center @titlefont{The GAWK Manual} @sp 4 @center by @center Diane Barlow Close @center Arnold D. Robbins @center Paul H. Rubin @center Richard Stallman @sp 2 @center Edition 0.11 Beta @sp 2 @center October 1989 @c Include the Distribution inside the titlepage environment so @c that headings are turned off. Headings on and off do not work. @page @vskip 0pt plus 1filll Copyright @copyright{} 1989 Free Software Foundation, Inc. @sp 2 This is Edition 0.11 Beta of @cite{The GAWK Manual}, @* for the 2.11.1 version of the GNU implementation @* of AWK. @sp 2 Published by the Free Software Foundation @* 675 Massachusetts Avenue, @* Cambridge, MA 02139 USA @* Printed copies are available for $10 each. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. @end titlepage @node Top, Preface, (dir), (dir) @comment node-name, next, previous, up @c Preface or Licensing nodes should come right after the Top @c node, in `unnumbered' sections, then the chapter, `What is gawk'. @ifinfo This file documents @code{awk}, a program that you can use to select particular records in a file and perform operations upon them; it contains the following chapters: @end ifinfo @menu * Preface:: What you can do with @code{awk}; brief history and acknowledgements. * Copying:: Your right to copy and distribute @code{gawk}. * This Manual:: Using this manual. Includes sample input files that you can use. * Getting Started:: A basic introduction to using @code{awk}. How to run an @code{awk} program. Command line syntax. * Reading Files:: How to read files and manipulate fields. * Printing:: How to print using @code{awk}. Describes the @code{print} and @code{printf} statements. Also describes redirection of output. * One-liners:: Short, sample @code{awk} programs. * Patterns:: The various types of patterns explained in detail. * Actions:: The various types of actions are introduced here. Describes expressions and the various operators in detail. Also describes comparison expressions. * Expressions:: Expressions are the basic building blocks of statements. * Statements:: The various control statements are described in detail. * Arrays:: The description and use of arrays. Also includes array-oriented control statements. * Built-in:: The built-in functions are summarized here. * User-defined:: User-defined functions are described in detail. * Var: Built-in Variables. The built-in variables are summarized here. * Command Line:: How to run @code{gawk}. * Language History:: The evolution of the @code{awk} language. * Gawk Summary:: @code{gawk} Options and Language Summary. * Sample Program:: A sample @code{awk} program with a complete explanation. * Notes:: Something about the implementation of @code{gawk}. * Glossary:: An explanation of some unfamiliar terms. * Index:: @end menu @node Preface, Copying, Top , Top @comment node-name, next, previous, up @unnumbered Preface @c @cindex what is @code{awk} If you are like many computer users, you frequently would like to make changes in various text files wherever certain patterns appear, or extract data from parts of certain lines while discarding the rest. To write a program to do this in a language such as C or Pascal is a time-consuming inconvenience that may take many lines of code. The job may be easier with @code{awk}. The @code{awk} utility interprets a special-purpose programming language that makes it possible to handle simple data-reformatting jobs easily with just a few lines of code. The GNU implementation of @code{awk} is called @code{gawk}; it is fully upward compatible with the System V Release 3.1 and later version of @code{awk}. All properly written @code{awk} programs should work with @code{gawk}. So we usually don't distinguish between @code{gawk} and other @code{awk} implementations in this manual.@refill @cindex uses of @code{awk} This manual teaches you what @code{awk} does and how you can use @code{awk} effectively. You should already be familiar with basic system commands such as @code{ls}. Using @code{awk} you can: @refill @itemize @bullet @item manage small, personal databases, @item generate reports, @item validate data, @item produce indexes, and perform other document preparation tasks, @item even experiment with algorithms that can be adapted later to other computer languages! @end itemize @menu * History:: The history of @code{gawk} and @code{awk}. Acknowledgements. @end menu @node History, , Preface, Preface @comment node-name, next, previous, up @unnumberedsec History of @code{awk} and @code{gawk} @cindex acronym @cindex history of @code{awk} The name @code{awk} comes from the initials of its designers: Alfred V. Aho, Peter J. Weinberger, and Brian W. Kernighan. The original version of @code{awk} was written in 1977. In 1985 a new version made the programming language more powerful, introducing user-defined functions, multiple input streams, and computed regular expressions. This new version became generally available with System V Release 3.1. The version in System V Release 4 added some new features and also cleaned up the behaviour in some of the ``dark corners'' of the language.@refill @comment We don't refer people to non-free information @comment In 1988, the original authors @comment published @cite{The AWK Programming Language} (Addison-Wesley, ISBN @comment 0-201-07981-X), as a definitive description of the @code{awk} language. The GNU implementation, @code{gawk}, was written in 1986 by Paul Rubin and Jay Fenlason, with advice from Richard Stallman. John Woods contributed parts of the code as well. In 1988 and 1989, David Trueman, with help from Arnold Robbins, thoroughly reworked @code{gawk} for compatibility with the newer @code{awk}. Many people need to be thanked for their assistance in producing this manual. Jay Fenlason contributed many ideas and sample programs. Richard Mlynarik and Robert Chassell gave helpful comments on drafts of this manual. The paper @cite{A Supplemental Document for @code{awk}} by John W. Pierce of the Chemistry Department at UC San Diego, pinpointed several issues relevant both to @code{awk} implementation and to this manual, that would otherwise have escaped us. Finally, we would like to thank Brian Kernighan of Bell Labs for invaluable assistance during the testing and debugging of @code{gawk}, and for help in clarifying several points about the language.@refill @node Copying, This Manual, Preface, Top @unnumbered GNU General Public License @center Version 1, February 1989 @display Copyright @copyright{} 1989 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @end display @c fakenode - this is for prepinfo. @unnumberedsec Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software---to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. @iftex @c fakenode -- this is for prepinfo. @unnumberedsec TERMS AND CONDITIONS @end iftex @ifinfo @center TERMS AND CONDITIONS @end ifinfo @enumerate @item This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as ``you''. @item You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. @item You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: @itemize @bullet @item cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and @item cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). @item If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. @item You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. @end itemize Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. @item You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: @itemize @bullet @item accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, @item accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, @item accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) @end itemize Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. @item You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. @item By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. @item Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. @item The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. @item If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. @iftex @c fakenode -- this is for prepinfo. @heading NO WARRANTY @end iftex @ifinfo @center NO WARRANTY @end ifinfo @item BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. @item IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. @end enumerate @iftex @c fakenode -- this is for prepinfo. @heading END OF TERMS AND CONDITIONS @end iftex @ifinfo @center END OF TERMS AND CONDITIONS @end ifinfo @page @c fakenode -- this is for prepinfo. @unnumberedsec Appendix: Using These Terms in New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found. @smallexample @var{one line to give the program's name and a brief idea of what it does.} Copyright (C) 19@var{yy} @var{name of author} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @end smallexample Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: @smallexample Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author} Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. @end smallexample The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items---whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the program, if necessary. Here a sample; alter the names: @example Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. @var{signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice @end example That's all there is to it! @node This Manual, Getting Started, Copying, Top @chapter Using This Manual @cindex manual, using this @cindex using this manual @cindex language, @code{awk} @cindex program, @code{awk} @cindex @code{awk} language @cindex @code{awk} program The term @code{gawk} refers to a particular program (a version of @code{awk}, developed as part the GNU project), and to the language you use to tell this program what to do. When we need to be careful, we call the program ``the @code{awk} utility'' and the language ``the @code{awk} language''. The purpose of this manual is to explain the @code{awk} language and how to run the @code{awk} utility. The term @dfn{@code{awk} program} refers to a program written by you in the @code{awk} programming language.@refill @xref{Getting Started}, for the bare essentials you need to know to start using @code{awk}. Some useful ``one-liners'' are included to give you a feel for the @code{awk} language (@pxref{One-liners}). @ignore @strong{I deleted four paragraphs here because they would confuse the beginner more than help him. They mention terms such as ``field'', ``pattern'', ``action'', ``built-in function'' which the beginner doesn't know.} @strong{If you can find a way to introduce several of these concepts here, enough to give the reader a map of what is to follow, that might be useful. I'm not sure that can be done without taking up more space than ought to be used here. There may be no way to win.} @strong{ADR: I'd like to tackle this in phase 2 of my editing.} @end ignore A sizable sample @code{awk} program has been provided for you (@pxref{Sample Program}).@refill If you find terms that you aren't familiar with, try looking them up in the glossary (@pxref{Glossary}).@refill Most of the time complete @code{awk} programs are used as examples, but in some of the more advanced sections, only the part of the @code{awk} program that illustrates the concept being described is shown.@refill @menu This chapter contains the following sections: * Sample Data Files:: Sample data files for use in the @code{awk} programs illustrated in this manual. @end menu @node Sample Data Files, , This Manual, This Manual @section Data Files for the Examples @cindex input file, sample @cindex sample input file @cindex @file{BBS-list} file Many of the examples in this manual take their input from two sample data files. The first, called @file{BBS-list}, represents a list of computer bulletin board systems and information about those systems. The second data file, called @file{inventory-shipped}, contains information about shipments on a monthly basis. Each line of these files is one @dfn{record}. In the file @file{BBS-list}, each record contains the name of a computer bulletin board, its phone number, the board's baud rate, and a code for the number of hours it is operational. An @samp{A} in the last column means the board operates 24 hours all week. A @samp{B} in the last column means the board operates evening and weekend hours, only. A @samp{C} means the board operates only on weekends. @group @example aardvark 555-5553 1200/300 B alpo-net 555-3412 2400/1200/300 A barfly 555-7685 1200/300 A bites 555-1675 2400/1200/300 A camelot 555-0542 300 C core 555-2912 1200/300 C fooey 555-1234 2400/1200/300 B foot 555-6699 1200/300 B macfoo 555-6480 1200/300 A sdace 555-3430 2400/1200/300 A sabafoo 555-2127 1200/300 C @end example @end group @cindex @file{inventory-shipped} file The second data file, called @file{inventory-shipped}, represents information about shipments during the year. Each line of this file is also one record. Each record contains the month of the year, the number of green crates shipped, the number of red boxes shipped, the number of orange bags shipped, and the number of blue packages shipped, respectively. There are 16 entries, covering the 12 months of one year and 4 months of the next year. @group @example Jan 13 25 15 115 Feb 15 32 24 226 Mar 15 24 34 228 Apr 31 52 63 420 May 16 34 29 208 Jun 31 42 75 492 Jul 24 34 67 436 Aug 15 34 47 316 Sep 13 55 37 277 Oct 29 54 68 525 Nov 20 87 82 577 Dec 17 35 61 401 Jan 21 36 64 620 Feb 26 58 80 652 Mar 24 75 70 495 Apr 21 70 74 514 @end example @end group @ifinfo If you are reading this in GNU Emacs using Info, you can copy the regions of text showing these sample files into your own test files. This way you can try out the examples shown in the remainder of this document. You do this by using the command @kbd{M-x write-region} to copy text from the Info file into a file for use with @code{awk} (see your @cite{GNU Emacs Manual} for more information). Using this information, create your own @file{BBS-list} and @file{inventory-shipped} files, and practice what you learn in this manual. @end ifinfo @node Getting Started, Reading Files, This Manual, Top @chapter Getting Started With @code{awk} @cindex script, definition of @cindex rule, definition of @cindex program, definition of @cindex basic function of @code{gawk} The basic function of @code{awk} is to search files for lines (or other units of text) that contain certain patterns. When a line matches one of the patterns, @code{awk} performs specified actions on that line. @code{awk} keeps processing input lines in this way until the end of the input file is reached.@refill When you run @code{awk}, you specify an @code{awk} @dfn{program} which tells @code{awk} what to do. The program consists of a series of @dfn{rules}. (It may also contain @dfn{function definitions}, but that is an advanced feature, so let's ignore it for now. @xref{User-defined}.) Each rule specifies one pattern to search for, and one action to perform when that pattern is found. Syntactically, a rule consists of a pattern followed by an action. The action is enclosed in curly braces to separate it from the pattern. Rules are usually separated by newlines. Therefore, an @code{awk} program looks like this: @example @var{pattern} @{ @var{action} @} @var{pattern} @{ @var{action} @} @dots{} @end example @menu * Very Simple:: A very simple example. * Two Rules:: A less simple one-line example with two rules. * More Complex:: A more complex example. * Running gawk:: How to run @code{gawk} programs; includes command line syntax. * Comments:: Adding documentation to @code{gawk} programs. * Statements/Lines:: Subdividing or combining statements into lines. * When:: When to use @code{gawk} and when to use other things. @end menu @node Very Simple, Two Rules, Getting Started, Getting Started @section A Very Simple Example @cindex @samp{print $0} The following command runs a simple @code{awk} program that searches the input file @file{BBS-list} for the string of characters: @samp{foo}. (A string of characters is usually called, quite simply, a @dfn{string}. The term @dfn{string} is perhaps based on similar usage in English, such as ``a string of pearls,'' or, ``a string of cars in a train.'') @example awk '/foo/ @{ print $0 @}' BBS-list @end example @noindent When lines containing @samp{foo} are found, they are printed, because @w{@samp{print $0}} means print the current line. (Just @samp{print} by itself also means the same thing, so we could have written that instead.) You will notice that slashes, @samp{/}, surround the string @samp{foo} in the actual @code{awk} program. The slashes indicate that @samp{foo} is a pattern to search for. This type of pattern is called a @dfn{regular expression}, and is covered in more detail later (@pxref{Regexp}). There are single-quotes around the @code{awk} program so that the shell won't interpret any of it as special shell characters.@refill Here is what this program prints: @example fooey 555-1234 2400/1200/300 B foot 555-6699 1200/300 B macfoo 555-6480 1200/300 A sabafoo 555-2127 1200/300 C @end example @cindex action, default @cindex pattern, default @cindex default action @cindex default pattern In an @code{awk} rule, either the pattern or the action can be omitted, but not both. If the pattern is omitted, then the action is performed for @emph{every} input line. If the action is omitted, the default action is to print all lines that match the pattern. Thus, we could leave out the action (the @code{print} statement and the curly braces) in the above example, and the result would be the same: all lines matching the pattern @samp{foo} would be printed. By comparison, omitting the @code{print} statement but retaining the curly braces makes an empty action that does nothing; then no lines would be printed. @node Two Rules, More Complex, Very Simple, Getting Started @section An Example with Two Rules @cindex how @code{awk} works The @code{awk} utility reads the input files one line at a time. For each line, @code{awk} tries the patterns of all the rules. If several patterns match then several actions are run, in the order in which they appear in the @code{awk} program. If no patterns match, then no actions are run. After processing all the rules (perhaps none) that match the line, @code{awk} reads the next line (however, @pxref{Next Statement}). This continues until the end of the file is reached.@refill For example, the @code{awk} program: @example /12/ @{ print $0 @} /21/ @{ print $0 @} @end example @noindent contains two rules. The first rule has the string @samp{12} as the pattern and @samp{print $0} as the action. The second rule has the string @samp{21} as the pattern and also has @samp{print $0} as the action. Each rule's action is enclosed in its own pair of braces. This @code{awk} program prints every line that contains the string @samp{12} @emph{or} the string @samp{21}. If a line contains both strings, it is printed twice, once by each rule. If we run this program on our two sample data files, @file{BBS-list} and @file{inventory-shipped}, as shown here: @example awk '/12/ @{ print $0 @} /21/ @{ print $0 @}' BBS-list inventory-shipped @end example @noindent we get the following output: @example aardvark 555-5553 1200/300 B alpo-net 555-3412 2400/1200/300 A barfly 555-7685 1200/300 A bites 555-1675 2400/1200/300 A core 555-2912 1200/300 C fooey 555-1234 2400/1200/300 B foot 555-6699 1200/300 B macfoo 555-6480 1200/300 A sdace 555-3430 2400/1200/300 A sabafoo 555-2127 1200/300 C sabafoo 555-2127 1200/300 C Jan 21 36 64 620 Apr 21 70 74 514 @end example @noindent Note how the line in @file{BBS-list} beginning with @samp{sabafoo} was printed twice, once for each rule. @node More Complex, Running gawk, Two Rules, Getting Started @comment node-name, next, previous, up @section A More Complex Example Here is an example to give you an idea of what typical @code{awk} programs do. This example shows how @code{awk} can be used to summarize, select, and rearrange the output of another utility. It uses features that haven't been covered yet, so don't worry if you don't understand all the details. @example ls -l | awk '$5 == "Nov" @{ sum += $4 @} END @{ print sum @}' @end example This command prints the total number of bytes in all the files in the current directory that were last modified in November (of any year). (In the C shell you would need to type a semicolon and then a backslash at the end of the first line; in the Bourne shell or the Bourne-Again shell, you can type the example as shown.) The @w{@samp{ls -l}} part of this example is a command that gives you a full listing of all the files in a directory, including file size and date. Its output looks like this: @example -rw-r--r-- 1 close 1933 Nov 7 13:05 Makefile -rw-r--r-- 1 close 10809 Nov 7 13:03 gawk.h -rw-r--r-- 1 close 983 Apr 13 12:14 gawk.tab.h -rw-r--r-- 1 close 31869 Jun 15 12:20 gawk.y -rw-r--r-- 1 close 22414 Nov 7 13:03 gawk1.c -rw-r--r-- 1 close 37455 Nov 7 13:03 gawk2.c -rw-r--r-- 1 close 27511 Dec 9 13:07 gawk3.c -rw-r--r-- 1 close 7989 Nov 7 13:03 gawk4.c @end example @noindent The first field contains read-write permissions, the second field contains the number of links to the file, and the third field identifies the owner of the file. The fourth field contains the size of the file in bytes. The fifth, sixth, and seventh fields contain the month, day, and time, respectively, that the file was last modified. Finally, the eighth field contains the name of the file. The @code{$5 == "Nov"} in our @code{awk} program is an expression that tests whether the fifth field of the output from @w{@samp{ls -l}} matches the string @samp{Nov}. Each time a line has the string @samp{Nov} in its fifth field, the action @samp{@{ sum += $4 @}} is performed. This adds the fourth field (the file size) to the variable @code{sum}. As a result, when @code{awk} has finished reading all the input lines, @code{sum} is the sum of the sizes of files whose lines matched the pattern.@refill After the last line of output from @code{ls} has been processed, the @code{END} rule is executed, and the value of @code{sum} is printed. In this example, the value of @code{sum} would be 80600.@refill These more advanced @code{awk} techniques are covered in later sections (@pxref{Actions}). Before you can move on to more advanced @code{awk} programming, you have to know how @code{awk} interprets your input and displays your output. By manipulating fields and using @code{print} statements, you can produce some very useful and spectacular looking reports.@refill @node Running gawk, Comments, More Complex, Getting Started @section How to Run @code{awk} Programs @cindex command line formats @cindex running @code{awk} programs There are several ways to run an @code{awk} program. If the program is short, it is easiest to include it in the command that runs @code{awk}, like this: @example awk '@var{program}' @var{input-file1} @var{input-file2} @dots{} @end example @noindent where @var{program} consists of a series of patterns and actions, as described earlier. When the program is long, you would probably prefer to put it in a file and run it with a command like this: @example awk -f @var{program-file} @var{input-file1} @var{input-file2} @dots{} @end example @menu * One-shot:: Running a short throw-away @code{awk} program. * Read Terminal:: Using no input files (input from terminal instead). * Long:: Putting permanent @code{awk} programs in files. * Executable Scripts:: Making self-contained @code{awk} programs. @end menu @node One-shot, Read Terminal, Running gawk, Running gawk @subsection One-shot Throw-away @code{awk} Programs Once you are familiar with @code{awk}, you will often type simple programs at the moment you want to use them. Then you can write the program as the first argument of the @code{awk} command, like this: @example awk '@var{program}' @var{input-file1} @var{input-file2} @dots{} @end example @noindent where @var{program} consists of a series of @var{patterns} and @var{actions}, as described earlier. @cindex single quotes, why needed This command format tells the shell to start @code{awk} and use the @var{program} to process records in the input file(s). There are single quotes around the @var{program} so that the shell doesn't interpret any @code{awk} characters as special shell characters. They cause the shell to treat all of @var{program} as a single argument for @code{awk}. They also allow @var{program} to be more than one line long.@refill This format is also useful for running short or medium-sized @code{awk} programs from shell scripts, because it avoids the need for a separate file for the @code{awk} program. A self-contained shell script is more reliable since there are no other files to misplace. @node Read Terminal, Long, One-shot, Running gawk @subsection Running @code{awk} without Input Files @cindex standard input @cindex input, standard You can also use @code{awk} without any input files. If you type the command line:@refill @example awk '@var{program}' @end example @noindent then @code{awk} applies the @var{program} to the @dfn{standard input}, which usually means whatever you type on the terminal. This continues until you indicate end-of-file by typing @kbd{Control-d}. For example, if you execute this command: @example awk '/th/' @end example @noindent whatever you type next is taken as data for that @code{awk} program. If you go on to type the following data: @example Kathy Ben Tom Beth Seth Karen Thomas @kbd{Control-d} @end example @noindent then @code{awk} prints this output: @example Kathy Beth Seth @end example @noindent @cindex case sensitivity @cindex pattern, case sensitive as matching the pattern @samp{th}. Notice that it did not recognize @samp{Thomas} as matching the pattern. The @code{awk} language is @dfn{case sensitive}, and matches patterns exactly. (However, you can override this with the variable @code{IGNORECASE}. @xref{Case-sensitivity}.) @node Long, Executable Scripts, Read Terminal, Running gawk @subsection Running Long Programs @cindex running long programs @cindex @samp{-f} option @cindex program file @cindex file, @code{awk} program Sometimes your @code{awk} programs can be very long. In this case it is more convenient to put the program into a separate file. To tell @code{awk} to use that file for its program, you type:@refill @example awk -f @var{source-file} @var{input-file1} @var{input-file2} @dots{} @end example The @samp{-f} tells the @code{awk} utility to get the @code{awk} program from the file @var{source-file}. Any file name can be used for @var{source-file}. For example, you could put the program:@refill @example /th/ @end example @noindent into the file @file{th-prog}. Then this command: @example awk -f th-prog @end example @noindent does the same thing as this one: @example awk '/th/' @end example @noindent which was explained earlier (@pxref{Read Terminal}). Note that you don't usually need single quotes around the file name that you specify with @samp{-f}, because most file names don't contain any of the shell's special characters. If you want to identify your @code{awk} program files clearly as such, you can add the extension @file{.awk} to the file name. This doesn't affect the execution of the @code{awk} program, but it does make ``housekeeping'' easier. @node Executable Scripts, , Long, Running gawk @c node-name, next, previous, up @subsection Executable @code{awk} Programs @cindex executable scripts @cindex scripts, executable @cindex self contained programs @cindex program, self contained @cindex @samp{#!} Once you have learned @code{awk}, you may want to write self-contained @code{awk} scripts, using the @samp{#!} script mechanism. You can do this on BSD Unix systems and (someday) on GNU. For example, you could create a text file named @file{hello}, containing the following (where @samp{BEGIN} is a feature we have not yet discussed): @example #! /bin/awk -f # a sample awk program BEGIN @{ print "hello, world" @} @end example @noindent After making this file executable (with the @code{chmod} command), you can simply type: @example hello @end example @noindent at the shell, and the system will arrange to run @code{awk} as if you had typed: @example awk -f hello @end example @noindent Self-contained @code{awk} scripts are useful when you want to write a program which users can invoke without knowing that the program is written in @code{awk}. @cindex shell scripts @cindex scripts, shell If your system does not support the @samp{#!} mechanism, you can get a similar effect using a regular shell script. It would look something like this: @example : The colon makes sure this script is executed by the Bourne shell. awk '@var{program}' "$@@" @end example Using this technique, it is @emph{vital} to enclose the @var{program} in single quotes to protect it from interpretation by the shell. If you omit the quotes, only a shell wizard can predict the result. The @samp{"$@@"} causes the shell to forward all the command line arguments to the @code{awk} program, without interpretation. The first line, which starts with a colon, is used so that this shell script will work even if invoked by a user who uses the C shell. @c Someday: (See @cite{The Bourne Again Shell}, by ??.) @c We don't refer to hoarded information. @c (See @c @cite{The UNIX Programming Environment} by Brian Kernighan and Rob Pike, @c Prentice-Hall, 1984, for more information on writing shell programs that @c use the Unix utilities. The most powerful version of the shell is the @c Korn shell. A detailed description of the Korn shell can be found in @c @cite{The KornShell Command and Programming Language} by Morris Bolsky @c and David Korn, Prentice-Hall, 1989.) @node Comments, Statements/Lines, Running gawk, Getting Started @section Comments in @code{awk} Programs @cindex comments @cindex use of comments @cindex documenting @code{awk} programs @cindex programs, documenting A @dfn{comment} is some text that is included in a program for the sake of human readers, and that is not really part of the program. Comments can explain what the program does, and how it works. Nearly all programming languages have provisions for comments, because programs are hard to understand without their extra help. In the @code{awk} language, a comment starts with the sharp sign character, @samp{#}, and continues to the end of the line. The @code{awk} language ignores the rest of a line following a sharp sign. For example, we could have put the following into @file{th-prog}:@refill @example # This program finds records containing the pattern @samp{th}. This is how # you continue comments on additional lines. /th/ @end example You can put comment lines into keyboard-composed throw-away @code{awk} programs also, but this usually isn't very useful; the purpose of a comment is to help you or another person understand the program at another time. @node Statements/Lines, When, Comments, Getting Started @section @code{awk} Statements versus Lines Most often, each line in an @code{awk} program is a separate statement or separate rule, like this: @example awk '/12/ @{ print $0 @} /21/ @{ print $0 @}' BBS-list inventory-shipped @end example But sometimes statements can be more than one line, and lines can contain several statements. You can split a statement into multiple lines by inserting a newline after any of the following: @example , @{ ? : || && do else @end example @noindent A newline at any other point is considered the end of the statement. @cindex backslash continuation @cindex continuation of lines If you would like to split a single statement into two lines at a point where a newline would terminate it, you can @dfn{continue} it by ending the first line with a backslash character, @samp{\}. This is allowed absolutely anywhere in the statement, even in the middle of a string or regular expression. For example: @example awk '/This program is too long, so continue it\ on the next line/ @{ print $1 @}' @end example @noindent We have generally not used backslash continuation in the sample programs in this manual. Since there is no limit on the length of a line, it is never strictly necessary; it just makes programs prettier. We have preferred to make them even more pretty by keeping the statements short. Backslash continuation is most useful when your @code{awk} program is in a separate source file, instead of typed in on the command line. @strong{Warning: backslash continuation does not work as described above with the C shell.} Continuation with backslash works for @code{awk} programs in files, and also for one-shot programs @emph{provided} you are using the Bourne shell or the Bourne-again shell. But the C shell used on Berkeley Unix behaves differently! There, you must use two backslashes in a row, followed by a newline.@refill @cindex multiple statements on one line When @code{awk} statements within one rule are short, you might want to put more than one of them on a line. You do this by separating the statements with semicolons, @samp{;}. This also applies to the rules themselves. Thus, the above example program could have been written:@refill @example /12/ @{ print $0 @} ; /21/ @{ print $0 @} @end example @noindent @strong{Note:} the requirement that rules on the same line must be separated with a semicolon is a recent change in the @code{awk} language; it was done for consistency with the treatment of statements within an action. @node When, , Statements/Lines, Getting Started @section When to Use @code{awk} @cindex when to use @code{awk} @cindex applications of @code{awk} What use is all of this to me, you might ask? Using additional utility programs, more advanced patterns, field separators, arithmetic statements, and other selection criteria, you can produce much more complex output. The @code{awk} language is very useful for producing reports from large amounts of raw data, such as summarizing information from the output of other utility programs such as @code{ls}. (@xref{More Complex, , A More Complex Example}.) Programs written with @code{awk} are usually much smaller than they would be in other languages. This makes @code{awk} programs easy to compose and use. Often @code{awk} programs can be quickly composed at your terminal, used once, and thrown away. Since @code{awk} programs are interpreted, you can avoid the usually lengthy edit-compile-test-debug cycle of software development. Complex programs have been written in @code{awk}, including a complete retargetable assembler for 8-bit microprocessors (@pxref{Glossary}, for more information) and a microcode assembler for a special purpose Prolog computer. However, @code{awk}'s capabilities are strained by tasks of such complexity. If you find yourself writing @code{awk} scripts of more than, say, a few hundred lines, you might consider using a different programming language. Emacs Lisp is a good choice if you need sophisticated string or pattern matching capabilities. The shell is also good at string and pattern matching; in addition, it allows powerful use of the system utilities. More conventional languages, such as C, C++, and Lisp, offer better facilities for system programming and for managing the complexity of large programs. Programs in these languages may require more lines of source code than the equivalent @code{awk} programs, but they are easier to maintain and usually run more efficiently.@refill @node Reading Files, Printing, Getting Started, Top @chapter Reading Input Files @cindex reading files @cindex input @cindex standard input @vindex FILENAME In the typical @code{awk} program, all input is read either from the standard input (usually the keyboard) or from files whose names you specify on the @code{awk} command line. If you specify input files, @code{awk} reads data from the first one until it reaches the end; then it reads the second file until it reaches the end, and so on. The name of the current input file can be found in the built-in variable @code{FILENAME} (@pxref{Built-in Variables}).@refill The input is read in units called @dfn{records}, and processed by the rules one record at a time. By default, each record is one line. Each record read is split automatically into @dfn{fields}, to make it more convenient for a rule to work on parts of the record under consideration. On rare occasions you will need to use the @code{getline} command, which can do explicit input from any number of files (@pxref{Getline}). @menu * Records:: Controlling how data is split into records. * Fields:: An introduction to fields. * Non-Constant Fields:: Non-constant Field Numbers. * Changing Fields:: Changing the Contents of a Field. * Field Separators:: The field separator and how to change it. * Multiple Line:: Reading multi-line records. * Getline:: Reading files under explicit program control using the @code{getline} function. * Close Input:: Closing an input file (so you can read from the beginning once more). @end menu @node Records, Fields, Reading Files, Reading Files @section How Input is Split into Records @cindex record separator The @code{awk} language divides its input into records and fields. Records are separated by a character called the @dfn{record separator}. By default, the record separator is the newline character. Therefore, normally, a record is a line of text.@refill @c @cindex changing the record separator @vindex RS Sometimes you may want to use a different character to separate your records. You can use different characters by changing the built-in variable @code{RS}. The value of @code{RS} is a string that says how to separate records; the default value is @code{"\n"}, the string of just a newline character. This is why records are, by default, single lines. @code{RS} can have any string as its value, but only the first character of the string is used as the record separator. The other characters are ignored. @code{RS} is exceptional in this regard; @code{awk} uses the full value of all its other built-in variables.@refill @ignore Someday this should be true! The value of @code{RS} is not limited to a one-character string. It can be any regular expression (@pxref{Regexp}). In general, each record ends at the next string that matches the regular expression; the next record starts at the end of the matching string. This general rule is actually at work in the usual case, where @code{RS} contains just a newline: a record ends at the beginning of the next matching string (the next newline in the input) and the following record starts just after the end of this string (at the first character of the following line). The newline, since it matches @code{RS}, is not part of either record. @end ignore You can change the value of @code{RS} in the @code{awk} program with the assignment operator, @samp{=} (@pxref{Assignment Ops}). The new record-separator character should be enclosed in quotation marks to make a string constant. Often the right time to do this is at the beginning of execution, before any input has been processed, so that the very first record will be read with the proper separator. To do this, use the special @code{BEGIN} pattern (@pxref{BEGIN/END}). For example:@refill @example awk 'BEGIN @{ RS = "/" @} ; @{ print $0 @}' BBS-list @end example @noindent changes the value of @code{RS} to @code{"/"}, before reading any input. This is a string whose first character is a slash; as a result, records are separated by slashes. Then the input file is read, and the second rule in the @code{awk} program (the action with no pattern) prints each record. Since each @code{print} statement adds a newline at the end of its output, the effect of this @code{awk} program is to copy the input with each slash changed to a newline. Another way to change the record separator is on the command line, using the variable-assignment feature (@pxref{Command Line}). @example awk '@dots{}' RS="/" @var{source-file} @end example @noindent This sets @code{RS} to @samp{/} before processing @var{source-file}. The empty string (a string of no characters) has a special meaning as the value of @code{RS}: it means that records are separated only by blank lines. @xref{Multiple Line}, for more details. @cindex number of records, @code{NR} or @code{FNR} @vindex NR @vindex FNR The @code{awk} utility keeps track of the number of records that have been read so far from the current input file. This value is stored in a built-in variable called @code{FNR}. It is reset to zero when a new file is started. Another built-in variable, @code{NR}, is the total number of input records read so far from all files. It starts at zero but is never automatically reset to zero. If you change the value of @code{RS} in the middle of an @code{awk} run, the new value is used to delimit subsequent records, but the record currently being processed (and records already finished) are not affected. @node Fields, Non-Constant Fields, Records, Reading Files @section Examining Fields @cindex examining fields @cindex fields @cindex accessing fields When @code{awk} reads an input record, the record is automatically separated or @dfn{parsed} by the interpreter into pieces called @dfn{fields}. By default, fields are separated by whitespace, like words in a line. Whitespace in @code{awk} means any string of one or more spaces and/or tabs; other characters such as newline, formfeed, and so on, that are considered whitespace by other languages are @emph{not} considered whitespace by @code{awk}. The purpose of fields is to make it more convenient for you to refer to these pieces of the record. You don't have to use them---you can operate on the whole record if you wish---but fields are what make simple @code{awk} programs so powerful. @cindex @code{$} (field operator) @cindex operators, @code{$} To refer to a field in an @code{awk} program, you use a dollar-sign, @samp{$}, followed by the number of the field you want. Thus, @code{$1} refers to the first field, @code{$2} to the second, and so on. For example, suppose the following is a line of input:@refill @example This seems like a pretty nice example. @end example @noindent Here the first field, or @code{$1}, is @samp{This}; the second field, or @code{$2}, is @samp{seems}; and so on. Note that the last field, @code{$7}, is @samp{example.}. Because there is no space between the @samp{e} and the @samp{.}, the period is considered part of the seventh field.@refill No matter how many fields there are, the last field in a record can be represented by @code{$NF}. So, in the example above, @code{$NF} would be the same as @code{$7}, which is @samp{example.}. Why this works is explained below (@pxref{Non-Constant Fields}). If you try to refer to a field beyond the last one, such as @code{$8} when the record has only 7 fields, you get the empty string. @vindex NF @cindex number of fields, @code{NF} Plain @code{NF}, with no @samp{$}, is a built-in variable whose value is the number of fields in the current record. @code{$0}, which looks like an attempt to refer to the zeroth field, is a special case: it represents the whole input record. This is what you would use when you aren't interested in fields. Here are some more examples: @example awk '$1 ~ /foo/ @{ print $0 @}' BBS-list @end example @noindent This example prints each record in the file @file{BBS-list} whose first field contains the string @samp{foo}. The operator @samp{~} is called a @dfn{matching operator} (@pxref{Comparison Ops}); it tests whether a string (here, the field @code{$1}) contains a match for a given regular expression.@refill By contrast, the following example: @example awk '/foo/ @{ print $1, $NF @}' BBS-list @end example @noindent looks for @samp{foo} in @emph{the entire record} and prints the first field and the last field for each input record containing a match.@refill @node Non-Constant Fields, Changing Fields, Fields, Reading Files @section Non-constant Field Numbers The number of a field does not need to be a constant. Any expression in the @code{awk} language can be used after a @samp{$} to refer to a field. The value of the expression specifies the field number. If the value is a string, rather than a number, it is converted to a number. Consider this example:@refill @example awk '@{ print $NR @}' @end example @noindent Recall that @code{NR} is the number of records read so far: 1 in the first record, 2 in the second, etc. So this example prints the first field of the first record, the second field of the second record, and so on. For the twentieth record, field number 20 is printed; most likely, the record has fewer than 20 fields, so this prints a blank line. Here is another example of using expressions as field numbers: @example awk '@{ print $(2*2) @}' BBS-list @end example The @code{awk} language must evaluate the expression @code{(2*2)} and use its value as the number of the field to print. The @samp{*} sign represents multiplication, so the expression @code{2*2} evaluates to 4. The parentheses are used so that the multiplication is done before the @samp{$} operation; they are necessary whenever there is a binary operator in the field-number expression. This example, then, prints the hours of operation (the fourth field) for every line of the file @file{BBS-list}.@refill If the field number you compute is zero, you get the entire record. Thus, @code{$(2-2)} has the same value as @code{$0}. Negative field numbers are not allowed. The number of fields in the current record is stored in the built-in variable @code{NF} (@pxref{Built-in Variables}). The expression @code{$NF} is not a special feature: it is the direct consequence of evaluating @code{NF} and using its value as a field number. @node Changing Fields, Field Separators, Non-Constant Fields, Reading Files @section Changing the Contents of a Field @cindex field, changing contents of @cindex changing contents of a field @cindex assignment to fields You can change the contents of a field as seen by @code{awk} within an @code{awk} program; this changes what @code{awk} perceives as the current input record. (The actual input is untouched: @code{awk} never modifies the input file.) Look at this example: @example awk '@{ $3 = $2 - 10; print $2, $3 @}' inventory-shipped @end example @noindent The @samp{-} sign represents subtraction, so this program reassigns field three, @code{$3}, to be the value of field two minus ten, @code{$2 - 10}. (@xref{Arithmetic Ops}.) Then field two, and the new value for field three, are printed. In order for this to work, the text in field @code{$2} must make sense as a number; the string of characters must be converted to a number in order for the computer to do arithmetic on it. The number resulting from the subtraction is converted back to a string of characters which then becomes field three. @xref{Conversion}. When you change the value of a field (as perceived by @code{awk}), the text of the input record is recalculated to contain the new field where the old one was. Therefore, @code{$0} changes to reflect the altered field. Thus, @example awk '@{ $2 = $2 - 10; print $0 @}' inventory-shipped @end example @noindent prints a copy of the input file, with 10 subtracted from the second field of each line. You can also assign contents to fields that are out of range. For example: @example awk '@{ $6 = ($5 + $4 + $3 + $2) ; print $6 @}' inventory-shipped @end example @noindent We've just created @code{$6}, whose value is the sum of fields @code{$2}, @code{$3}, @code{$4}, and @code{$5}. The @samp{+} sign represents addition. For the file @file{inventory-shipped}, @code{$6} represents the total number of parcels shipped for a particular month. Creating a new field changes the internal @code{awk} copy of the current input record---the value of @code{$0}. Thus, if you do @samp{print $0} after adding a field, the record printed includes the new field, with the appropriate number of field separators between it and the previously existing fields. This recomputation affects and is affected by several features not yet discussed, in particular, the @dfn{output field separator}, @code{OFS}, which is used to separate the fields (@pxref{Output Separators}), and @code{NF} (the number of fields; @pxref{Fields}). For example, the value of @code{NF} is set to the number of the highest field you create.@refill Note, however, that merely @emph{referencing} an out-of-range field does @emph{not} change the value of either @code{$0} or @code{NF}. Referencing an out-of-range field merely produces a null string. For example:@refill @example if ($(NF+1) != "") print "can't happen" else print "everything is normal" @end example @noindent should print @samp{everything is normal}, because @code{NF+1} is certain to be out of range. (@xref{If Statement}, for more information about @code{awk}'s @code{if-else} statements.) @node Field Separators, Multiple Line, Changing Fields, Reading Files @section Specifying How Fields Are Separated @vindex FS @cindex fields, separating @cindex field separator, @code{FS} @cindex @samp{-F} option The way @code{awk} splits an input record into fields is controlled by the @dfn{field separator}, which is a single character or a regular expression. @code{awk} scans the input record for matches for the separator; the fields themselves are the text between the matches. For example, if the field separator is @samp{oo}, then the following line: @example moo goo gai pan @end example @noindent would be split into three fields: @samp{m}, @samp{@ g} and @samp{@ gai@ pan}. The field separator is represented by the built-in variable @code{FS}. Shell programmers take note! @code{awk} does not use the name @code{IFS} which is used by the shell.@refill You can change the value of @code{FS} in the @code{awk} program with the assignment operator, @samp{=} (@pxref{Assignment Ops}). Often the right time to do this is at the beginning of execution, before any input has been processed, so that the very first record will be read with the proper separator. To do this, use the special @code{BEGIN} pattern (@pxref{BEGIN/END}). For example, here we set the value of @code{FS} to the string @code{","}: @example awk 'BEGIN @{ FS = "," @} ; @{ print $2 @}' @end example @noindent Given the input line, @example John Q. Smith, 29 Oak St., Walamazoo, MI 42139 @end example @noindent this @code{awk} program extracts the string @samp{29 Oak St.}. @cindex field separator, choice of @cindex regular expressions as field separators Sometimes your input data will contain separator characters that don't separate fields the way you thought they would. For instance, the person's name in the example we've been using might have a title or suffix attached, such as @samp{John Q. Smith, LXIX}. From input containing such a name: @example John Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139 @end example @noindent the previous sample program would extract @samp{LXIX}, instead of @samp{29 Oak St.}. If you were expecting the program to print the address, you would be surprised. So choose your data layout and separator characters carefully to prevent such problems. As you know, by default, fields are separated by whitespace sequences (spaces and tabs), not by single spaces: two spaces in a row do not delimit an empty field. The default value of the field separator is a string @w{@code{" "}} containing a single space. If this value were interpreted in the usual way, each space character would separate fields, so two spaces in a row would make an empty field between them. The reason this does not happen is that a single space as the value of @code{FS} is a special case: it is taken to specify the default manner of delimiting fields. If @code{FS} is any other single character, such as @code{","}, then each occurrence of that character separates two fields. Two consecutive occurrences delimit an empty field. If the character occurs at the beginning or the end of the line, that too delimits an empty field. The space character is the only single character which does not follow these rules. More generally, the value of @code{FS} may be a string containing any regular expression. Then each match in the record for the regular expression separates fields. For example, the assignment:@refill @example FS = ", \t" @end example @noindent makes every area of an input line that consists of a comma followed by a space and a tab, into a field separator. (@samp{\t} stands for a tab.)@refill For a less trivial example of a regular expression, suppose you want single spaces to separate fields the way single commas were used above. You can set @code{FS} to @w{@code{"[@ ]"}}. This regular expression matches a single space and nothing else. @cindex field separator, setting on command line @cindex command line, setting @code{FS} on @code{FS} can be set on the command line. You use the @samp{-F} argument to do so. For example: @example awk -F, '@var{program}' @var{input-files} @end example @noindent sets @code{FS} to be the @samp{,} character. Notice that the argument uses a capital @samp{F}. Contrast this with @samp{-f}, which specifies a file containing an @code{awk} program. Case is significant in command options: the @samp{-F} and @samp{-f} options have nothing to do with each other. You can use both options at the same time to set the @code{FS} argument @emph{and} get an @code{awk} program from a file. As a special case, in compatibility mode (@pxref{Command Line}), if the argument to @samp{-F} is @samp{t}, then @code{FS} is set to the tab character. (This is because if you type @samp{-F\t}, without the quotes, at the shell, the @samp{\} gets deleted, so @code{awk} figures that you really want your fields to be separated with tabs, and not @samp{t}s. Use @samp{FS="t"} on the command line if you really do want to separate your fields with @samp{t}s.) For example, let's use an @code{awk} program file called @file{baud.awk} that contains the pattern @code{/300/}, and the action @samp{print $1}. Here is the program: @example /300/ @{ print $1 @} @end example Let's also set @code{FS} to be the @samp{-} character, and run the program on the file @file{BBS-list}. The following command prints a list of the names of the bulletin boards that operate at 300 baud and the first three digits of their phone numbers:@refill @example awk -F- -f baud.awk BBS-list @end example @noindent It produces this output: @example aardvark 555 alpo barfly 555 bites 555 camelot 555 core 555 fooey 555 foot 555 macfoo 555 sdace 555 sabafoo 555 @end example @noindent Note the second line of output. If you check the original file, you will see that the second line looked like this: @example alpo-net 555-3412 2400/1200/300 A @end example The @samp{-} as part of the system's name was used as the field separator, instead of the @samp{-} in the phone number that was originally intended. This demonstrates why you have to be careful in choosing your field and record separators. The following program searches the system password file, and prints the entries for users who have no password: @example awk -F: '$2 == ""' /etc/passwd @end example @noindent Here we use the @samp{-F} option on the command line to set the field separator. Note that fields in @file{/etc/passwd} are separated by colons. The second field represents a user's encrypted password, but if the field is empty, that user has no password. @node Multiple Line, Getline, Field Separators, Reading Files @section Multiple-Line Records @cindex multiple line records @cindex input, multiple line records @cindex reading files, multiple line records @cindex records, multiple line In some data bases, a single line cannot conveniently hold all the information in one entry. In such cases, you can use multi-line records. The first step in doing this is to choose your data format: when records are not defined as single lines, how do you want to define them? What should separate records? One technique is to use an unusual character or string to separate records. For example, you could use the formfeed character (written @samp{\f} in @code{awk}, as in C) to separate them, making each record a page of the file. To do this, just set the variable @code{RS} to @code{"\f"} (a string containing the formfeed character). Any other character could equally well be used, as long as it won't be part of the data in a record. @ignore Another technique is to have blank lines separate records. The string @code{"^\n+"} is a regular expression that matches any sequence of newlines starting at the beginning of a line---in other words, it matches a sequence of blank lines. If you set @code{RS} to this string, a record always ends at the first blank line encountered. In addition, a regular expression always matches the longest possible sequence when there is a choice. So the next record doesn't start until the first nonblank line that follows---no matter how many blank lines appear in a row, they are considered one record-separator. @end ignore Another technique is to have blank lines separate records. By a special dispensation, a null string as the value of @code{RS} indicates that records are separated by one or more blank lines. If you set @code{RS} to the null string, a record always ends at the first blank line encountered. And the next record doesn't start until the first nonblank line that follows---no matter how many blank lines appear in a row, they are considered one record-separator. The second step is to separate the fields in the record. One way to do this is to put each field on a separate line: to do this, just set the variable @code{FS} to the string @code{"\n"}. (This simple regular expression matches a single newline.) Another idea is to divide each of the lines into fields in the normal manner. This happens by default as a result of a special feature: when @code{RS} is set to the null string, the newline character @emph{always} acts as a field separator. This is in addition to whatever field separations result from @code{FS}. The original motivation for this special exception was probably so that you get useful behavior in the default case (i.e., @w{@code{FS == " "}}). This feature can be a problem if you really don't want the newline character to separate fields, since there is no way to prevent it. However, you can work around this by using the @code{split} function to break up the record manually (@pxref{String Functions}). @ignore Here are two ways to use records separated by blank lines and break each line into fields normally: @example awk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} @{ print $1 @}' BBS-list @exdent @r{or} awk 'BEGIN @{ RS = "^\n+"; FS = "[ \t\n]+" @} @{ print $1 @}' BBS-list @end example @end ignore @ignore Here is how to use records separated by blank lines and break each line into fields normally: @example awk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} ; @{ print $1 @}' BBS-list @end example @end ignore @node Getline, Close Input, Multiple Line, Reading Files @section Explicit Input with @code{getline} @findex getline @cindex input, explicit @cindex explicit input @cindex input, @code{getline} command @cindex reading files, @code{getline} command So far we have been getting our input files from @code{awk}'s main input stream---either the standard input (usually your terminal) or the files specified on the command line. The @code{awk} language has a special built-in command called @code{getline} that can be used to read input under your explicit control. This command is quite complex and should @emph{not} be used by beginners. It is covered here because this is the chapter on input. The examples that follow the explanation of the @code{getline} command include material that has not been covered yet. Therefore, come back and study the @code{getline} command @emph{after} you have reviewed the rest of this manual and have a good knowledge of how @code{awk} works. @code{getline} returns 1 if it finds a record, and 0 if the end of the file is encountered. If there is some error in getting a record, such as a file that cannot be opened, then @code{getline} returns @minus{}1. In the following examples, @var{command} stands for a string value that represents a shell command. @table @code @item getline The @code{getline} command can be used without arguments to read input from the current input file. All it does in this case is read the next input record and split it up into fields. This is useful if you've finished processing the current record, but you want to do some special processing @emph{right now} on the next record. Here's an example:@refill @example awk '@{ if (t = index($0, "/*")) @{ if(t > 1) tmp = substr($0, 1, t - 1) else tmp = "" u = index(substr($0, t + 2), "*/") while (! u) @{ getline t = -1 u = index($0, "*/") @} if(u <= length($0) - 2) $0 = tmp substr($0, t + u + 3) else $0 = tmp @} print $0 @}' @end example This @code{awk} program deletes all comments, @samp{/* @dots{} */}, from the input. By replacing the @samp{print $0} with other statements, you could perform more complicated processing on the decommented input, such as searching it for matches for a regular expression. This form of the @code{getline} command sets @code{NF} (the number of fields; @pxref{Fields}), @code{NR} (the number of records read so far; @pxref{Records}), @code{FNR} (the number of records read from this input file), and the value of @code{$0}. @strong{Note:} the new value of @code{$0} is used in testing the patterns of any subsequent rules. The original value of @code{$0} that triggered the rule which executed @code{getline} is lost. By contrast, the @code{next} statement reads a new record but immediately begins processing it normally, starting with the first rule in the program. @xref{Next Statement}. @item getline @var{var} This form of @code{getline} reads a record into the variable @var{var}. This is useful when you want your program to read the next record from the current input file, but you don't want to subject the record to the normal input processing. For example, suppose the next line is a comment, or a special string, and you want to read it, but you must make certain that it won't trigger any rules. This version of @code{getline} allows you to read that line and store it in a variable so that the main read-a-line-and-check-each-rule loop of @code{awk} never sees it. The following example swaps every two lines of input. For example, given: @example wan tew free phore @end example @noindent it outputs: @example tew wan phore free @end example @noindent Here's the program: @example awk '@{ if ((getline tmp) > 0) @{ print tmp print $0 @} else print $0 @}' @end example The @code{getline} function used in this way sets only the variables @code{NR} and @code{FNR} (and of course, @var{var}). The record is not split into fields, so the values of the fields (including @code{$0}) and the value of @code{NF} do not change.@refill @item getline < @var{file} @cindex input redirection @cindex redirection of input This form of the @code{getline} function takes its input from the file @var{file}. Here @var{file} is a string-valued expression that specifies the file name. @samp{< @var{file}} is called a @dfn{redirection} since it directs input to come from a different place. This form is useful if you want to read your input from a particular file, instead of from the main input stream. For example, the following program reads its input record from the file @file{foo.input} when it encounters a first field with a value equal to 10 in the current input file.@refill @example awk '@{ if ($1 == 10) @{ getline < "foo.input" print @} else print @}' @end example Since the main input stream is not used, the values of @code{NR} and @code{FNR} are not changed. But the record read is split into fields in the normal manner, so the values of @code{$0} and other fields are changed. So is the value of @code{NF}. This does not cause the record to be tested against all the patterns in the @code{awk} program, in the way that would happen if the record were read normally by the main processing loop of @code{awk}. However the new record is tested against any subsequent rules, just as when @code{getline} is used without a redirection. @item getline @var{var} < @var{file} This form of the @code{getline} function takes its input from the file @var{file} and puts it in the variable @var{var}. As above, @var{file} is a string-valued expression that specifies the file to read from. In this version of @code{getline}, none of the built-in variables are changed, and the record is not split into fields. The only variable changed is @var{var}. For example, the following program copies all the input files to the output, except for records that say @w{@samp{@@include @var{filename}}}. Such a record is replaced by the contents of the file @var{filename}.@refill @example awk '@{ if (NF == 2 && $1 == "@@include") @{ while ((getline line < $2) > 0) print line close($2) @} else print @}' @end example Note here how the name of the extra input file is not built into the program; it is taken from the data, from the second field on the @samp{@@include} line. The @code{close} function is called to ensure that if two identical @samp{@@include} lines appear in the input, the entire specified file is included twice. @xref{Close Input}. One deficiency of this program is that it does not process nested @samp{@@include} statements the way a true macro preprocessor would. @item @var{command} | getline You can @dfn{pipe} the output of a command into @code{getline}. A pipe is simply a way to link the output of one program to the input of another. In this case, the string @var{command} is run as a shell command and its output is piped into @code{awk} to be used as input. This form of @code{getline} reads one record from the pipe. For example, the following program copies input to output, except for lines that begin with @samp{@@execute}, which are replaced by the output produced by running the rest of the line as a shell command: @example awk '@{ if ($1 == "@@execute") @{ tmp = substr($0, 10) while ((tmp | getline) > 0) print close(tmp) @} else print @}' @end example @noindent The @code{close} function is called to ensure that if two identical @samp{@@execute} lines appear in the input, the command is run again for each one. @xref{Close Input}. Given the input: @example foo bar baz @@execute who bletch @end example @noindent the program might produce: @example foo bar baz hack ttyv0 Jul 13 14:22 hack ttyp0 Jul 13 14:23 (gnu:0) hack ttyp1 Jul 13 14:23 (gnu:0) hack ttyp2 Jul 13 14:23 (gnu:0) hack ttyp3 Jul 13 14:23 (gnu:0) bletch @end example @noindent Notice that this program ran the command @code{who} and printed the result. (If you try this program yourself, you will get different results, showing you logged in.) This variation of @code{getline} splits the record into fields, sets the value of @code{NF} and recomputes the value of @code{$0}. The values of @code{NR} and @code{FNR} are not changed. @item @var{command} | getline @var{var} The output of the command @var{command} is sent through a pipe to @code{getline} and into the variable @var{var}. For example, the following program reads the current date and time into the variable @code{current_time}, using the utility called @code{date}, and then prints it.@refill @group @example awk 'BEGIN @{ "date" | getline current_time close("date") print "Report printed on " current_time @}' @end example @end group In this version of @code{getline}, none of the built-in variables are changed, and the record is not split into fields. @end table @node Close Input,, Getline, Reading Files @section Closing Input Files and Pipes @cindex closing input files and pipes @findex close If the same file name or the same shell command is used with @code{getline} more than once during the execution of an @code{awk} program, the file is opened (or the command is executed) only the first time. At that time, the first record of input is read from that file or command. The next time the same file or command is used in @code{getline}, another record is read from it, and so on. This implies that if you want to start reading the same file again from the beginning, or if you want to rerun a shell command (rather that reading more output from the command), you must take special steps. What you can do is use the @code{close} function, as follows: @example close(@var{filename}) @end example @noindent or @example close(@var{command}) @end example The argument @var{filename} or @var{command} can be any expression. Its value must exactly equal the string that was used to open the file or start the command---for example, if you open a pipe with this: @example "sort -r names" | getline foo @end example @noindent then you must close it with this: @example close("sort -r names") @end example Once this function call is executed, the next @code{getline} from that file or command will reopen the file or rerun the command. @node Printing, One-liners, Reading Files, Top @chapter Printing Output @cindex printing @cindex output One of the most common things that actions do is to output or @dfn{print} some or all of the input. For simple output, use the @code{print} statement. For fancier formatting use the @code{printf} statement. Both are described in this chapter. @menu * Print:: The @code{print} statement. * Print Examples:: Simple examples of @code{print} statements. * Output Separators:: The output separators and how to change them. * Printf:: The @code{printf} statement. * Redirection:: How to redirect output to multiple files and pipes. * Special Files:: File name interpretation in @code{gawk}. @code{gawk} allows access to inherited file descriptors. @end menu @node Print, Print Examples, Printing, Printing @section The @code{print} Statement @cindex @code{print} statement The @code{print} statement does output with simple, standardized formatting. You specify only the strings or numbers to be printed, in a list separated by commas. They are output, separated by single spaces, followed by a newline. The statement looks like this: @example print @var{item1}, @var{item2}, @dots{} @end example @noindent The entire list of items may optionally be enclosed in parentheses. The parentheses are necessary if any of the item expressions uses a relational operator; otherwise it could be confused with a redirection (@pxref{Redirection}). The relational operators are @samp{==}, @samp{!=}, @samp{<}, @samp{>}, @samp{>=}, @samp{<=}, @samp{~} and @samp{!~} (@pxref{Comparison Ops}).@refill The items printed can be constant strings or numbers, fields of the current record (such as @code{$1}), variables, or any @code{awk} expressions. The @code{print} statement is completely general for computing @emph{what} values to print. With one exception (@pxref{Output Separators}), what you can't do is specify @emph{how} to print them---how many columns to use, whether to use exponential notation or not, and so on. For that, you need the @code{printf} statement (@pxref{Printf}). The simple statement @samp{print} with no items is equivalent to @samp{print $0}: it prints the entire current record. To print a blank line, use @samp{print ""}, where @code{""} is the null, or empty, string. To print a fixed piece of text, use a string constant such as @w{@code{"Hello there"}} as one item. If you forget to use the double-quote characters, your text will be taken as an @code{awk} expression, and you will probably get an error. Keep in mind that a space is printed between any two items. Most often, each @code{print} statement makes one line of output. But it isn't limited to one line. If an item value is a string that contains a newline, the newline is output along with the rest of the string. A single @code{print} can make any number of lines this way. @node Print Examples, Output Separators, Print, Printing @section Examples of @code{print} Statements Here is an example of printing a string that contains embedded newlines: @example awk 'BEGIN @{ print "line one\nline two\nline three" @}' @end example @noindent produces output like this: @example line one line two line three @end example Here is an example that prints the first two fields of each input record, with a space between them: @example awk '@{ print $1, $2 @}' inventory-shipped @end example @noindent Its output looks like this: @example Jan 13 Feb 15 Mar 15 @dots{} @end example A common mistake in using the @code{print} statement is to omit the comma between two items. This often has the effect of making the items run together in the output, with no space. The reason for this is that juxtaposing two string expressions in @code{awk} means to concatenate them. For example, without the comma: @example awk '@{ print $1 $2 @}' inventory-shipped @end example @noindent prints: @example Jan13 Feb15 Mar15 @dots{} @end example Neither example's output makes much sense to someone unfamiliar with the file @file{inventory-shipped}. A heading line at the beginning would make it clearer. Let's add some headings to our table of months (@code{$1}) and green crates shipped (@code{$2}). We do this using the @code{BEGIN} pattern (@pxref{BEGIN/END}) to cause the headings to be printed only once: @c the formatting is strange here because the @{ becomes just a brace. @example awk 'BEGIN @{ print "Month Crates" print "----- ------" @} @{ print $1, $2 @}' inventory-shipped @end example @noindent Did you already guess what happens? This program prints the following: @group @example Month Crates ----- ------ Jan 13 Feb 15 Mar 15 @dots{} @end example @end group @noindent The headings and the table data don't line up! We can fix this by printing some spaces between the two fields: @example awk 'BEGIN @{ print "Month Crates" print "----- ------" @} @{ print $1, " ", $2 @}' inventory-shipped @end example You can imagine that this way of lining up columns can get pretty complicated when you have many columns to fix. Counting spaces for two or three columns can be simple, but more than this and you can get ``lost'' quite easily. This is why the @code{printf} statement was created (@pxref{Printf}); one of its specialties is lining up columns of data. @node Output Separators, Printf, Print Examples, Printing @section Output Separators @cindex output field separator, @code{OFS} @vindex OFS @vindex ORS @cindex output record separator, @code{ORS} As mentioned previously, a @code{print} statement contains a list of items, separated by commas. In the output, the items are normally separated by single spaces. But they do not have to be spaces; a single space is only the default. You can specify any string of characters to use as the @dfn{output field separator} by setting the built-in variable @code{OFS}. The initial value of this variable is the string @w{@code{" "}}. The output from an entire @code{print} statement is called an @dfn{output record}. Each @code{print} statement outputs one output record and then outputs a string called the @dfn{output record separator}. The built-in variable @code{ORS} specifies this string. The initial value of the variable is the string @code{"\n"} containing a newline character; thus, normally each @code{print} statement makes a separate line. You can change how output fields and records are separated by assigning new values to the variables @code{OFS} and/or @code{ORS}. The usual place to do this is in the @code{BEGIN} rule (@pxref{BEGIN/END}), so that it happens before any input is processed. You may also do this with assignments on the command line, before the names of your input files. The following example prints the first and second fields of each input record separated by a semicolon, with a blank line added after each line:@refill @example awk 'BEGIN @{ OFS = ";"; ORS = "\n\n" @} @{ print $1, $2 @}' BBS-list @end example If the value of @code{ORS} does not contain a newline, all your output will be run together on a single line, unless you output newlines some other way. @node Printf, Redirection, Output Separators, Printing @section Using @code{printf} Statements For Fancier Printing @cindex formatted output @cindex output, formatted If you want more precise control over the output format than @code{print} gives you, use @code{printf}. With @code{printf} you can specify the width to use for each item, and you can specify various stylistic choices for numbers (such as what radix to use, whether to print an exponent, whether to print a sign, and how many digits to print after the decimal point). You do this by specifying a string, called the @dfn{format string}, which controls how and where to print the other arguments. @menu * Basic Printf:: Syntax of the @code{printf} statement. * Control Letters:: Format-control letters. * Format Modifiers:: Format-specification modifiers. * Printf Examples:: Several examples. @end menu @node Basic Printf, Control Letters, Printf, Printf @subsection Introduction to the @code{printf} Statement @cindex @code{printf} statement, syntax of The @code{printf} statement looks like this:@refill @example printf @var{format}, @var{item1}, @var{item2}, @dots{} @end example @noindent The entire list of items may optionally be enclosed in parentheses. The parentheses are necessary if any of the item expressions uses a relational operator; otherwise it could be confused with a redirection (@pxref{Redirection}). The relational operators are @samp{==}, @samp{!=}, @samp{<}, @samp{>}, @samp{>=}, @samp{<=}, @samp{~} and @samp{!~} (@pxref{Comparison Ops}).@refill @cindex format string The difference between @code{printf} and @code{print} is the argument @var{format}. This is an expression whose value is taken as a string; its job is to say how to output each of the other arguments. It is called the @dfn{format string}. The format string is essentially the same as in the C library function @code{printf}. Most of @var{format} is text to be output verbatim. Scattered among this text are @dfn{format specifiers}, one per item. Each format specifier says to output the next item at that place in the format.@refill The @code{printf} statement does not automatically append a newline to its output. It outputs nothing but what the format specifies. So if you want a newline, you must include one in the format. The output separator variables @code{OFS} and @code{ORS} have no effect on @code{printf} statements. @node Control Letters, Format Modifiers, Basic Printf, Printf @subsection Format-Control Letters @cindex @code{printf}, format-control characters @cindex format specifier A format specifier starts with the character @samp{%} and ends with a @dfn{format-control letter}; it tells the @code{printf} statement how to output one item. (If you actually want to output a @samp{%}, write @samp{%%}.) The format-control letter specifies what kind of value to print. The rest of the format specifier is made up of optional @dfn{modifiers} which are parameters such as the field width to use. Here is a list of the format-control letters: @table @samp @item c This prints a number as an ASCII character. Thus, @samp{printf "%c", 65} outputs the letter @samp{A}. The output for a string value is the first character of the string. @item d This prints a decimal integer. @item i This also prints a decimal integer. @item e This prints a number in scientific (exponential) notation. For example, @example printf "%4.3e", 1950 @end example @noindent prints @samp{1.950e+03}, with a total of 4 significant figures of which 3 follow the decimal point. The @samp{4.3} are @dfn{modifiers}, discussed below. @item f This prints a number in floating point notation. @item g This prints either scientific notation or floating point notation, whichever is shorter. @item o This prints an unsigned octal integer. @item s This prints a string. @item x This prints an unsigned hexadecimal integer. @item X This prints an unsigned hexadecimal integer. However, for the values 10 through 15, it uses the letters @samp{A} through @samp{F} instead of @samp{a} through @samp{f}. @item % This isn't really a format-control letter, but it does have a meaning when used after a @samp{%}: the sequence @samp{%%} outputs one @samp{%}. It does not consume an argument. @end table @node Format Modifiers, Printf Examples, Control Letters, Printf @subsection Modifiers for @code{printf} Formats @cindex @code{printf}, modifiers @cindex modifiers (in format specifiers) A format specification can also include @dfn{modifiers} that can control how much of the item's value is printed and how much space it gets. The modifiers come between the @samp{%} and the format-control letter. Here are the possible modifiers, in the order in which they may appear: @table @samp @item - The minus sign, used before the width modifier, says to left-justify the argument within its specified width. Normally the argument is printed right-justified in the specified width. Thus, @example printf "%-4s", "foo" @end example @noindent prints @samp{foo }. @item @var{width} This is a number representing the desired width of a field. Inserting any number between the @samp{%} sign and the format control character forces the field to be expanded to this width. The default way to do this is to pad with spaces on the left. For example, @example printf "%4s", "foo" @end example @noindent prints @samp{ foo}. The value of @var{width} is a minimum width, not a maximum. If the item value requires more than @var{width} characters, it can be as wide as necessary. Thus, @example printf "%4s", "foobar" @end example @noindent prints @samp{foobar}. Preceding the @var{width} with a minus sign causes the output to be padded with spaces on the right, instead of on the left. @item .@var{prec} This is a number that specifies the precision to use when printing. This specifies the number of digits you want printed to the right of the decimal point. For a string, it specifies the maximum number of characters from the string that should be printed. @end table The C library @code{printf}'s dynamic @var{width} and @var{prec} capability (for example, @code{"%*.*s"}) is not yet supported. However, it can easily be simulated using concatenation to dynamically build the format string.@refill @node Printf Examples, , Format Modifiers, Printf @subsection Examples of Using @code{printf} Here is how to use @code{printf} to make an aligned table: @example awk '@{ printf "%-10s %s\n", $1, $2 @}' BBS-list @end example @noindent prints the names of bulletin boards (@code{$1}) of the file @file{BBS-list} as a string of 10 characters, left justified. It also prints the phone numbers (@code{$2}) afterward on the line. This produces an aligned two-column table of names and phone numbers: @example aardvark 555-5553 alpo-net 555-3412 barfly 555-7685 bites 555-1675 camelot 555-0542 core 555-2912 fooey 555-1234 foot 555-6699 macfoo 555-6480 sdace 555-3430 sabafoo 555-2127 @end example Did you notice that we did not specify that the phone numbers be printed as numbers? They had to be printed as strings because the numbers are separated by a dash. This dash would be interpreted as a minus sign if we had tried to print the phone numbers as numbers. This would have led to some pretty confusing results. We did not specify a width for the phone numbers because they are the last things on their lines. We don't need to put spaces after them. We could make our table look even nicer by adding headings to the tops of the columns. To do this, use the @code{BEGIN} pattern (@pxref{BEGIN/END}) to cause the header to be printed only once, at the beginning of the @code{awk} program: @example awk 'BEGIN @{ print "Name Number" print "---- ------" @} @{ printf "%-10s %s\n", $1, $2 @}' BBS-list @end example Did you notice that we mixed @code{print} and @code{printf} statements in the above example? We could have used just @code{printf} statements to get the same results: @example awk 'BEGIN @{ printf "%-10s %s\n", "Name", "Number" printf "%-10s %s\n", "----", "------" @} @{ printf "%-10s %s\n", $1, $2 @}' BBS-list @end example @noindent By outputting each column heading with the same format specification used for the elements of the column, we have made sure that the headings are aligned just like the columns. The fact that the same format specification is used three times can be emphasized by storing it in a variable, like this: @example awk 'BEGIN @{ format = "%-10s %s\n" printf format, "Name", "Number" printf format, "----", "------" @} @{ printf format, $1, $2 @}' BBS-list @end example See if you can use the @code{printf} statement to line up the headings and table data for our @file{inventory-shipped} example covered earlier in the section on the @code{print} statement (@pxref{Print}). @node Redirection, Special Files, Printf, Printing @section Redirecting Output of @code{print} and @code{printf} @cindex output redirection @cindex redirection of output So far we have been dealing only with output that prints to the standard output, usually your terminal. Both @code{print} and @code{printf} can be told to send their output to other places. This is called @dfn{redirection}.@refill A redirection appears after the @code{print} or @code{printf} statement. Redirections in @code{awk} are written just like redirections in shell commands, except that they are written inside the @code{awk} program. @menu * File/Pipe Redirection:: Redirecting Output to Files and Pipes. * Close Output:: How to close output files and pipes. @end menu @node File/Pipe Redirection, Close Output, Redirection, Redirection @subsection Redirecting Output to Files and Pipes Here are the three forms of output redirection. They are all shown for the @code{print} statement, but they work identically for @code{printf} also. @table @code @item print @var{items} > @var{output-file} This type of redirection prints the items onto the output file @var{output-file}. The file name @var{output-file} can be any expression. Its value is changed to a string and then used as a file name (@pxref{Expressions}).@refill When this type of redirection is used, the @var{output-file} is erased before the first output is written to it. Subsequent writes do not erase @var{output-file}, but append to it. If @var{output-file} does not exist, then it is created.@refill For example, here is how one @code{awk} program can write a list of BBS names to a file @file{name-list} and a list of phone numbers to a file @file{phone-list}. Each output file contains one name or number per line. @example awk '@{ print $2 > "phone-list" print $1 > "name-list" @}' BBS-list @end example @item print @var{items} >> @var{output-file} This type of redirection prints the items onto the output file @var{output-file}. The difference between this and the single-@samp{>} redirection is that the old contents (if any) of @var{output-file} are not erased. Instead, the @code{awk} output is appended to the file. @cindex pipes for output @cindex output, piping @item print @var{items} | @var{command} It is also possible to send output through a @dfn{pipe} instead of into a file. This type of redirection opens a pipe to @var{command} and writes the values of @var{items} through this pipe, to another process created to execute @var{command}.@refill The redirection argument @var{command} is actually an @code{awk} expression. Its value is converted to a string, whose contents give the shell command to be run. For example, this produces two files, one unsorted list of BBS names and one list sorted in reverse alphabetical order: @example awk '@{ print $1 > "names.unsorted" print $1 | "sort -r > names.sorted" @}' BBS-list @end example Here the unsorted list is written with an ordinary redirection while the sorted list is written by piping through the @code{sort} utility. Here is an example that uses redirection to mail a message to a mailing list @samp{bug-system}. This might be useful when trouble is encountered in an @code{awk} script run periodically for system maintenance. @example print "Awk script failed:", $0 | "mail bug-system" print "at record number", FNR, "of", FILENAME | "mail bug-system" close("mail bug-system") @end example We call the @code{close} function here because it's a good idea to close the pipe as soon as all the intended output has been sent to it. @xref{Close Output}, for more information on this. @end table Redirecting output using @samp{>}, @samp{>>}, or @samp{|} asks the system to open a file or pipe only if the particular @var{file} or @var{command} you've specified has not already been written to by your program.@refill @node Close Output, , File/Pipe Redirection, Redirection @subsection Closing Output Files and Pipes @cindex closing output files and pipes @findex close When a file or pipe is opened, the file name or command associated with it is remembered by @code{awk} and subsequent writes to the same file or command are appended to the previous writes. The file or pipe stays open until @code{awk} exits. This is usually convenient. Sometimes there is a reason to close an output file or pipe earlier than that. To do this, use the @code{close} function, as follows: @example close(@var{filename}) @end example @noindent or @example close(@var{command}) @end example The argument @var{filename} or @var{command} can be any expression. Its value must exactly equal the string used to open the file or pipe to begin with---for example, if you open a pipe with this: @example print $1 | "sort -r > names.sorted" @end example @noindent then you must close it with this: @example close("sort -r > names.sorted") @end example Here are some reasons why you might need to close an output file: @itemize @bullet @item To write a file and read it back later on in the same @code{awk} program. Close the file when you are finished writing it; then you can start reading it with @code{getline} (@pxref{Getline}). @item To write numerous files, successively, in the same @code{awk} program. If you don't close the files, eventually you will exceed the system limit on the number of open files in one process. So close each one when you are finished writing it. @item To make a command finish. When you redirect output through a pipe, the command reading the pipe normally continues to try to read input as long as the pipe is open. Often this means the command cannot really do its work until the pipe is closed. For example, if you redirect output to the @code{mail} program, the message is not actually sent until the pipe is closed. @item To run the same program a second time, with the same arguments. This is not the same thing as giving more input to the first run! For example, suppose you pipe output to the @code{mail} program. If you output several lines redirected to this pipe without closing it, they make a single message of several lines. By contrast, if you close the pipe after each line of output, then each line makes a separate message. @end itemize @node Special Files, , Redirection, Printing @section Standard I/O Streams @cindex standard input @cindex standard output @cindex standard error output @cindex file descriptors Running programs conventionally have three input and output streams already available to them for reading and writing. These are known as the @dfn{standard input}, @dfn{standard output}, and @dfn{standard error output}. These streams are, by default, terminal input and output, but they are often redirected with the shell, via the @samp{<}, @samp{<<}, @samp{>}, @samp{>>}, @samp{>&} and @samp{|} operators. Standard error is used only for writing error messages; the reason we have two separate streams, standard output and standard error, is so that they can be redirected separately. @c @cindex differences between @code{gawk} and @code{awk} In other implementations of @code{awk}, the only way to write an error message to standard error in an @code{awk} program is as follows: @example print "Serious error detected!\n" | "cat 1>&2" @end example @noindent This works by opening a pipeline to a shell command which can access the standard error stream which it inherits from the @code{awk} process. This is far from elegant, and is also inefficient, since it requires a separate process. So people writing @code{awk} programs have often neglected to do this. Instead, they have sent the error messages to the terminal, like this: @example NF != 4 @{ printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/tty" @} @end example @noindent This has the same effect most of the time, but not always: although the standard error stream is usually the terminal, it can be redirected, and when that happens, writing to the terminal is not correct. In fact, if @code{awk} is run from a background job, it may not have a terminal at all. Then opening @file{/dev/tty} will fail. @code{gawk} provides special file names for accessing the three standard streams. When you redirect input or output in @code{gawk}, if the file name matches one of these special names, then @code{gawk} directly uses the stream it stands for. @cindex @file{/dev/stdin} @cindex @file{/dev/stdout} @cindex @file{/dev/stderr} @cindex @file{/dev/fd/} @table @file @item /dev/stdin The standard input (file descriptor 0). @item /dev/stdout The standard output (file descriptor 1). @item /dev/stderr The standard error output (file descriptor 2). @item /dev/fd/@var{n} The file associated with file descriptor @var{n}. Such a file must have been opened by the program initiating the @code{awk} execution (typically the shell). Unless you take special pains, only descriptors 0, 1 and 2 are available. @end table The file names @file{/dev/stdin}, @file{/dev/stdout}, and @file{/dev/stderr} are aliases for @file{/dev/fd/0}, @file{/dev/fd/1}, and @file{/dev/fd/2}, respectively, but they are more self-explanatory. The proper way to write an error message in a @code{gawk} program is to use @file{/dev/stderr}, like this: @example NF != 4 @{ printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/stderr" @} @end example Recognition of these special file names is disabled if @code{gawk} is in compatibility mode (@pxref{Command Line}). @node One-liners, Patterns, Printing, Top @chapter Useful ``One-liners'' @cindex one-liners Useful @code{awk} programs are often short, just a line or two. Here is a collection of useful, short programs to get you started. Some of these programs contain constructs that haven't been covered yet. The description of the program will give you a good idea of what is going on, but please read the rest of the manual to become an @code{awk} expert! @table @code @item awk '@{ num_fields = num_fields + NF @} @itemx @ @ @ @ @ END @{ print num_fields @}' This program prints the total number of fields in all input lines. @item awk 'length($0) > 80' This program prints every line longer than 80 characters. The sole rule has a relational expression as its pattern, and has no action (so the default action, printing the record, is used). @item awk 'NF > 0' This program prints every line that has at least one field. This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been deleted). @item awk '@{ if (NF > 0) print @}' This program also prints every line that has at least one field. Here we allow the rule to match every line, then decide in the action whether to print. @item awk@ 'BEGIN@ @{@ for (i = 1; i <= 7; i++) @itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ print int(101 * rand()) @}' This program prints 7 random numbers from 0 to 100, inclusive. @item ls -l @var{files} | awk '@{ x += $4 @} ; END @{ print "total bytes: " x @}' This program prints the total number of bytes used by @var{files}. @item expand@ @var{file}@ |@ awk@ '@{ if (x < length()) x = length() @} @itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ END @{ print "maximum line length is " x @}' This program prints the maximum line length of @var{file}. The input is piped through the @code{expand} program to change tabs into spaces, so the widths compared are actually the right-margin columns. @end table @node Patterns, Actions, One-liners, Top @chapter Patterns @cindex pattern, definition of Patterns in @code{awk} control the execution of rules: a rule is executed when its pattern matches the current input record. This chapter tells all about how to write patterns. @menu * Kinds of Patterns:: A list of all kinds of patterns. The following subsections describe them in detail. * Empty:: The empty pattern, which matches every record. * Regexp:: Regular expressions such as @samp{/foo/}. * Comparison Patterns:: Comparison expressions such as @code{$1 > 10}. * Boolean Patterns:: Combining comparison expressions. * Expression Patterns:: Any expression can be used as a pattern. * Ranges:: Using pairs of patterns to specify record ranges. * BEGIN/END:: Specifying initialization and cleanup rules. @end menu @node Kinds of Patterns, Empty, Patterns, Patterns @section Kinds of Patterns @cindex patterns, types of Here is a summary of the types of patterns supported in @code{awk}. @table @code @item /@var{regular expression}/ A regular expression as a pattern. It matches when the text of the input record fits the regular expression. (@xref{Regexp, , Regular Expressions as Patterns}.) @item @var{expression} A single expression. It matches when its value, converted to a number, is nonzero (if a number) or nonnull (if a string). (@xref{Expression Patterns}.) @item @var{pat1}, @var{pat2} A pair of patterns separated by a comma, specifying a range of records. (@xref{Ranges, , Specifying Record Ranges With Patterns}.) @item BEGIN @itemx END Special patterns to supply start-up or clean-up information to @code{awk}. (@xref{BEGIN/END}.) @item @var{null} The empty pattern matches every input record. (@xref{Empty, , The Empty Pattern}.) @end table @node Empty, Regexp, Kinds of Patterns, Patterns @section The Empty Pattern @cindex empty pattern @cindex pattern, empty An empty pattern is considered to match @emph{every} input record. For example, the program:@refill @example awk '@{ print $1 @}' BBS-list @end example @noindent prints just the first field of every record. @node Regexp, Comparison Patterns, Empty, Patterns @section Regular Expressions as Patterns @cindex pattern, regular expressions @cindex regexp @cindex regular expressions as patterns A @dfn{regular expression}, or @dfn{regexp}, is a way of describing a class of strings. A regular expression enclosed in slashes (@samp{/}) is an @code{awk} pattern that matches every input record whose text belongs to that class. The simplest regular expression is a sequence of letters, numbers, or both. Such a regexp matches any string that contains that sequence. Thus, the regexp @samp{foo} matches any string containing @samp{foo}. Therefore, the pattern @code{/foo/} matches any input record containing @samp{foo}. Other kinds of regexps let you specify more complicated classes of strings. @menu * Usage: Regexp Usage. How regexps are used in patterns. * Operators: Regexp Operators. How to write a regexp. * Case-sensitivity:: How to do case-insensitive matching. @end menu @node Regexp Usage, Regexp Operators, Regexp, Regexp @subsection How to Use Regular Expressions A regular expression can be used as a pattern by enclosing it in slashes. Then the regular expression is matched against the entire text of each record. (Normally, it only needs to match some part of the text in order to succeed.) For example, this prints the second field of each record that contains @samp{foo} anywhere: @example awk '/foo/ @{ print $2 @}' BBS-list @end example @cindex regular expression matching operators @cindex string-matching operators @cindex operators, string-matching @cindex operators, regular expression matching @cindex regexp search operators Regular expressions can also be used in comparison expressions. Then you can specify the string to match against; it need not be the entire current input record. These comparison expressions can be used as patterns or in @code{if} and @code{while} statements. @table @code @item @var{exp} ~ /@var{regexp}/ This is true if the expression @var{exp} (taken as a character string) is matched by @var{regexp}. The following example matches, or selects, all input records with the upper-case letter @samp{J} somewhere in the first field:@refill @example awk '$1 ~ /J/' inventory-shipped @end example So does this: @example awk '@{ if ($1 ~ /J/) print @}' inventory-shipped @end example @item @var{exp} !~ /@var{regexp}/ This is true if the expression @var{exp} (taken as a character string) is @emph{not} matched by @var{regexp}. The following example matches, or selects, all input records whose first field @emph{does not} contain the upper-case letter @samp{J}:@refill @example awk '$1 !~ /J/' inventory-shipped @end example @end table @cindex computed regular expressions @cindex regular expressions, computed @cindex dynamic regular expressions The right hand side of a @samp{~} or @samp{!~} operator need not be a constant regexp (i.e., a string of characters between slashes). It may be any expression. The expression is evaluated, and converted if necessary to a string; the contents of the string are used as the regexp. A regexp that is computed in this way is called a @dfn{dynamic regexp}. For example: @example identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+" $0 ~ identifier_regexp @end example @noindent sets @code{identifier_regexp} to a regexp that describes @code{awk} variable names, and tests if the input record matches this regexp. @node Regexp Operators, Case-sensitivity, Regexp Usage, Regexp @subsection Regular Expression Operators @cindex metacharacters @cindex regular expression metacharacters You can combine regular expressions with the following characters, called @dfn{regular expression operators}, or @dfn{metacharacters}, to increase the power and versatility of regular expressions. Here is a table of metacharacters. All characters not listed in the table stand for themselves. @table @code @item ^ This matches the beginning of the string or the beginning of a line within the string. For example: @example ^@@chapter @end example @noindent matches the @samp{@@chapter} at the beginning of a string, and can be used to identify chapter beginnings in Texinfo source files. @item $ This is similar to @samp{^}, but it matches only at the end of a string or the end of a line within the string. For example: @example p$ @end example @noindent matches a record that ends with a @samp{p}. @item . This matches any single character except a newline. For example: @example .P @end example @noindent matches any single character followed by a @samp{P} in a string. Using concatenation we can make regular expressions like @samp{U.A}, which matches any three-character sequence that begins with @samp{U} and ends with @samp{A}. @item [@dots{}] This is called a @dfn{character set}. It matches any one of the characters that are enclosed in the square brackets. For example: @example [MVX] @end example @noindent matches any of the characters @samp{M}, @samp{V}, or @samp{X} in a string.@refill Ranges of characters are indicated by using a hyphen between the beginning and ending characters, and enclosing the whole thing in brackets. For example:@refill @example [0-9] @end example @noindent matches any digit. To include the character @samp{\}, @samp{]}, @samp{-} or @samp{^} in a character set, put a @samp{\} in front of it. For example: @example [d\]] @end example @noindent matches either @samp{]}, or @samp{d}.@refill This treatment of @samp{\} is compatible with other @code{awk} implementations but incompatible with the proposed POSIX specification for @code{awk}. The current draft specifies the use of the same syntax used in @code{egrep}. We may change @code{gawk} to fit the standard, once we are sure it will no longer change. For the meanwhile, the @samp{-a} option specifies the traditional @code{awk} syntax described above (which is also the default), while the @samp{-e} option specifies @code{egrep} syntax. @xref{Options}. In @code{egrep} syntax, backslash is not syntactically special within square brackets. This means that special tricks have to be used to represent the characters @samp{]}, @samp{-} and @samp{^} as members of a character set. To match @samp{-}, write it as @samp{---}, which is a range containing only @samp{-}. You may also give @samp{-} as the first or last character in the set. To match @samp{^}, put it anywhere except as the first character of a set. To match a @samp{]}, make it the first character in the set. For example: @example []d^] @end example @noindent matches either @samp{]}, @samp{d} or @samp{^}.@refill @item [^ @dots{}] This is a @dfn{complemented character set}. The first character after the @samp{[} @emph{must} be a @samp{^}. It matches any characters @emph{except} those in the square brackets. For example: @example [^0-9] @end example @noindent matches any character that is not a digit. @item | This is the @dfn{alternation operator} and it is used to specify alternatives. For example: @example ^P|[0-9] @end example @noindent matches any string that matches either @samp{^P} or @samp{[0-9]}. This means it matches any string that contains a digit or starts with @samp{P}. The alternation applies to the largest possible regexps on either side. @item (@dots{}) Parentheses are used for grouping in regular expressions as in arithmetic. They can be used to concatenate regular expressions containing the alternation operator, @samp{|}. @item * This symbol means that the preceding regular expression is to be repeated as many times as possible to find a match. For example: @example ph* @end example @noindent applies the @samp{*} symbol to the preceding @samp{h} and looks for matches to one @samp{p} followed by any number of @samp{h}s. This will also match just @samp{p} if no @samp{h}s are present. The @samp{*} repeats the @emph{smallest} possible preceding expression. (Use parentheses if you wish to repeat a larger expression.) It finds as many repetitions as possible. For example: @example awk '/\(c[ad][ad]*r x\)/ @{ print @}' sample @end example @noindent prints every record in the input containing a string of the form @samp{(car x)}, @samp{(cdr x)}, @samp{(cadr x)}, and so on.@refill @item + This symbol is similar to @samp{*}, but the preceding expression must be matched at least once. This means that: @example wh+y @end example @noindent would match @samp{why} and @samp{whhy} but not @samp{wy}, whereas @samp{wh*y} would match all three of these strings. This is a simpler way of writing the last @samp{*} example: @example awk '/\(c[ad]+r x\)/ @{ print @}' sample @end example @item ? This symbol is similar to @samp{*}, but the preceding expression can be matched once or not at all. For example: @example fe?d @end example @noindent will match @samp{fed} or @samp{fd}, but nothing else.@refill @item \ This is used to suppress the special meaning of a character when matching. For example: @example \$ @end example @noindent matches the character @samp{$}. The escape sequences used for string constants (@pxref{Constants}) are valid in regular expressions as well; they are also introduced by a @samp{\}. @end table In regular expressions, the @samp{*}, @samp{+}, and @samp{?} operators have the highest precedence, followed by concatenation, and finally by @samp{|}. As in arithmetic, parentheses can change how operators are grouped.@refill @node Case-sensitivity,, Regexp Operators, Regexp @subsection Case-sensitivity in Matching Case is normally significant in regular expressions, both when matching ordinary characters (i.e., not metacharacters), and inside character sets. Thus a @samp{w} in a regular expression matches only a lower case @samp{w} and not an upper case @samp{W}. The simplest way to do a case-independent match is to use a character set: @samp{[Ww]}. However, this can be cumbersome if you need to use it often; and it can make the regular expressions harder for humans to read. There are two other alternatives that you might prefer. One way to do a case-insensitive match at a particular point in the program is to convert the data to a single case, using the @code{tolower} or @code{toupper} built-in string functions (which we haven't discussed yet; @pxref{String Functions}). For example: @example tolower($1) ~ /foo/ @{ @dots{} @} @end example @noindent converts the first field to lower case before matching against it. Another method is to set the variable @code{IGNORECASE} to a nonzero value (@pxref{Built-in Variables}). When @code{IGNORECASE} is not zero, @emph{all} regexp operations ignore case. Changing the value of @code{IGNORECASE} dynamically controls the case sensitivity of your program as it runs. Case is significant by default because @code{IGNORECASE} (like most variables) is initialized to zero. @example x = "aB" if (x ~ /ab/) @dots{} # this test will fail IGNORECASE = 1 if (x ~ /ab/) @dots{} # now it will succeed @end example You cannot generally use @code{IGNORECASE} to make certain rules case-insensitive and other rules case-sensitive, because there is no way to set @code{IGNORECASE} just for the pattern of a particular rule. To do this, you must use character sets or @code{tolower}. However, one thing you can do only with @code{IGNORECASE} is turn case-sensitivity on or off dynamically for all the rules at once. @code{IGNORECASE} can be set on the command line, or in a @code{BEGIN} rule. Setting @code{IGNORECASE} from the command line is a way to make a program case-insensitive without having to edit it. The value of @code{IGNORECASE} has no effect if @code{gawk} is in compatibility mode (@pxref{Command Line}). Case is always significant in compatibility mode. @node Comparison Patterns, Boolean Patterns, Regexp, Patterns @section Comparison Expressions as Patterns @cindex comparison expressions as patterns @cindex pattern, comparison expressions @cindex relational operators @cindex operators, relational @dfn{Comparison patterns} test relationships such as equality between two strings or numbers. They are a special case of expression patterns (@pxref{Expression Patterns}). They are written with @dfn{relational operators}, which are a superset of those in C. Here is a table of them: @table @code @item @var{x} < @var{y} True if @var{x} is less than @var{y}. @item @var{x} <= @var{y} True if @var{x} is less than or equal to @var{y}. @item @var{x} > @var{y} True if @var{x} is greater than @var{y}. @item @var{x} >= @var{y} True if @var{x} is greater than or equal to @var{y}. @item @var{x} == @var{y} True if @var{x} is equal to @var{y}. @item @var{x} != @var{y} True if @var{x} is not equal to @var{y}. @item @var{x} ~ @var{y} True if @var{x} matches the regular expression described by @var{y}. @item @var{x} !~ @var{y} True if @var{x} does not match the regular expression described by @var{y}. @end table The operands of a relational operator are compared as numbers if they are both numbers. Otherwise they are converted to, and compared as, strings (@pxref{Conversion}). Strings are compared by comparing the first character of each, then the second character of each, and so on, until there is a difference. If the two strings are equal until the shorter one runs out, the shorter one is considered to be less than the longer one. Thus, @code{"10"} is less than @code{"9"}. The left operand of the @samp{~} and @samp{!~} operators is a string. The right operand is either a constant regular expression enclosed in slashes (@code{/@var{regexp}/}), or any expression, whose string value is used as a dynamic regular expression (@pxref{Regexp Usage}). The following example prints the second field of each input record whose first field is precisely @samp{foo}. @example awk '$1 == "foo" @{ print $2 @}' BBS-list @end example @noindent Contrast this with the following regular expression match, which would accept any record with a first field that contains @samp{foo}: @example awk '$1 ~ "foo" @{ print $2 @}' BBS-list @end example @noindent or, equivalently, this one: @example awk '$1 ~ /foo/ @{ print $2 @}' BBS-list @end example @node Boolean Patterns, Expression Patterns, Comparison Patterns, Patterns @section Boolean Operators and Patterns @cindex patterns, boolean @cindex boolean patterns A @dfn{boolean pattern} is an expression which combines other patterns using the @dfn{boolean operators} ``or'' (@samp{||}), ``and'' (@samp{&&}), and ``not'' (@samp{!}). Whether the boolean pattern matches an input record depends on whether its subpatterns match. For example, the following command prints all records in the input file @file{BBS-list} that contain both @samp{2400} and @samp{foo}.@refill @example awk '/2400/ && /foo/' BBS-list @end example The following command prints all records in the input file @file{BBS-list} that contain @emph{either} @samp{2400} or @samp{foo}, or both.@refill @example awk '/2400/ || /foo/' BBS-list @end example The following command prints all records in the input file @file{BBS-list} that do @emph{not} contain the string @samp{foo}. @example awk '! /foo/' BBS-list @end example Note that boolean patterns are a special case of expression patterns (@pxref{Expression Patterns}); they are expressions that use the boolean operators. For complete information on the boolean operators, see @ref{Boolean Ops}. The subpatterns of a boolean pattern can be constant regular expressions, comparisons, or any other @code{gawk} expressions. Range patterns are not expressions, so they cannot appear inside boolean patterns. Likewise, the special patterns @code{BEGIN} and @code{END}, which never match any input record, are not expressions and cannot appear inside boolean patterns. @node Expression Patterns, Ranges, Boolean Patterns, Patterns @section Expressions as Patterns Any @code{awk} expression is valid also as a pattern in @code{gawk}. Then the pattern ``matches'' if the expression's value is nonzero (if a number) or nonnull (if a string). The expression is reevaluated each time the rule is tested against a new input record. If the expression uses fields such as @code{$1}, the value depends directly on the new input record's text; otherwise, it depends only on what has happened so far in the execution of the @code{awk} program, but that may still be useful. Comparison patterns are actually a special case of this. For example, the expression @code{$5 == "foo"} has the value 1 when the value of @code{$5} equals @code{"foo"}, and 0 otherwise; therefore, this expression as a pattern matches when the two values are equal. Boolean patterns are also special cases of expression patterns. A constant regexp as a pattern is also a special case of an expression pattern. @code{/foo/} as an expression has the value 1 if @samp{foo} appears in the current input record; thus, as a pattern, @code{/foo/} matches any record containing @samp{foo}. Other implementations of @code{awk} are less general than @code{gawk}: they allow comparison expressions, and boolean combinations thereof (optionally with parentheses), but not necessarily other kinds of expressions. @node Ranges, BEGIN/END, Expression Patterns, Patterns @section Specifying Record Ranges With Patterns @cindex range pattern @cindex patterns, range A @dfn{range pattern} is made of two patterns separated by a comma, of the form @code{@var{begpat}, @var{endpat}}. It matches ranges of consecutive input records. The first pattern @var{begpat} controls where the range begins, and the second one @var{endpat} controls where it ends. For example,@refill @example awk '$1 == "on", $1 == "off"' @end example @noindent prints every record between @samp{on}/@samp{off} pairs, inclusive. In more detail, a range pattern starts out by matching @var{begpat} against every input record; when a record matches @var{begpat}, the range pattern becomes @dfn{turned on}. The range pattern matches this record. As long as it stays turned on, it automatically matches every input record read. But meanwhile, it also matches @var{endpat} against every input record, and when that succeeds, the range pattern is turned off again for the following record. Now it goes back to checking @var{begpat} against each record. The record that turns on the range pattern and the one that turns it off both match the range pattern. If you don't want to operate on these records, you can write @code{if} statements in the rule's action to distinguish them. It is possible for a pattern to be turned both on and off by the same record, if both conditions are satisfied by that record. Then the action is executed for just that record. @node BEGIN/END,, Ranges, Patterns @section @code{BEGIN} and @code{END} Special Patterns @cindex @code{BEGIN} special pattern @cindex patterns, @code{BEGIN} @cindex @code{END} special pattern @cindex patterns, @code{END} @code{BEGIN} and @code{END} are special patterns. They are not used to match input records. Rather, they are used for supplying start-up or clean-up information to your @code{awk} script. A @code{BEGIN} rule is executed, once, before the first input record has been read. An @code{END} rule is executed, once, after all the input has been read. For example:@refill @group @example awk 'BEGIN @{ print "Analysis of `foo'" @} /foo/ @{ ++foobar @} END @{ print "`foo' appears " foobar " times." @}' BBS-list @end example @end group This program finds out how many times the string @samp{foo} appears in the input file @file{BBS-list}. The @code{BEGIN} rule prints a title for the report. There is no need to use the @code{BEGIN} rule to initialize the counter @code{foobar} to zero, as @code{awk} does this for us automatically (@pxref{Variables}). The second rule increments the variable @code{foobar} every time a record containing the pattern @samp{foo} is read. The @code{END} rule prints the value of @code{foobar} at the end of the run.@refill The special patterns @code{BEGIN} and @code{END} cannot be used in ranges or with boolean operators. An @code{awk} program may have multiple @code{BEGIN} and/or @code{END} rules. They are executed in the order they appear, all the @code{BEGIN} rules at start-up and all the @code{END} rules at termination. Multiple @code{BEGIN} and @code{END} sections are useful for writing library functions, since each library can have its own @code{BEGIN} or @code{END} rule to do its own initialization and/or cleanup. Note that the order in which library functions are named on the command line controls the order in which their @code{BEGIN} and @code{END} rules are executed. Therefore you have to be careful to write such rules in library files so that it doesn't matter what order they are executed in. @xref{Command Line}, for more information on using library functions. If an @code{awk} program only has a @code{BEGIN} rule, and no other rules, then the program exits after the @code{BEGIN} rule has been run. (Older versions of @code{awk} used to keep reading and ignoring input until end of file was seen.) However, if an @code{END} rule exists as well, then the input will be read, even if there are no other rules in the program. This is necessary in case the @code{END} rule checks the @code{NR} variable. @code{BEGIN} and @code{END} rules must have actions; there is no default action for these rules since there is no current record when they run. @node Actions, Expressions, Patterns, Top @chapter Actions: Overview @cindex action, definition of @cindex curly braces @cindex action, curly braces @cindex action, separating statements An @code{awk} @dfn{program} or @dfn{script} consists of a series of @dfn{rules} and function definitions, interspersed. (Functions are described later; see @ref{User-defined}.) A rule contains a pattern and an @dfn{action}, either of which may be omitted. The purpose of the action is to tell @code{awk} what to do once a match for the pattern is found. Thus, the entire program looks somewhat like this: @example @r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]} @r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]} @dots{} function @var{name} (@var{args}) @{ @dots{} @} @dots{} @end example An action consists of one or more @code{awk} @dfn{statements}, enclosed in curly braces (@samp{@{} and @samp{@}}). Each statement specifies one thing to be done. The statements are separated by newlines or semicolons. The curly braces around an action must be used even if the action contains only one statement, or even if it contains no statements at all. However, if you omit the action entirely, omit the curly braces as well. (An omitted action is equivalent to @samp{@{ print $0 @}}.) Here are the kinds of statement supported in @code{awk}: @itemize @bullet @item Expressions, which can call functions or assign values to variables (@pxref{Expressions}). Executing this kind of statement simply computes the value of the expression and then ignores it. This is useful when the expression has side effects (@pxref{Assignment Ops}). @item Control statements, which specify the control flow of @code{awk} programs. The @code{awk} language gives you C-like constructs (@code{if}, @code{for}, @code{while}, and so on) as well as a few special ones (@pxref{Statements}).@refill @item Compound statements, which consist of one or more statements enclosed in curly braces. A compound statement is used in order to put several statements together in the body of an @code{if}, @code{while}, @code{do} or @code{for} statement. @item Input control, using the @code{getline} function (@pxref{Getline}), and the @code{next} statement (@pxref{Next Statement}). @item Output statements, @code{print} and @code{printf}. @xref{Printing}. @item Deletion statements, for deleting array elements. @xref{Delete}. @end itemize @iftex The next two chapters cover in detail expressions and control statements, respectively. We go on to treat arrays, and built-in functions, both of which are used in expressions. Then we proceed to discuss how to define your own functions. @end iftex @node Expressions, Statements, Actions, Top @chapter Actions: Expressions @cindex expression Expressions are the basic building block of @code{awk} actions. An expression evaluates to a value, which you can print, test, store in a variable or pass to a function. But, beyond that, an expression can assign a new value to a variable or a field, with an assignment operator. An expression can serve as a statement on its own. Most other kinds of statement contain one or more expressions which specify data to be operated on. As in other languages, expressions in @code{awk} include variables, array references, constants, and function calls, as well as combinations of these with various operators. @menu * Constants:: String, numeric, and regexp constants. * Variables:: Variables give names to values for later use. * Arithmetic Ops:: Arithmetic operations (@samp{+}, @samp{-}, etc.) * Concatenation:: Concatenating strings. * Comparison Ops:: Comparison of numbers and strings with @samp{<}, etc. * Boolean Ops:: Combining comparison expressions using boolean operators @samp{||} (``or''), @samp{&&} (``and'') and @samp{!} (``not''). * Assignment Ops:: Changing the value of a variable or a field. * Increment Ops:: Incrementing the numeric value of a variable. * Conversion:: The conversion of strings to numbers and vice versa. * Conditional Exp:: Conditional expressions select between two subexpressions under control of a third subexpression. * Function Calls:: A function call is an expression. * Precedence:: How various operators nest. @end menu @node Constants, Variables, Expressions, Expressions @section Constant Expressions @cindex constants, types of @cindex string constants The simplest type of expression is the @dfn{constant}, which always has the same value. There are three types of constant: numeric constants, string constants, and regular expression constants. @cindex numeric constant @cindex numeric value A @dfn{numeric constant} stands for a number. This number can be an integer, a decimal fraction, or a number in scientific (exponential) notation. Note that all numeric values are represented within @code{awk} in double-precision floating point. Here are some examples of numeric constants, which all have the same value: @example 105 1.05e+2 1050e-1 @end example A string constant consists of a sequence of characters enclosed in double-quote marks. For example: @example "parrot" @end example @noindent @c @cindex differences between @code{gawk} and @code{awk} represents the string whose contents are @samp{parrot}. Strings in @code{gawk} can be of any length and they can contain all the possible 8-bit ASCII characters including ASCII NUL. Other @code{awk} implementations may have difficulty with some character codes.@refill @cindex escape sequence notation Some characters cannot be included literally in a string constant. You represent them instead with @dfn{escape sequences}, which are character sequences beginning with a backslash (@samp{\}). One use of an escape sequence is to include a double-quote character in a string constant. Since a plain double-quote would end the string, you must use @samp{\"} to represent a single double-quote character as a part of the string. Backslash itself is another character that can't be included normally; you write @samp{\\} to put one backslash in the string. Thus, the string whose contents are the two characters @samp{"\} must be written @code{"\"\\"}. Another use of backslash is to represent unprintable characters such as newline. While there is nothing to stop you from writing most of these characters directly in a string constant, they may look ugly. Here is a table of all the escape sequences used in @code{awk}: @table @code @item \\ Represents a literal backslash, @samp{\}. @item \a Represents the ``alert'' character, control-g, ASCII code 7. @item \b Represents a backspace, control-h, ASCII code 8. @item \f Represents a formfeed, control-l, ASCII code 12. @item \n Represents a newline, control-j, ASCII code 10. @item \r Represents a carriage return, control-m, ASCII code 13. @item \t Represents a horizontal tab, control-i, ASCII code 9. @item \v Represents a vertical tab, control-k, ASCII code 11. @item \@var{nnn} Represents the octal value @var{nnn}, where @var{nnn} are one to three digits between 0 and 7. For example, the code for the ASCII ESC (escape) character is @samp{\033}.@refill @item \x@var{hh@dots{}} Represents the hexadecimal value @var{hh}, where @var{hh} are hexadecimal digits (@samp{0} through @samp{9} and either @samp{A} through @samp{F} or @samp{a} through @samp{f}). Like the same construct in ANSI C, the escape sequence continues until the first non-hexadecimal digit is seen. However, using more than two hexadecimal digits produces undefined results.@refill @end table A constant regexp is a regular expression description enclosed in slashes, such as @code{/^beginning and end$/}. Most regexps used in @code{awk} programs are constant, but the @samp{~} and @samp{!~} operators can also match computed or ``dynamic'' regexps (@pxref{Regexp Usage}). Constant regexps are useful only with the @samp{~} and @samp{!~} operators; you cannot assign them to variables or print them. They are not truly expressions in the usual sense. @node Variables, Arithmetic Ops, Constants, Expressions @section Variables @cindex variables, user-defined @cindex user-defined variables Variables let you give names to values and refer to them later. You have already seen variables in many of the examples. The name of a variable must be a sequence of letters, digits and underscores, but it may not begin with a digit. Case is significant in variable names; @code{a} and @code{A} are distinct variables. A variable name is a valid expression by itself; it represents the variable's current value. Variables are given new values with @dfn{assignment operators} and @dfn{increment operators}. @xref{Assignment Ops}. A few variables have special built-in meanings, such as @code{FS}, the field separator, and @code{NF}, the number of fields in the current input record. @xref{Built-in Variables}, for a list of them. These built-in variables can be used and assigned just like all other variables, but their values are also used or changed automatically by @code{awk}. Each built-in variable's name is made entirely of upper case letters. Variables in @code{awk} can be assigned either numeric values or string values. By default, variables are initialized to the null string, which is effectively zero if converted to a number. So there is no need to ``initialize'' each variable explicitly in @code{awk}, the way you would need to do in C or most other traditional programming languages. @menu * Assignment Options:: Setting variables on the command line and a summary of command line syntax. This is an advanced method of input. @end menu @node Assignment Options,, Variables, Variables @subsection Assigning Variables on the Command Line You can set any @code{awk} variable by including a @dfn{variable assignment} among the arguments on the command line when you invoke @code{awk} (@pxref{Command Line}). Such an assignment has this form: @example @var{variable}=@var{text} @end example @noindent With it, you can set a variable either at the beginning of the @code{awk} run or in between input files. If you precede the assignment with the @samp{-v} option, like this: @example -v @var{variable}=@var{text} @end example @noindent then the variable is set at the very beginning, before even the @code{BEGIN} rules are run. The @samp{-v} option and its assignment must precede all the file name arguments. Otherwise, the variable assignment is performed at a time determined by its position among the input file arguments: after the processing of the preceding input file argument. For example: @example awk '@{ print $n @}' n=4 inventory-shipped n=2 BBS-list @end example @noindent prints the value of field number @code{n} for all input records. Before the first file is read, the command line sets the variable @code{n} equal to 4. This causes the fourth field to be printed in lines from the file @file{inventory-shipped}. After the first file has finished, but before the second file is started, @code{n} is set to 2, so that the second field is printed in lines from @file{BBS-list}. Command line arguments are made available for explicit examination by the @code{awk} program in an array named @code{ARGV} (@pxref{Built-in Variables}). @node Arithmetic Ops, Concatenation, Variables, Expressions @section Arithmetic Operators @cindex arithmetic operators @cindex operators, arithmetic @cindex addition @cindex subtraction @cindex multiplication @cindex division @cindex remainder @cindex quotient @cindex exponentiation The @code{awk} language uses the common arithmetic operators when evaluating expressions. All of these arithmetic operators follow normal precedence rules, and work as you would expect them to. This example divides field three by field four, adds field two, stores the result into field one, and prints the resulting altered input record: @example awk '@{ $1 = $2 + $3 / $4; print @}' inventory-shipped @end example The arithmetic operators in @code{awk} are: @table @code @item @var{x} + @var{y} Addition. @item @var{x} - @var{y} Subtraction. @item - @var{x} Negation. @item @var{x} * @var{y} Multiplication. @item @var{x} / @var{y} Division. Since all numbers in @code{awk} are double-precision floating point, the result is not rounded to an integer: @code{3 / 4} has the value 0.75. @item @var{x} % @var{y} @c @cindex differences between @code{gawk} and @code{awk} Remainder. The quotient is rounded toward zero to an integer, multiplied by @var{y} and this result is subtracted from @var{x}. This operation is sometimes known as ``trunc-mod''. The following relation always holds: @example b * int(a / b) + (a % b) == a @end example One undesirable effect of this definition of remainder is that @code{@var{x} % @var{y}} is negative if @var{x} is negative. Thus, @example -17 % 8 = -1 @end example In other @code{awk} implementations, the signedness of the remainder may be machine dependent. @item @var{x} ^ @var{y} @itemx @var{x} ** @var{y} Exponentiation: @var{x} raised to the @var{y} power. @code{2 ^ 3} has the value 8. The character sequence @samp{**} is equivalent to @samp{^}. @end table @node Concatenation, Comparison Ops, Arithmetic Ops, Expressions @section String Concatenation @cindex string operators @cindex operators, string @cindex concatenation There is only one string operation: concatenation. It does not have a specific operator to represent it. Instead, concatenation is performed by writing expressions next to one another, with no operator. For example: @example awk '@{ print "Field number one: " $1 @}' BBS-list @end example @noindent produces, for the first record in @file{BBS-list}: @example Field number one: aardvark @end example Without the space in the string constant after the @samp{:}, the line would run together. For example: @example awk '@{ print "Field number one:" $1 @}' BBS-list @end example @noindent produces, for the first record in @file{BBS-list}: @example Field number one:aardvark @end example Since string concatenation does not have an explicit operator, it is often necessary to insure that it happens where you want it to by enclosing the items to be concatenated in parentheses. For example, the following code fragment does not concatenate @code{file} and @code{name} as you might expect: @example file = "file" name = "name" print "something meaningful" > file name @end example @noindent It is necessary to use the following: @example print "something meaningful" > (file name) @end example We recommend you use parentheses around concatenation in all but the most common contexts (such as in the right-hand operand of @samp{=}). @ignore @code{gawk} actually now allows a concatenation on the right hand side of a @code{>} redirection, but other @code{awk}s don't. So for now we won't mention that fact. @end ignore @node Comparison Ops, Boolean Ops, Concatenation, Expressions @section Comparison Expressions @cindex comparison expressions @cindex expressions, comparison @cindex relational operators @cindex operators, relational @cindex regexp operators @dfn{Comparison expressions} compare strings or numbers for relationships such as equality. They are written using @dfn{relational operators}, which are a superset of those in C. Here is a table of them: @table @code @item @var{x} < @var{y} True if @var{x} is less than @var{y}. @item @var{x} <= @var{y} True if @var{x} is less than or equal to @var{y}. @item @var{x} > @var{y} True if @var{x} is greater than @var{y}. @item @var{x} >= @var{y} True if @var{x} is greater than or equal to @var{y}. @item @var{x} == @var{y} True if @var{x} is equal to @var{y}. @item @var{x} != @var{y} True if @var{x} is not equal to @var{y}. @item @var{x} ~ @var{y} True if the string @var{x} matches the regexp denoted by @var{y}. @item @var{x} !~ @var{y} True if the string @var{x} does not match the regexp denoted by @var{y}. @item @var{subscript} in @var{array} True if array @var{array} has an element with the subscript @var{subscript}. @end table Comparison expressions have the value 1 if true and 0 if false. The operands of a relational operator are compared as numbers if they are both numbers. Otherwise they are converted to, and compared as, strings (@pxref{Conversion}). Strings are compared by comparing the first character of each, then the second character of each, and so on. Thus, @code{"10"} is less than @code{"9"}. For example, @example $1 == "foo" @end example @noindent has the value of 1, or is true, if the first field of the current input record is precisely @samp{foo}. By contrast, @example $1 ~ /foo/ @end example @noindent has the value 1 if the first field contains @samp{foo}. The right hand operand of the @samp{~} and @samp{!~} operators may be either a constant regexp (@code{/@dots{}/}), or it may be an ordinary expression, in which case the value of the expression as a string is a dynamic regexp (@pxref{Regexp Usage}). @cindex regexp as expression In very recent implementations of @code{awk}, a constant regular expression in slashes by itself is also an expression. The regexp @code{/@var{regexp}/} is an abbreviation for this comparison expression: @example $0 ~ /@var{regexp}/ @end example In some contexts it may be necessary to write parentheses around the regexp to avoid confusing the @code{gawk} parser. For example, @code{(/x/ - /y/) > threshold} is not allowed, but @code{((/x/) - (/y/)) > threshold} parses properly. One special place where @code{/foo/} is @emph{not} an abbreviation for @code{$0 ~ /foo/} is when it is the right-hand operand of @samp{~} or @samp{!~}! @node Boolean Ops, Assignment Ops, Comparison Ops, Expressions @section Boolean Expressions @cindex expressions, boolean @cindex boolean expressions @cindex operators, boolean @cindex boolean operators @cindex logical operations @cindex and operator @cindex or operator @cindex not operator A @dfn{boolean expression} is combination of comparison expressions or matching expressions, using the @dfn{boolean operators} ``or'' (@samp{||}), ``and'' (@samp{&&}), and ``not'' (@samp{!}), along with parentheses to control nesting. The truth of the boolean expression is computed by combining the truth values of the component expressions. Boolean expressions can be used wherever comparison and matching expressions can be used. They can be used in @code{if} and @code{while} statements. They have numeric values (1 if true, 0 if false), which come into place if the result of the boolean expression is stored in a variable, or used in arithmetic. In addition, every boolean expression is also a valid boolean pattern, so you can use it as a pattern to control the execution of rules. Here are descriptions of the three boolean operators, with an example of each. It may be instructive to compare these examples with the analogous examples of boolean patterns (@pxref{Boolean Patterns}), which use the same boolean operators in patterns instead of expressions. @table @code @item @var{boolean1} && @var{boolean2} True if both @var{boolean1} and @var{boolean2} are true. For example, the following statement prints the current input record if it contains both @samp{2400} and @samp{foo}.@refill @example if ($0 ~ /2400/ && $0 ~ /foo/) print @end example The subexpression @var{boolean2} is evaluated only if @var{boolean1} is true. This can make a difference when @var{boolean2} contains expressions that have side effects: in the case of @code{$0 ~ /foo/ && ($2 == bar++)}, the variable @code{bar} is not incremented if there is no @samp{foo} in the record. @item @var{boolean1} || @var{boolean2} True if at least one of @var{boolean1} and @var{boolean2} is true. For example, the following command prints all records in the input file @file{BBS-list} that contain @emph{either} @samp{2400} or @samp{foo}, or both.@refill @example awk '@{ if ($0 ~ /2400/ || $0 ~ /foo/) print @}' BBS-list @end example The subexpression @var{boolean2} is evaluated only if @var{boolean1} is false. This can make a difference when @var{boolean2} contains expressions that have side effects. @item !@var{boolean} True if @var{boolean} is false. For example, the following program prints all records in the input file @file{BBS-list} that do @emph{not} contain the string @samp{foo}. @example awk '@{ if (! ($0 ~ /foo/)) print @}' BBS-list @end example @end table @node Assignment Ops, Increment Ops, Boolean Ops, Expressions @section Assignment Expressions @cindex assignment operators @cindex operators, assignment @cindex expressions, assignment An @dfn{assignment} is an expression that stores a new value into a variable. For example, let's assign the value 1 to the variable @code{z}:@refill @example z = 1 @end example After this expression is executed, the variable @code{z} has the value 1. Whatever old value @code{z} had before the assignment is forgotten. Assignments can store string values also. For example, this would store the value @code{"this food is good"} in the variable @code{message}: @example thing = "food" predicate = "good" message = "this " thing " is " predicate @end example @noindent (This also illustrates concatenation of strings.) The @samp{=} sign is called an @dfn{assignment operator}. It is the simplest assignment operator because the value of the right-hand operand is stored unchanged. @cindex side effect Most operators (addition, concatenation, and so on) have no effect except to compute a value. If you ignore the value, you might as well not use the operator. An assignment operator is different; it does produce a value, but even if you ignore the value, the assignment still makes itself felt through the alteration of the variable. We call this a @dfn{side effect}. @cindex lvalue The left-hand operand of an assignment need not be a variable (@pxref{Variables}); it can also be a field (@pxref{Changing Fields}) or an array element (@pxref{Arrays}). These are all called @dfn{lvalues}, which means they can appear on the left-hand side of an assignment operator. The right-hand operand may be any expression; it produces the new value which the assignment stores in the specified variable, field or array element. It is important to note that variables do @emph{not} have permanent types. The type of a variable is simply the type of whatever value it happens to hold at the moment. In the following program fragment, the variable @code{foo} has a numeric value at first, and a string value later on: @example foo = 1 print foo foo = "bar" print foo @end example @noindent When the second assignment gives @code{foo} a string value, the fact that it previously had a numeric value is forgotten. An assignment is an expression, so it has a value: the same value that is assigned. Thus, @code{z = 1} as an expression has the value 1. One consequence of this is that you can write multiple assignments together: @example x = y = z = 0 @end example @noindent stores the value 0 in all three variables. It does this because the value of @code{z = 0}, which is 0, is stored into @code{y}, and then the value of @code{y = z = 0}, which is 0, is stored into @code{x}. You can use an assignment anywhere an expression is called for. For example, it is valid to write @code{x != (y = 1)} to set @code{y} to 1 and then test whether @code{x} equals 1. But this style tends to make programs hard to read; except in a one-shot program, you should rewrite it to get rid of such nesting of assignments. This is never very hard. Aside from @samp{=}, there are several other assignment operators that do arithmetic with the old value of the variable. For example, the operator @samp{+=} computes a new value by adding the right-hand value to the old value of the variable. Thus, the following assignment adds 5 to the value of @code{foo}: @example foo += 5 @end example @noindent This is precisely equivalent to the following: @example foo = foo + 5 @end example @noindent Use whichever one makes the meaning of your program clearer. Here is a table of the arithmetic assignment operators. In each case, the right-hand operand is an expression whose value is converted to a number. @table @code @item @var{lvalue} += @var{increment} Adds @var{increment} to the value of @var{lvalue} to make the new value of @var{lvalue}. @item @var{lvalue} -= @var{decrement} Subtracts @var{decrement} from the value of @var{lvalue}. @item @var{lvalue} *= @var{coefficient} Multiplies the value of @var{lvalue} by @var{coefficient}. @item @var{lvalue} /= @var{quotient} Divides the value of @var{lvalue} by @var{quotient}. @item @var{lvalue} %= @var{modulus} Sets @var{lvalue} to its remainder by @var{modulus}. @item @var{lvalue} ^= @var{power} @itemx @var{lvalue} **= @var{power} Raises @var{lvalue} to the power @var{power}. @end table @node Increment Ops, Conversion, Assignment Ops, Expressions @section Increment Operators @cindex increment operators @cindex operators, increment @dfn{Increment operators} increase or decrease the value of a variable by 1. You could do the same thing with an assignment operator, so the increment operators add no power to the @code{awk} language; but they are convenient abbreviations for something very common. The operator to add 1 is written @samp{++}. It can be used to increment a variable either before or after taking its value. To pre-increment a variable @var{v}, write @code{++@var{v}}. This adds 1 to the value of @var{v} and that new value is also the value of this expression. The assignment expression @code{@var{v} += 1} is completely equivalent. Writing the @samp{++} after the variable specifies post-increment. This increments the variable value just the same; the difference is that the value of the increment expression itself is the variable's @emph{old} value. Thus, if @code{foo} has value 4, then the expression @code{foo++} has the value 4, but it changes the value of @code{foo} to 5. The post-increment @code{foo++} is nearly equivalent to writing @code{(foo += 1) - 1}. It is not perfectly equivalent because all numbers in @code{awk} are floating point: in floating point, @code{foo + 1 - 1} does not necessarily equal @code{foo}. But the difference is minute as long as you stick to numbers that are fairly small (less than a trillion). Any lvalue can be incremented. Fields and array elements are incremented just like variables. The decrement operator @samp{--} works just like @samp{++} except that it subtracts 1 instead of adding. Like @samp{++}, it can be used before the lvalue to pre-decrement or after it to post-decrement. Here is a summary of increment and decrement expressions. @table @code @item ++@var{lvalue} This expression increments @var{lvalue} and the new value becomes the value of this expression. @item @var{lvalue}++ This expression causes the contents of @var{lvalue} to be incremented. The value of the expression is the @emph{old} value of @var{lvalue}. @item --@var{lvalue} Like @code{++@var{lvalue}}, but instead of adding, it subtracts. It decrements @var{lvalue} and delivers the value that results. @item @var{lvalue}-- Like @code{@var{lvalue}++}, but instead of adding, it subtracts. It decrements @var{lvalue}. The value of the expression is the @emph{old} value of @var{lvalue}. @end table @node Conversion, Conditional Exp, Increment Ops, Expressions @section Conversion of Strings and Numbers @cindex conversion of strings and numbers Strings are converted to numbers, and numbers to strings, if the context of the @code{awk} program demands it. For example, if the value of either @code{foo} or @code{bar} in the expression @code{foo + bar} happens to be a string, it is converted to a number before the addition is performed. If numeric values appear in string concatenation, they are converted to strings. Consider this:@refill @example two = 2; three = 3 print (two three) + 4 @end example @noindent This eventually prints the (numeric) value 27. The numeric values of the variables @code{two} and @code{three} are converted to strings and concatenated together, and the resulting string is converted back to the number 23, to which 4 is then added. If, for some reason, you need to force a number to be converted to a string, concatenate the null string with that number. To force a string to be converted to a number, add zero to that string. Strings are converted to numbers by interpreting them as numerals: @code{"2.5"} converts to 2.5, and @code{"1e3"} converts to 1000. Strings that can't be interpreted as valid numbers are converted to zero. @vindex OFMT The exact manner in which numbers are converted into strings is controlled by the @code{awk} built-in variable @code{OFMT} (@pxref{Built-in Variables}). Numbers are converted using a special version of the @code{sprintf} function (@pxref{Built-in}) with @code{OFMT} as the format specifier.@refill @code{OFMT}'s default value is @code{"%.6g"}, which prints a value with at least six significant digits. For some applications you will want to change it to specify more precision. Double precision on most modern machines gives you 16 or 17 decimal digits of precision. Strange results can happen if you set @code{OFMT} to a string that doesn't tell @code{sprintf} how to format floating point numbers in a useful way. For example, if you forget the @samp{%} in the format, all numbers will be converted to the same constant string.@refill @node Conditional Exp, Function Calls, Conversion, Expressions @section Conditional Expressions @cindex conditional expression @cindex expression, conditional A @dfn{conditional expression} is a special kind of expression with three operands. It allows you to use one expression's value to select one of two other expressions. The conditional expression looks the same as in the C language: @example @var{selector} ? @var{if-true-exp} : @var{if-false-exp} @end example @noindent There are three subexpressions. The first, @var{selector}, is always computed first. If it is ``true'' (not zero) then @var{if-true-exp} is computed next and its value becomes the value of the whole expression. Otherwise, @var{if-false-exp} is computed next and its value becomes the value of the whole expression. For example, this expression produces the absolute value of @code{x}: @example x > 0 ? x : -x @end example Each time the conditional expression is computed, exactly one of @var{if-true-exp} and @var{if-false-exp} is computed; the other is ignored. This is important when the expressions contain side effects. For example, this conditional expression examines element @code{i} of either array @code{a} or array @code{b}, and increments @code{i}. @example x == y ? a[i++] : b[i++] @end example @noindent This is guaranteed to increment @code{i} exactly once, because each time one or the other of the two increment expressions is executed, and the other is not. @node Function Calls, Precedence, Conditional Exp, Expressions @section Function Calls @cindex function call @cindex calling a function A @dfn{function} is a name for a particular calculation. Because it has a name, you can ask for it by name at any point in the program. For example, the function @code{sqrt} computes the square root of a number. A fixed set of functions are @dfn{built in}, which means they are available in every @code{awk} program. The @code{sqrt} function is one of these. @xref{Built-in}, for a list of built-in functions and their descriptions. In addition, you can define your own functions in the program for use elsewhere in the same program. @xref{User-defined}, for how to do this. @cindex arguments in function call The way to use a function is with a @dfn{function call} expression, which consists of the function name followed by a list of @dfn{arguments} in parentheses. The arguments are expressions which give the raw materials for the calculation that the function will do. When there is more than one argument, they are separated by commas. If there are no arguments, write just @samp{()} after the function name. Here are some examples: @example sqrt(x**2 + y**2) # @r{One argument} atan2(y, x) # @r{Two arguments} rand() # @r{No arguments} @end example @strong{Do not put any space between the function name and the open-parenthesis!} A user-defined function name looks just like the name of a variable, and space would make the expression look like concatenation of a variable with an expression inside parentheses. Space before the parenthesis is harmless with built-in functions, but it is best not to get into the habit of using space, lest you do likewise for a user-defined function one day by mistake. Each function expects a particular number of arguments. For example, the @code{sqrt} function must be called with a single argument, the number to take the square root of: @example sqrt(@var{argument}) @end example Some of the built-in functions allow you to omit the final argument. If you do so, they use a reasonable default. @xref{Built-in}, for full details. If arguments are omitted in calls to user-defined functions, then those arguments are treated as local variables, initialized to the null string (@pxref{User-defined}). Like every other expression, the function call has a value, which is computed by the function based on the arguments you give it. In this example, the value of @code{sqrt(@var{argument})} is the square root of the argument. A function can also have side effects, such as assigning the values of certain variables or doing I/O. Here is a command to read numbers, one number per line, and print the square root of each one: @example awk '@{ print "The square root of", $1, "is", sqrt($1) @}' @end example @node Precedence,, Function Calls, Expressions @section Operator Precedence: How Operators Nest @cindex precedence @cindex operator precedence @dfn{Operator precedence} determines how operators are grouped, when different operators appear close by in one expression. For example, @samp{*} has higher precedence than @samp{+}; thus, @code{a + b * c} means to multiply @code{b} and @code{c}, and then add @code{a} to the product. You can overrule the precedence of the operators by writing parentheses yourself. You can think of the precedence rules as saying where the parentheses are assumed if you do not write parentheses yourself. In fact, it is wise always to use parentheses whenever you have an unusual combination of operators, because other people who read the program may not remember what the precedence is in this case. You might forget, too; then you could make a mistake. Explicit parentheses will prevent any such mistake. When operators of equal precedence are used together, the leftmost operator groups first, except for the assignment, conditional and and exponentiation operators, which group in the opposite order. Thus, @code{a - b + c} groups as @code{(a - b) + c}; @code{a = b = c} groups as @code{a = (b = c)}. The precedence of prefix unary operators does not matter as long as only unary operators are involved, because there is only one way to parse them---innermost first. Thus, @code{$++i} means @code{$(++i)} and @code{++$x} means @code{++($x)}. However, when another operator follows the operand, then the precedence of the unary operators can matter. Thus, @code{$x**2} means @code{($x)**2}, but @code{-x**2} means @code{-(x**2)}, because @samp{-} has lower precedence than @samp{**} while @samp{$} has higher precedence. Here is a table of the operators of @code{awk}, in order of increasing precedence: @table @asis @item assignment @samp{=}, @samp{+=}, @samp{-=}, @samp{*=}, @samp{/=}, @samp{%=}, @samp{^=}, @samp{**=}. These operators group right-to-left. @item conditional @samp{?:}. These operators group right-to-left. @item logical ``or''. @samp{||}. @item logical ``and''. @samp{&&}. @item array membership @code{in}. @item matching @samp{~}, @samp{!~}. @item relational, and redirection The relational operators and the redirections have the same precedence level. Characters such as @samp{>} serve both as relationals and as redirections; the context distinguishes between the two meanings. The relational operators are @samp{<}, @samp{<=}, @samp{==}, @samp{!=}, @samp{>=} and @samp{>}. The I/O redirection operators are @samp{<}, @samp{>}, @samp{>>} and @samp{|}. Note that I/O redirection operators in @code{print} and @code{printf} statements belong to the statement level, not to expressions. The redirection does not produce an expression which could be the operand of another operator. As a result, it does not make sense to use a redirection operator near another operator of lower precedence, without parentheses. Such combinations, for example @samp{print foo > a ? b : c}, result in syntax errors. @item concatentation No special token is used to indicate concatenation. The operands are simply written side by side. @c This is supposedly being fixed @ignore Concatenation has the same precedence as relational and redirection operators. These operators nest left to right. Thus, @code{4 5 > 6} concatenates first, yielding 1, while @code{6 < 4 5} compares first, and yields @code{"05"}. @end ignore @item add, subtract @samp{+}, @samp{-}. @item multiply, divide, mod @samp{*}, @samp{/}, @samp{%}. @item unary plus, minus, ``not'' @samp{+}, @samp{-}, @samp{!}. @item exponentiation @samp{^}, @samp{**}. These operators group right-to-left. @item increment, decrement @samp{++}, @samp{--}. @item field @samp{$}. @end table @node Statements, Arrays, Expressions, Top @chapter Actions: Control Statements @cindex control statement @dfn{Control statements} such as @code{if}, @code{while}, and so on control the flow of execution in @code{awk} programs. Most of the control statements in @code{awk} are patterned on similar statements in C. All the control statements start with special keywords such as @code{if} and @code{while}, to distinguish them from simple expressions. Many control statements contain other statements; for example, the @code{if} statement contains another statement which may or may not be executed. The contained statement is called the @dfn{body}. If you want to include more than one statement in the body, group them into a single compound statement with curly braces, separating them with newlines or semicolons. @menu * If Statement:: Conditionally execute some @code{awk} statements. * While Statement:: Loop until some condition is satisfied. * Do Statement:: Do specified action while looping until some condition is satisfied. * For Statement:: Another looping statement, that provides initialization and increment clauses. * Break Statement:: Immediately exit the innermost enclosing loop. * Continue Statement:: Skip to the end of the innermost enclosing loop. * Next Statement:: Stop processing the current input record. * Exit Statement:: Stop execution of @code{awk}. @end menu @node If Statement, While Statement, Statements, Statements @section The @code{if} Statement @cindex @code{if} statement The @code{if}-@code{else} statement is @code{awk}'s decision-making statement. It looks like this:@refill @example if (@var{condition}) @var{then-body} @r{[}else @var{else-body}@r{]} @end example @noindent Here @var{condition} is an expression that controls what the rest of the statement will do. If @var{condition} is true, @var{then-body} is executed; otherwise, @var{else-body} is executed (assuming that the @code{else} clause is present). The @code{else} part of the statement is optional. The condition is considered false if its value is zero or the null string, true otherwise.@refill Here is an example: @example if (x % 2 == 0) print "x is even" else print "x is odd" @end example In this example, if the expression @code{x % 2 == 0} is true (that is, the value of @code{x} is divisible by 2), then the first @code{print} statement is executed, otherwise the second @code{print} statement is performed.@refill If the @code{else} appears on the same line as @var{then-body}, and @var{then-body} is not a compound statement (i.e., not surrounded by curly braces), then a semicolon must separate @var{then-body} from @code{else}. To illustrate this, let's rewrite the previous example: @group @example awk '@{ if (x % 2 == 0) print "x is even"; else print "x is odd" @}' @end example @end group @noindent If you forget the @samp{;}, @code{awk} won't be able to parse the statement, and you will get a syntax error. We would not actually write this example this way, because a human reader might fail to see the @code{else} if it were not the first thing on its line. @node While Statement, Do Statement, If Statement, Statements @section The @code{while} Statement @cindex @code{while} statement @cindex loop @cindex body of a loop In programming, a @dfn{loop} means a part of a program that is (or at least can be) executed two or more times in succession. The @code{while} statement is the simplest looping statement in @code{awk}. It repeatedly executes a statement as long as a condition is true. It looks like this: @example while (@var{condition}) @var{body} @end example @noindent Here @var{body} is a statement that we call the @dfn{body} of the loop, and @var{condition} is an expression that controls how long the loop keeps running. The first thing the @code{while} statement does is test @var{condition}. If @var{condition} is true, it executes the statement @var{body}. (Truth, as usual in @code{awk}, means that the value of @var{condition} is not zero and not a null string.) After @var{body} has been executed, @var{condition} is tested again, and if it is still true, @var{body} is executed again. This process repeats until @var{condition} is no longer true. If @var{condition} is initially false, the body of the loop is never executed.@refill This example prints the first three fields of each record, one per line. @example awk '@{ i = 1 while (i <= 3) @{ print $i i++ @} @}' @end example @noindent Here the body of the loop is a compound statement enclosed in braces, containing two statements. The loop works like this: first, the value of @code{i} is set to 1. Then, the @code{while} tests whether @code{i} is less than or equal to three. This is the case when @code{i} equals one, so the @code{i}-th field is printed. Then the @code{i++} increments the value of @code{i} and the loop repeats. The loop terminates when @code{i} reaches 4. As you can see, a newline is not required between the condition and the body; but using one makes the program clearer unless the body is a compound statement or is very simple. The newline after the open-brace that begins the compound statement is not required either, but the program would be hard to read without it. @node Do Statement, For Statement, While Statement, Statements @section The @code{do}-@code{while} Statement The @code{do} loop is a variation of the @code{while} looping statement. The @code{do} loop executes the @var{body} once, then repeats @var{body} as long as @var{condition} is true. It looks like this: @group @example do @var{body} while (@var{condition}) @end example @end group Even if @var{condition} is false at the start, @var{body} is executed at least once (and only once, unless executing @var{body} makes @var{condition} true). Contrast this with the corresponding @code{while} statement: @example while (@var{condition}) @var{body} @end example @noindent This statement does not execute @var{body} even once if @var{condition} is false to begin with. Here is an example of a @code{do} statement: @example awk '@{ i = 1 do @{ print $0 i++ @} while (i <= 10) @}' @end example @noindent prints each input record ten times. It isn't a very realistic example, since in this case an ordinary @code{while} would do just as well. But this reflects actual experience; there is only occasionally a real use for a @code{do} statement.@refill @node For Statement, Break Statement, Do Statement, Statements @section The @code{for} Statement @cindex @code{for} statement The @code{for} statement makes it more convenient to count iterations of a loop. The general form of the @code{for} statement looks like this:@refill @example for (@var{initialization}; @var{condition}; @var{increment}) @var{body} @end example @noindent This statement starts by executing @var{initialization}. Then, as long as @var{condition} is true, it repeatedly executes @var{body} and then @var{increment}. Typically @var{initialization} sets a variable to either zero or one, @var{increment} adds 1 to it, and @var{condition} compares it against the desired number of iterations. Here is an example of a @code{for} statement: @example awk '@{ for (i = 1; i <= 3; i++) print $i @}' @end example @noindent This prints the first three fields of each input record, one field per line. In the @code{for} statement, @var{body} stands for any statement, but @var{initialization}, @var{condition} and @var{increment} are just expressions. You cannot set more than one variable in the @var{initialization} part unless you use a multiple assignment statement such as @code{x = y = 0}, which is possible only if all the initial values are equal. (But you can initialize additional variables by writing their assignments as separate statements preceding the @code{for} loop.) The same is true of the @var{increment} part; to increment additional variables, you must write separate statements at the end of the loop. The C compound expression, using C's comma operator, would be useful in this context, but it is not supported in @code{awk}. Most often, @var{increment} is an increment expression, as in the example above. But this is not required; it can be any expression whatever. For example, this statement prints all the powers of 2 between 1 and 100: @example for (i = 1; i <= 100; i *= 2) print i @end example Any of the three expressions in the parentheses following @code{for} may be omitted if there is nothing to be done there. Thus, @w{@samp{for (;x > 0;)}} is equivalent to @w{@samp{while (x > 0)}}. If the @var{condition} is omitted, it is treated as @var{true}, effectively yielding an infinite loop.@refill In most cases, a @code{for} loop is an abbreviation for a @code{while} loop, as shown here: @example @var{initialization} while (@var{condition}) @{ @var{body} @var{increment} @} @end example @noindent The only exception is when the @code{continue} statement (@pxref{Continue Statement}) is used inside the loop; changing a @code{for} statement to a @code{while} statement in this way can change the effect of the @code{continue} statement inside the loop. There is an alternate version of the @code{for} loop, for iterating over all the indices of an array: @example for (i in array) @var{do something with} array[i] @end example @noindent @xref{Arrays}, for more information on this version of the @code{for} loop. The @code{awk} language has a @code{for} statement in addition to a @code{while} statement because often a @code{for} loop is both less work to type and more natural to think of. Counting the number of iterations is very common in loops. It can be easier to think of this counting as part of looping rather than as something to do inside the loop. The next section has more complicated examples of @code{for} loops. @node Break Statement, Continue Statement, For Statement, Statements @section The @code{break} Statement @cindex @code{break} statement @cindex loops, exiting The @code{break} statement jumps out of the innermost @code{for}, @code{while}, or @code{do}-@code{while} loop that encloses it. The following example finds the smallest divisor of any integer, and also identifies prime numbers:@refill @example awk '# find smallest divisor of num @{ num = $1 for (div = 2; div*div <= num; div++) if (num % div == 0) break if (num % div == 0) printf "Smallest divisor of %d is %d\n", num, div else printf "%d is prime\n", num @}' @end example When the remainder is zero in the first @code{if} statement, @code{awk} immediately @dfn{breaks out} of the containing @code{for} loop. This means that @code{awk} proceeds immediately to the statement following the loop and continues processing. (This is very different from the @code{exit} statement (@pxref{Exit Statement}) which stops the entire @code{awk} program.)@refill Here is another program equivalent to the previous one. It illustrates how the @var{condition} of a @code{for} or @code{while} could just as well be replaced with a @code{break} inside an @code{if}: @example awk '# find smallest divisor of num @{ num = $1 for (div = 2; ; div++) @{ if (num % div == 0) @{ printf "Smallest divisor of %d is %d\n", num, div break @} if (div*div > num) @{ printf "%d is prime\n", num break @} @} @}' @end example @node Continue Statement, Next Statement, Break Statement, Statements @section The @code{continue} Statement @cindex @code{continue} statement The @code{continue} statement, like @code{break}, is used only inside @code{for}, @code{while}, and @code{do}-@code{while} loops. It skips over the rest of the loop body, causing the next cycle around the loop to begin immediately. Contrast this with @code{break}, which jumps out of the loop altogether. Here is an example:@refill @example # print names that don't contain the string "ignore" # first, save the text of each line @{ names[NR] = $0 @} # print what we're interested in END @{ for (x in names) @{ if (names[x] ~ /ignore/) continue print names[x] @} @} @end example If one of the input records contains the string @samp{ignore}, this example skips the print statement for that record, and continues back to the first statement in the loop. This isn't a practical example of @code{continue}, since it would be just as easy to write the loop like this: @example for (x in names) if (names[x] !~ /ignore/) print names[x] @end example The @code{continue} statement in a @code{for} loop directs @code{awk} to skip the rest of the body of the loop, and resume execution with the increment-expression of the @code{for} statement. The following program illustrates this fact:@refill @example awk 'BEGIN @{ for (x = 0; x <= 20; x++) @{ if (x == 5) continue printf ("%d ", x) @} print "" @}' @end example @noindent This program prints all the numbers from 0 to 20, except for 5, for which the @code{printf} is skipped. Since the increment @code{x++} is not skipped, @code{x} does not remain stuck at 5. Contrast the @code{for} loop above with the @code{while} loop: @example awk 'BEGIN @{ x = 0 while (x <= 20) @{ if (x == 5) continue printf ("%d ", x) x++ @} print "" @}' @end example @noindent This program loops forever once @code{x} gets to 5. @node Next Statement, Exit Statement, Continue Statement, Statements @section The @code{next} Statement @cindex @code{next} statement The @code{next} statement forces @code{awk} to immediately stop processing the current record and go on to the next record. This means that no further rules are executed for the current record. The rest of the current rule's action is not executed either. Contrast this with the effect of the @code{getline} function (@pxref{Getline}). That too causes @code{awk} to read the next record immediately, but it does not alter the flow of control in any way. So the rest of the current action executes with a new input record. At the grossest level, @code{awk} program execution is a loop that reads an input record and then tests each rule's pattern against it. If you think of this loop as a @code{for} statement whose body contains the rules, then the @code{next} statement is analogous to a @code{continue} statement: it skips to the end of the body of this implicit loop, and executes the increment (which reads another record). For example, if your @code{awk} program works only on records with four fields, and you don't want it to fail when given bad input, you might use this rule near the beginning of the program: @example NF != 4 @{ printf("line %d skipped: doesn't have 4 fields", FNR) > "/dev/stderr" next @} @end example @noindent so that the following rules will not see the bad record. The error message is redirected to the standard error output stream, as error messages should be. @xref{Special Files}. The @code{next} statement is not allowed in a @code{BEGIN} or @code{END} rule. @node Exit Statement, , Next Statement, Statements @section The @code{exit} Statement @cindex @code{exit} statement The @code{exit} statement causes @code{awk} to immediately stop executing the current rule and to stop processing input; any remaining input is ignored.@refill If an @code{exit} statement is executed from a @code{BEGIN} rule the program stops processing everything immediately. No input records are read. However, if an @code{END} rule is present, it is executed (@pxref{BEGIN/END}). If @code{exit} is used as part of an @code{END} rule, it causes the program to stop immediately. An @code{exit} statement that is part an ordinary rule (that is, not part of a @code{BEGIN} or @code{END} rule) stops the execution of any further automatic rules, but the @code{END} rule is executed if there is one. If you don't want the @code{END} rule to do its job in this case, you can set a variable to nonzero before the @code{exit} statement, and check that variable in the @code{END} rule. If an argument is supplied to @code{exit}, its value is used as the exit status code for the @code{awk} process. If no argument is supplied, @code{exit} returns status zero (success).@refill For example, let's say you've discovered an error condition you really don't know how to handle. Conventionally, programs report this by exiting with a nonzero status. Your @code{awk} program can do this using an @code{exit} statement with a nonzero argument. Here's an example of this:@refill @example BEGIN @{ if (("date" | getline date_now) < 0) @{ print "Can't get system date" > "/dev/stderr" exit 4 @} @} @end example @node Arrays, Built-in, Statements, Top @chapter Arrays in @code{awk} An @dfn{array} is a table of various values, called @dfn{elements}. The elements of an array are distinguished by their @dfn{indices}. Indices may be either numbers or strings. Each array has a name, which looks like a variable name, but must not be in use as a variable name in the same @code{awk} program. @menu * Intro: Array Intro. Basic facts about arrays in @code{awk}. * Reference to Elements:: How to examine one element of an array. * Assigning Elements:: How to change an element of an array. * Example: Array Example. Sample program explained. * Scanning an Array:: A variation of the @code{for} statement. It loops through the indices of an array's existing elements. * Delete:: The @code{delete} statement removes an element from an array. * Multi-dimensional:: Emulating multi-dimensional arrays in @code{awk}. * Multi-scanning:: Scanning multi-dimensional arrays. @end menu @node Array Intro, Reference to Elements, Arrays, Arrays @section Introduction to Arrays @cindex arrays The @code{awk} language has one-dimensional @dfn{arrays} for storing groups of related strings or numbers. Every @code{awk} array must have a name. Array names have the same syntax as variable names; any valid variable name would also be a valid array name. But you cannot use one name in both ways (as an array and as a variable) in one @code{awk} program. Arrays in @code{awk} superficially resemble arrays in other programming languages; but there are fundamental differences. In @code{awk}, you don't need to specify the size of an array before you start to use it. What's more, in @code{awk} any number or even a string may be used as an array index. In most other languages, you have to @dfn{declare} an array and specify how many elements or components it has. In such languages, the declaration causes a contiguous block of memory to be allocated for that many elements. An index in the array must be a positive integer; for example, the index 0 specifies the first element in the array, which is actually stored at the beginning of the block of memory. Index 1 specifies the second element, which is stored in memory right after the first element, and so on. It is impossible to add more elements to the array, because it has room for only as many elements as you declared. A contiguous array of four elements might look like this, conceptually, if the element values are 8, @code{"foo"}, @code{""} and 30:@refill @example +---------+---------+--------+---------+ | 8 | "foo" | "" | 30 | @r{value} +---------+---------+--------+---------+ 0 1 2 3 @r{index} @end example @noindent Only the values are stored; the indices are implicit from the order of the values. 8 is the value at index 0, because 8 appears in the position with 0 elements before it. @cindex arrays, definition of @cindex associative arrays Arrays in @code{awk} are different: they are @dfn{associative}. This means that each array is a collection of pairs: an index, and its corresponding array element value: @example @r{Element} 4 @r{Value} 30 @r{Element} 2 @r{Value} "foo" @r{Element} 1 @r{Value} 8 @r{Element} 3 @r{Value} "" @end example @noindent We have shown the pairs in jumbled order because their order doesn't mean anything. One advantage of an associative array is that new pairs can be added at any time. For example, suppose we add to that array a tenth element whose value is @w{@code{"number ten"}}. The result is this: @example @r{Element} 10 @r{Value} "number ten" @r{Element} 4 @r{Value} 30 @r{Element} 2 @r{Value} "foo" @r{Element} 1 @r{Value} 8 @r{Element} 3 @r{Value} "" @end example @noindent Now the array is @dfn{sparse} (i.e., some indices are missing): it has elements 4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.@refill Another consequence of associative arrays is that the indices don't have to be positive integers. Any number, or even a string, can be an index. For example, here is an array which translates words from English into French: @example @r{Element} "dog" @r{Value} "chien" @r{Element} "cat" @r{Value} "chat" @r{Element} "one" @r{Value} "un" @r{Element} 1 @r{Value} "un" @end example @noindent Here we decided to translate the number 1 in both spelled-out and numeric form---thus illustrating that a single array can have both numbers and strings as indices. When @code{awk} creates an array for you, e.g., with the @code{split} built-in function (@pxref{String Functions}), that array's indices are consecutive integers starting at 1. @node Reference to Elements, Assigning Elements, Array Intro, Arrays @section Referring to an Array Element @cindex array reference @cindex element of array @cindex reference to array The principal way of using an array is to refer to one of its elements. An array reference is an expression which looks like this: @example @var{array}[@var{index}] @end example @noindent Here @var{array} is the name of an array. The expression @var{index} is the index of the element of the array that you want. The value of the array reference is the current value of that array element. For example, @code{foo[4.3]} is an expression for the element of array @code{foo} at index 4.3. If you refer to an array element that has no recorded value, the value of the reference is @code{""}, the null string. This includes elements to which you have not assigned any value, and elements that have been deleted (@pxref{Delete}). Such a reference automatically creates that array element, with the null string as its value. (In some cases, this is unfortunate, because it might waste memory inside @code{awk}). @cindex arrays, determining presence of elements You can find out if an element exists in an array at a certain index with the expression: @example @var{index} in @var{array} @end example @noindent This expression tests whether or not the particular index exists, without the side effect of creating that element if it is not present. The expression has the value 1 (true) if @code{@var{array}[@var{index}]} exists, and 0 (false) if it does not exist.@refill For example, to test whether the array @code{frequencies} contains the index @code{"2"}, you could write this statement:@refill @example if ("2" in frequencies) print "Subscript \"2\" is present." @end example Note that this is @emph{not} a test of whether or not the array @code{frequencies} contains an element whose @emph{value} is @code{"2"}. (There is no way to do that except to scan all the elements.) Also, this @emph{does not} create @code{frequencies["2"]}, while the following (incorrect) alternative would do so:@refill @example if (frequencies["2"] != "") print "Subscript \"2\" is present." @end example @node Assigning Elements, Array Example, Reference to Elements, Arrays @section Assigning Array Elements @cindex array assignment @cindex element assignment Array elements are lvalues: they can be assigned values just like @code{awk} variables: @example @var{array}[@var{subscript}] = @var{value} @end example @noindent Here @var{array} is the name of your array. The expression @var{subscript} is the index of the element of the array that you want to assign a value. The expression @var{value} is the value you are assigning to that element of the array.@refill @node Array Example, Scanning an Array, Assigning Elements, Arrays @section Basic Example of an Array The following program takes a list of lines, each beginning with a line number, and prints them out in order of line number. The line numbers are not in order, however, when they are first read: they are scrambled. This program sorts the lines by making an array using the line numbers as subscripts. It then prints out the lines in sorted order of their numbers. It is a very simple program, and gets confused if it encounters repeated numbers, gaps, or lines that don't begin with a number.@refill @example @{ if ($1 > max) max = $1 arr[$1] = $0 @} END @{ for (x = 1; x <= max; x++) print arr[x] @} @end example @ignore The first rule just initializes the variable @code{max}. (This is not strictly necessary, since an uninitialized variable has the null string as its value, and the null string is effectively zero when used in a context where a number is required.) @end ignore The first rule keeps track of the largest line number seen so far; it also stores each line into the array @code{arr}, at an index that is the line's number. The second rule runs after all the input has been read, to print out all the lines. When this program is run with the following input: @example 5 I am the Five man 2 Who are you? The new number two! 4 . . . And four on the floor 1 Who is number one? 3 I three you. @end example @noindent its output is this: @example 1 Who is number one? 2 Who are you? The new number two! 3 I three you. 4 . . . And four on the floor 5 I am the Five man @end example If a line number is repeated, the last line with a given number overrides the others. Gaps in the line numbers can be handled with an easy improvement to the program's @code{END} rule: @example END @{ for (x = 1; x <= max; x++) if (x in arr) print arr[x] @} @end example @node Scanning an Array, Delete, Array Example, Arrays @section Scanning All Elements of an Array @cindex @code{for (x in @dots{})} @cindex arrays, special @code{for} statement @cindex scanning an array In programs that use arrays, often you need a loop that executes once for each element of an array. In other languages, where arrays are contiguous and indices are limited to positive integers, this is easy: the largest index is one less than the length of the array, and you can find all the valid indices by counting from zero up to that value. This technique won't do the job in @code{awk}, since any number or string may be an array index. So @code{awk} has a special kind of @code{for} statement for scanning an array: @example for (@var{var} in @var{array}) @var{body} @end example @noindent This loop executes @var{body} once for each different value that your program has previously used as an index in @var{array}, with the variable @var{var} set to that index.@refill Here is a program that uses this form of the @code{for} statement. The first rule scans the input records and notes which words appear (at least once) in the input, by storing a 1 into the array @code{used} with the word as index. The second rule scans the elements of @code{used} to find all the distinct words that appear in the input. It prints each word that is more than 10 characters long, and also prints the number of such words. @xref{Built-in}, for more information on the built-in function @code{length}. @example # Record a 1 for each word that is used at least once. @{ for (i = 0; i < NF; i++) used[$i] = 1 @} # Find number of distinct words more than 10 characters long. END @{ num_long_words = 0 for (x in used) if (length(x) > 10) @{ ++num_long_words print x @} print num_long_words, "words longer than 10 characters" @} @end example @noindent @xref{Sample Program}, for a more detailed example of this type. The order in which elements of the array are accessed by this statement is determined by the internal arrangement of the array elements within @code{awk} and cannot be controlled or changed. This can lead to problems if new elements are added to @var{array} by statements in @var{body}; you cannot predict whether or not the @code{for} loop will reach them. Similarly, changing @var{var} inside the loop can produce strange results. It is best to avoid such things.@refill @node Delete, Multi-dimensional, Scanning an Array, Arrays @section The @code{delete} Statement @cindex @code{delete} statement @cindex deleting elements of arrays @cindex removing elements of arrays @cindex arrays, deleting an element You can remove an individual element of an array using the @code{delete} statement: @example delete @var{array}[@var{index}] @end example When an array element is deleted, it is as if you had never referred to it and had never given it any value. Any value the element formerly had can no longer be obtained. Here is an example of deleting elements in an array: @example for (i in frequencies) delete frequencies[i] @end example @noindent This example removes all the elements from the array @code{frequencies}. If you delete an element, a subsequent @code{for} statement to scan the array will not report that element, and the @code{in} operator to check for the presence of that element will return 0: @example delete foo[4] if (4 in foo) print "This will never be printed" @end example @node Multi-dimensional, Multi-scanning, Delete, Arrays @section Multi-dimensional Arrays @cindex subscripts, multi-dimensional in arrays @cindex arrays, multi-dimensional subscripts @cindex multi-dimensional subscripts A multi-dimensional array is an array in which an element is identified by a sequence of indices, not a single index. For example, a two-dimensional array requires two indices. The usual way (in most languages, including @code{awk}) to refer to an element of a two-dimensional array named @code{grid} is with @code{grid[@var{x},@var{y}]}. @vindex SUBSEP Multi-dimensional arrays are supported in @code{awk} through concatenation of indices into one string. What happens is that @code{awk} converts the indices into strings (@pxref{Conversion}) and concatenates them together, with a separator between them. This creates a single string that describes the values of the separate indices. The combined string is used as a single index into an ordinary, one-dimensional array. The separator used is the value of the built-in variable @code{SUBSEP}. For example, suppose we evaluate the expression @code{foo[5,12]="value"} when the value of @code{SUBSEP} is @code{"@@"}. The numbers 5 and 12 are concatenated with a comma between them, yielding @code{"5@@12"}; thus, the array element @code{foo["5@@12"]} is set to @code{"value"}. Once the element's value is stored, @code{awk} has no record of whether it was stored with a single index or a sequence of indices. The two expressions @code{foo[5,12]} and @w{@code{foo[5 SUBSEP 12]}} always have the same value. The default value of @code{SUBSEP} is actually the string @code{"\034"}, which contains a nonprinting character that is unlikely to appear in an @code{awk} program or in the input data. The usefulness of choosing an unlikely character comes from the fact that index values that contain a string matching @code{SUBSEP} lead to combined strings that are ambiguous. Suppose that @code{SUBSEP} were @code{"@@"}; then @w{@code{foo["a@@b", "c"]}} and @w{@code{foo["a", "b@@c"]}} would be indistinguishable because both would actually be stored as @code{foo["a@@b@@c"]}. Because @code{SUBSEP} is @code{"\034"}, such confusion can actually happen only when an index contains the character with ASCII code 034, which is a rare event.@refill You can test whether a particular index-sequence exists in a ``multi-dimensional'' array with the same operator @code{in} used for single dimensional arrays. Instead of a single index as the left-hand operand, write the whole sequence of indices, separated by commas, in parentheses:@refill @example (@var{subscript1}, @var{subscript2}, @dots{}) in @var{array} @end example The following example treats its input as a two-dimensional array of fields; it rotates this array 90 degrees clockwise and prints the result. It assumes that all lines have the same number of elements. @example awk '@{ if (max_nf < NF) max_nf = NF max_nr = NR for (x = 1; x <= NF; x++) vector[x, NR] = $x @} END @{ for (x = 1; x <= max_nf; x++) @{ for (y = max_nr; y >= 1; --y) printf("%s ", vector[x, y]) printf("\n") @} @}' @end example @noindent When given the input: @example 1 2 3 4 5 6 2 3 4 5 6 1 3 4 5 6 1 2 4 5 6 1 2 3 @end example @noindent it produces: @example 4 3 2 1 5 4 3 2 6 5 4 3 1 6 5 4 2 1 6 5 3 2 1 6 @end example @node Multi-scanning, , Multi-dimensional, Arrays @section Scanning Multi-dimensional Arrays There is no special @code{for} statement for scanning a ``multi-dimensional'' array; there cannot be one, because in truth there are no multi-dimensional arrays or elements; there is only a multi-dimensional @emph{way of accessing} an array. However, if your program has an array that is always accessed as multi-dimensional, you can get the effect of scanning it by combining the scanning @code{for} statement (@pxref{Scanning an Array}) with the @code{split} built-in function (@pxref{String Functions}). It works like this: @example for (combined in @var{array}) @{ split(combined, separate, SUBSEP) @dots{} @} @end example @noindent This finds each concatenated, combined index in the array, and splits it into the individual indices by breaking it apart where the value of @code{SUBSEP} appears. The split-out indices become the elements of the array @code{separate}. Thus, suppose you have previously stored in @code{@var{array}[1, "foo"]}; then an element with index @code{"1\034foo"} exists in @var{array}. (Recall that the default value of @code{SUBSEP} contains the character with code 034.) Sooner or later the @code{for} statement will find that index and do an iteration with @code{combined} set to @code{"1\034foo"}. Then the @code{split} function is called as follows: @example split("1\034foo", separate, "\034") @end example @noindent The result of this is to set @code{separate[1]} to 1 and @code{separate[2]} to @code{"foo"}. Presto, the original sequence of separate indices has been recovered. @node Built-in, User-defined, Arrays, Top @chapter Built-in Functions @cindex built-in functions @dfn{Built-in} functions are functions that are always available for your @code{awk} program to call. This chapter defines all the built-in functions in @code{awk}; some of them are mentioned in other sections, but they are summarized here for your convenience. (You can also define new functions yourself. @xref{User-defined}.) @menu * Calling Built-in:: How to call built-in functions. * Numeric Functions:: Functions that work with numbers, including @code{int}, @code{sin} and @code{rand}. * String Functions:: Functions for string manipulation, such as @code{split}, @code{match}, and @code{sprintf}. * I/O Functions:: Functions for files and shell commands @end menu @node Calling Built-in, Numeric Functions, Built-in, Built-in @section Calling Built-in Functions To call a built-in function, write the name of the function followed by arguments in parentheses. For example, @code{atan2(y + z, 1)} is a call to the function @code{atan2}, with two arguments. Whitespace is ignored between the built-in function name and the open-parenthesis, but we recommend that you avoid using whitespace there. User-defined functions do not permit whitespace in this way, and you will find it easier to avoid mistakes by following a simple convention which always works: no whitespace after a function name. Each built-in function accepts a certain number of arguments. In most cases, any extra arguments given to built-in functions are ignored. The defaults for omitted arguments vary from function to function and are described under the individual functions. When a function is called, expressions that create the function's actual parameters are evaluated completely before the function call is performed. For example, in the code fragment: @example i = 4 j = sqrt(i++) @end example @noindent the variable @code{i} is set to 5 before @code{sqrt} is called with a value of 4 for its actual parameter. @node Numeric Functions, String Functions, Calling Built-in, Built-in @section Numeric Built-in Functions Here is a full list of built-in functions that work with numbers: @table @code @item int(@var{x}) This gives you the integer part of @var{x}, truncated toward 0. This produces the nearest integer to @var{x}, located between @var{x} and 0. For example, @code{int(3)} is 3, @code{int(3.9)} is 3, @code{int(-3.9)} is @minus{}3, and @code{int(-3)} is @minus{}3 as well.@refill @item sqrt(@var{x}) This gives you the positive square root of @var{x}. It reports an error if @var{x} is negative. Thus, @code{sqrt(4)} is 2.@refill @item exp(@var{x}) This gives you the exponential of @var{x}, or reports an error if @var{x} is out of range. The range of values @var{x} can have depends on your machine's floating point representation.@refill @item log(@var{x}) This gives you the natural logarithm of @var{x}, if @var{x} is positive; otherwise, it reports an error.@refill @item sin(@var{x}) This gives you the sine of @var{x}, with @var{x} in radians. @item cos(@var{x}) This gives you the cosine of @var{x}, with @var{x} in radians. @item atan2(@var{y}, @var{x}) This gives you the arctangent of @code{@var{y} / @var{x}}, with the quotient understood in radians. @item rand() This gives you a random number. The values of @code{rand} are uniformly-distributed between 0 and 1. The value is never 0 and never 1. Often you want random integers instead. Here is a user-defined function you can use to obtain a random nonnegative integer less than @var{n}: @example function randint(n) @{ return int(n * rand()) @} @end example @noindent The multiplication produces a random real number greater than 0 and less than @var{n}. We then make it an integer (using @code{int}) between 0 and @code{@var{n} @minus{} 1}. Here is an example where a similar function is used to produce random integers between 1 and @var{n}: @example awk ' # Function to roll a simulated die. function roll(n) @{ return 1 + int(rand() * n) @} # Roll 3 six-sided dice and print total number of points. @{ printf("%d points\n", roll(6)+roll(6)+roll(6)) @}' @end example @strong{Note:} @code{rand} starts generating numbers from the same point, or @dfn{seed}, each time you run @code{awk}. This means that a program will produce the same results each time you run it. The numbers are random within one @code{awk} run, but predictable from run to run. This is convenient for debugging, but if you want a program to do different things each time it is used, you must change the seed to a value that will be different in each run. To do this, use @code{srand}. @item srand(@var{x}) The function @code{srand} sets the starting point, or @dfn{seed}, for generating random numbers to the value @var{x}. Each seed value leads to a particular sequence of ``random'' numbers. Thus, if you set the seed to the same value a second time, you will get the same sequence of ``random'' numbers again. If you omit the argument @var{x}, as in @code{srand()}, then the current date and time of day are used for a seed. This is the way to get random numbers that are truly unpredictable. The return value of @code{srand} is the previous seed. This makes it easy to keep track of the seeds for use in consistently reproducing sequences of random numbers. @end table @node String Functions, I/O Functions, Numeric Functions, Built-in @section Built-in Functions for String Manipulation The functions in this section look at the text of one or more strings. @table @code @item index(@var{in}, @var{find}) @findex match This searches the string @var{in} for the first occurrence of the string @var{find}, and returns the position where that occurrence begins in the string @var{in}. For example:@refill @example awk 'BEGIN @{ print index("peanut", "an") @}' @end example @noindent prints @samp{3}. If @var{find} is not found, @code{index} returns 0. @item length(@var{string}) @findex length This gives you the number of characters in @var{string}. If @var{string} is a number, the length of the digit string representing that number is returned. For example, @code{length("abcde")} is 5. By contrast, @code{length(15 * 35)} works out to 3. How? Well, 15 * 35 = 525, and 525 is then converted to the string @samp{"525"}, which has three characters. If no argument is supplied, @code{length} returns the length of @code{$0}. @item match(@var{string}, @var{regexp}) @findex match The @code{match} function searches the string, @var{string}, for the longest, leftmost substring matched by the regular expression, @var{regexp}. It returns the character position, or @dfn{index}, of where that substring begins (1, if it starts at the beginning of @var{string}). If no match if found, it returns 0. @vindex RSTART @vindex RLENGTH The @code{match} function sets the built-in variable @code{RSTART} to the index. It also sets the built-in variable @code{RLENGTH} to the length of the matched substring. If no match is found, @code{RSTART} is set to 0, and @code{RLENGTH} to @minus{}1. For example: @example awk '@{ if ($1 == "FIND") regex = $2 else @{ where = match($0, regex) if (where) print "Match of", regex, "found at", where, "in", $0 @} @}' @end example @noindent This program looks for lines that match the regular expression stored in the variable @code{regex}. This regular expression can be changed. If the first word on a line is @samp{FIND}, @code{regex} is changed to be the second word on that line. Therefore, given: @example FIND fo*bar My program was a foobar But none of it would doobar FIND Melvin JF+KM This line is property of The Reality Engineering Co. This file created by Melvin. @end example @noindent @code{awk} prints: @example Match of fo*bar found at 18 in My program was a foobar Match of Melvin found at 26 in This file created by Melvin. @end example @item split(@var{string}, @var{array}, @var{fieldsep}) @findex split This divides @var{string} up into pieces separated by @var{fieldsep}, and stores the pieces in @var{array}. The first piece is stored in @code{@var{array}[1]}, the second piece in @code{@var{array}[2]}, and so forth. The string value of the third argument, @var{fieldsep}, is used as a regexp to search for to find the places to split @var{string}. If the @var{fieldsep} is omitted, the value of @code{FS} is used. @code{split} returns the number of elements created.@refill The @code{split} function, then, splits strings into pieces in a manner similar to the way input lines are split into fields. For example: @example split("auto-da-fe", a, "-") @end example @noindent splits the string @samp{auto-da-fe} into three fields using @samp{-} as the separator. It sets the contents of the array @code{a} as follows: @example a[1] = "auto" a[2] = "da" a[3] = "fe" @end example @noindent The value returned by this call to @code{split} is 3. @item sprintf(@var{format}, @var{expression1},@dots{}) @findex sprintf This returns (without printing) the string that @code{printf} would have printed out with the same arguments (@pxref{Printf}). For example: @example sprintf("pi = %.2f (approx.)", 22/7) @end example @noindent returns the string @w{@code{"pi = 3.14 (approx.)"}}. @item sub(@var{regexp}, @var{replacement}, @var{target}) @findex sub The @code{sub} function alters the value of @var{target}. It searches this value, which should be a string, for the leftmost substring matched by the regular expression, @var{regexp}, extending this match as far as possible. Then the entire string is changed by replacing the matched text with @var{replacement}. The modified string becomes the new value of @var{target}. This function is peculiar because @var{target} is not simply used to compute a value, and not just any expression will do: it must be a variable, field or array reference, so that @code{sub} can store a modified value there. If this argument is omitted, then the default is to use and alter @code{$0}. For example:@refill @example str = "water, water, everywhere" sub(/at/, "ith", str) @end example @noindent sets @code{str} to @w{@code{"wither, water, everywhere"}}, by replacing the leftmost, longest occurrence of @samp{at} with @samp{ith}. The @code{sub} function returns the number of substitutions made (either one or zero). If the special character @samp{&} appears in @var{replacement}, it stands for the precise substring that was matched by @var{regexp}. (If the regexp can match more than one string, then this precise substring may vary.) For example:@refill @example awk '@{ sub(/candidate/, "& and his wife"); print @}' @end example @noindent changes the first occurrence of @samp{candidate} to @samp{candidate and his wife} on each input line. The effect of this special character can be turned off by putting a backslash before it in the string. As usual, to insert one backslash in the string, you must write two backslashes. Therefore, write @samp{\\&} in a string constant to include a literal @samp{&} in the replacement. For example, here is how to replace the first @samp{|} on each line with an @samp{&}:@refill @example awk '@{ sub(/\|/, "\\&"); print @}' @end example @strong{Note:} as mentioned above, the third argument to @code{sub} must be an lvalue. Some versions of @code{awk} allow the third argument to be an expression which is not an lvalue. In such a case, @code{sub} would still search for the pattern and return 0 or 1, but the result of the substitution (if any) would be thrown away because there is no place to put it. Such versions of @code{awk} accept expressions like this:@refill @example sub(/USA/, "United States", "the USA and Canada") @end example @noindent But that is considered erroneous in @code{gawk}. @item gsub(@var{regexp}, @var{replacement}, @var{target}) @findex gsub This is similar to the @code{sub} function, except @code{gsub} replaces @emph{all} of the longest, leftmost, @emph{nonoverlapping} matching substrings it can find. The @samp{g} in @code{gsub} stands for ``global'', which means replace everywhere. For example:@refill @example awk '@{ gsub(/Britain/, "United Kingdom"); print @}' @end example @noindent replaces all occurrences of the string @samp{Britain} with @samp{United Kingdom} for all input records.@refill The @code{gsub} function returns the number of substitutions made. If the variable to be searched and altered, @var{target}, is omitted, then the entire input record, @code{$0}, is used.@refill As in @code{sub}, the characters @samp{&} and @samp{\} are special, and the third argument must be an lvalue. @item substr(@var{string}, @var{start}, @var{length}) @findex substr This returns a @var{length}-character-long substring of @var{string}, starting at character number @var{start}. The first character of a string is character number one. For example, @code{substr("washington", 5, 3)} returns @code{"ing"}.@refill If @var{length} is not present, this function returns the whole suffix of @var{string} that begins at character number @var{start}. For example, @code{substr("washington", 5)} returns @code{"ington"}. @item tolower(@var{string}) @findex tolower This returns a copy of @var{string}, with each upper-case character in the string replaced with its corresponding lower-case character. Nonalphabetic characters are left unchanged. For example, @code{tolower("MiXeD cAsE 123")} returns @code{"mixed case 123"}. @item toupper(@var{string}) @findex toupper This returns a copy of @var{string}, with each lower-case character in the string replaced with its corresponding upper-case character. Nonalphabetic characters are left unchanged. For example, @code{toupper("MiXeD cAsE 123")} returns @code{"MIXED CASE 123"}. @end table @node I/O Functions, , String Functions, Built-in @section Built-in Functions For Input/Output @table @code @item close(@var{filename}) Close the file @var{filename}, for input or output. The argument may alternatively be a shell command that was used for redirecting to or from a pipe; then the pipe is closed. @xref{Close Input}, regarding closing input files and pipes. @xref{Close Output}, regarding closing output files and pipes. @item system(@var{command}) @findex system @cindex interaction of @code{awk} with other programs The system function allows the user to execute operating system commands and then return to the @code{awk} program. The @code{system} function executes the command given by the string @var{command}. It returns, as its value, the status returned by the command that was executed. For example, if the following fragment of code is put in your @code{awk} program: @example END @{ system("mail -s 'awk run done' operator < /dev/null") @} @end example @noindent the system operator will be sent mail when the @code{awk} program finishes processing input and begins its end-of-input processing. Note that much the same result can be obtained by redirecting @code{print} or @code{printf} into a pipe. However, if your @code{awk} program is interactive, @code{system} is useful for cranking up large self-contained programs, such as a shell or an editor.@refill Some operating systems cannot implement the @code{system} function. @code{system} causes a fatal error if it is not supported. @end table @node User-defined, Built-in Variables, Built-in, Top @chapter User-defined Functions @cindex user-defined functions @cindex functions, user-defined Complicated @code{awk} programs can often be simplified by defining your own functions. User-defined functions can be called just like built-in ones (@pxref{Function Calls}), but it is up to you to define them---to tell @code{awk} what they should do. @menu * Definition Syntax:: How to write definitions and what they mean. * Function Example:: An example function definition and what it does. * Function Caveats:: Things to watch out for. * Return Statement:: Specifying the value a function returns. @end menu @node Definition Syntax, Function Example, User-defined, User-defined @section Syntax of Function Definitions @cindex defining functions @cindex function definition Definitions of functions can appear anywhere between the rules of the @code{awk} program. Thus, the general form of an @code{awk} program is extended to include sequences of rules @emph{and} user-defined function definitions. The definition of a function named @var{name} looks like this: @example function @var{name} (@var{parameter-list}) @{ @var{body-of-function} @} @end example @noindent The keyword @code{function} may be abbreviated @code{func}. @var{name} is the name of the function to be defined. A valid function name is like a valid variable name: a sequence of letters, digits and underscores, not starting with a digit. @var{parameter-list} is a list of the function's arguments and local variable names, separated by commas. When the function is called, the argument names are used to hold the argument values given in the call. The local variables are initialized to the null string. The @var{body-of-function} consists of @code{awk} statements. It is the most important part of the definition, because it says what the function should actually @emph{do}. The argument names exist to give the body a way to talk about the arguments; local variables, to give the body places to keep temporary values. Argument names are not distinguished syntactically from local variable names; instead, the number of arguments supplied when the function is called determines how many argument variables there are. Thus, if three argument values are given, the first three names in @var{parameter-list} are arguments, and the rest are local variables. It follows that if the number of arguments is not the same in all calls to the function, some of the names in @var{parameter-list} may be arguments on some occasions and local variables on others. Another way to think of this is that omitted arguments default to the null string. Usually when you write a function you know how many names you intend to use for arguments and how many you intend to use as locals. By convention, you should write an extra space between the arguments and the locals, so that other people can follow how your function is supposed to be used. During execution of the function body, the arguments and local variable values hide or @dfn{shadow} any variables of the same names used in the rest of the program. The shadowed variables are not accessible in the function definition, because there is no way to name them while their names have been taken away for the local variables. All other variables used in the @code{awk} program can be referenced or set normally in the function definition. The arguments and local variables last only as long as the function body is executing. Once the body finishes, the shadowed variables come back. The function body can contain expressions which call functions. They can even call this function, either directly or by way of another function. When this happens, we say the function is @dfn{recursive}. There is no need in @code{awk} to put the definition of a function before all uses of the function. This is because @code{awk} reads the entire program before starting to execute any of it. @node Function Example, Function Caveats, Definition Syntax, User-defined @section Function Definition Example Here is an example of a user-defined function, called @code{myprint}, that takes a number and prints it in a specific format. @example function myprint(num) @{ printf "%6.3g\n", num @} @end example @noindent To illustrate, here is an @code{awk} rule which uses our @code{myprint} function: @example $3 > 0 @{ myprint($3) @} @end example @noindent This program prints, in our special format, all the third fields that contain a positive number in our input. Therefore, when given: @example 1.2 3.4 5.6 7.8 9.10 11.12 13.14 15.16 17.18 19.20 21.22 23.24 @end example @noindent this program, using our function to format the results, prints: @example 5.6 13.1 21.2 @end example Here is a rather contrived example of a recursive function. It prints a string backwards: @example function rev (str, len) @{ if (len == 0) @{ printf "\n" return @} printf "%c", substr(str, len, 1) rev(str, len - 1) @} @end example @node Function Caveats, Return Statement, Function Example, User-defined @section Calling User-defined Functions @dfn{Calling a function} means causing the function to run and do its job. A function call is an expression, and its value is the value returned by the function. A function call consists of the function name followed by the arguments in parentheses. What you write in the call for the arguments are @code{awk} expressions; each time the call is executed, these expressions are evaluated, and the values are the actual arguments. For example, here is a call to @code{foo} with three arguments: @example foo(x y, "lose", 4 * z) @end example @strong{Note:} whitespace characters (spaces and tabs) are not allowed between the function name and the open-parenthesis of the argument list. If you write whitespace by mistake, @code{awk} might think that you mean to concatenate a variable with an expression in parentheses. However, it notices that you used a function name and not a variable name, and reports an error. @cindex call by value When a function is called, it is given a @emph{copy} of the values of its arguments. This is called @dfn{call by value}. The caller may use a variable as the expression for the argument, but the called function does not know this: all it knows is what value the argument had. For example, if you write this code: @example foo = "bar" z = myfunc(foo) @end example @noindent then you should not think of the argument to @code{myfunc} as being ``the variable @code{foo}''. Instead, think of the argument as the string value, @code{"bar"}. If the function @code{myfunc} alters the values of its local variables, this has no effect on any other variables. In particular, if @code{myfunc} does this: @example function myfunc (win) @{ print win win = "zzz" print win @} @end example @noindent to change its first argument variable @code{win}, this @emph{does not} change the value of @code{foo} in the caller. The role of @code{foo} in calling @code{myfunc} ended when its value, @code{"bar"}, was computed. If @code{win} also exists outside of @code{myfunc}, the function body cannot alter this outer value, because it is shadowed during the execution of @code{myfunc} and cannot be seen or changed from there. @cindex call by reference However, when arrays are the parameters to functions, they are @emph{not} copied. Instead, the array itself is made available for direct manipulation by the function. This is usually called @dfn{call by reference}. Changes made to an array parameter inside the body of a function @emph{are} visible outside that function. @emph{This can be very dangerous if you don't watch what you are doing.} For example:@refill @example function changeit (array, ind, nvalue) @{ array[ind] = nvalue @} BEGIN @{ a[1] = 1 ; a[2] = 2 ; a[3] = 3 changeit(a, 2, "two") printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3] @} @end example @noindent prints @samp{a[1] = 1, a[2] = two, a[3] = 3}, because calling @code{changeit} stores @code{"two"} in the second element of @code{a}. @node Return Statement, , Function Caveats, User-defined @section The @code{return} Statement @cindex @code{return} statement The body of a user-defined function can contain a @code{return} statement. This statement returns control to the rest of the @code{awk} program. It can also be used to return a value for use in the rest of the @code{awk} program. It looks like this:@refill @example return @var{expression} @end example The @var{expression} part is optional. If it is omitted, then the returned value is undefined and, therefore, unpredictable. A @code{return} statement with no value expression is assumed at the end of every function definition. So if control reaches the end of the function definition, then the function returns an unpredictable value. Here is an example of a user-defined function that returns a value for the largest number among the elements of an array:@refill @example function maxelt (vec, i, ret) @{ for (i in vec) @{ if (ret == "" || vec[i] > ret) ret = vec[i] @} return ret @} @end example @noindent You call @code{maxelt} with one argument, an array name. The local variables @code{i} and @code{ret} are not intended to be arguments; while there is nothing to stop you from passing two or three arguments to @code{maxelt}, the results would be strange. The extra space before @code{i} in the function parameter list is to indicate that @code{i} and @code{ret} are not supposed to be arguments. This is a convention which you should follow when you define functions. Here is a program that uses our @code{maxelt} function. It loads an array, calls @code{maxelt}, and then reports the maximum number in that array:@refill @example awk ' function maxelt (vec, i, ret) @{ for (i in vec) @{ if (ret == "" || vec[i] > ret) ret = vec[i] @} return ret @} # Load all fields of each record into nums. @{ for(i = 1; i <= NF; i++) nums[NR, i] = $i @} END @{ print maxelt(nums) @}' @end example Given the following input: @example 1 5 23 8 16 44 3 5 2 8 26 256 291 1396 2962 100 -6 467 998 1101 99385 11 0 225 @end example @noindent our program tells us (predictably) that: @example 99385 @end example @noindent is the largest number in our array. @node Built-in Variables, Command Line, User-defined, Top @chapter Built-in Variables @cindex built-in variables Most @code{awk} variables are available for you to use for your own purposes; they never change except when your program assigns them, and never affect anything except when your program examines them. A few variables have special built-in meanings. Some of them @code{awk} examines automatically, so that they enable you to tell @code{awk} how to do certain things. Others are set automatically by @code{awk}, so that they carry information from the internal workings of @code{awk} to your program. This chapter documents all the built-in variables of @code{gawk}. Most of them are also documented in the chapters where their areas of activity are described. @menu * User-modified:: Built-in variables that you change to control @code{awk}. * Auto-set:: Built-in variables where @code{awk} gives you information. @end menu @node User-modified, Auto-set, Built-in Variables, Built-in Variables @section Built-in Variables That Control @code{awk} @cindex built-in variables, user modifiable This is a list of the variables which you can change to control how @code{awk} does certain things. @table @code @c it's unadvisable to have multiple index entries for the same name @c since in Info there is no way to distinguish the two. @c @vindex FS @item FS @code{FS} is the input field separator (@pxref{Field Separators}). The value is a single-character string or a multi-character regular expression that matches the separations between fields in an input record. The default value is @w{@code{" "}}, a string consisting of a single space. As a special exception, this value actually means that any sequence of spaces and tabs is a single separator. It also causes spaces and tabs at the beginning or end of a line to be ignored. You can set the value of @code{FS} on the command line using the @samp{-F} option: @example awk -F, '@var{program}' @var{input-files} @end example @item IGNORECASE @c @vindex IGNORECASE If @code{IGNORECASE} is nonzero, then @emph{all} regular expression matching is done in a case-independent fashion. In particular, regexp matching with @samp{~} and @samp{!~}, and the @code{gsub} @code{index}, @code{match}, @code{split} and @code{sub} functions all ignore case when doing their particular regexp operations. @strong{Note:} since field splitting with the value of the @code{FS} variable is also a regular expression operation, that too is done with case ignored. @xref{Case-sensitivity}. If @code{gawk} is in compatibility mode (@pxref{Command Line}), then @code{IGNORECASE} has no special meaning, and regexp operations are always case-sensitive.@refill @item OFMT @c @vindex OFMT This string is used by @code{awk} to control conversion of numbers to strings (@pxref{Conversion}). It works by being passed, in effect, as the first argument to the @code{sprintf} function. Its default value is @code{"%.6g"}.@refill @item OFS @c @vindex OFS This is the output field separator (@pxref{Output Separators}). It is output between the fields output by a @code{print} statement. Its default value is @w{@code{" "}}, a string consisting of a single space. @item ORS @c @vindex ORS This is the output record separator. It is output at the end of every @code{print} statement. Its default value is a string containing a single newline character, which could be written as @code{"\n"}. (@xref{Output Separators}).@refill @item RS @c @vindex RS This is @code{awk}'s record separator. Its default value is a string containing a single newline character, which means that an input record consists of a single line of text. (@xref{Records}.)@refill @item SUBSEP @c @vindex SUBSEP @code{SUBSEP} is a subscript separator. It has the default value of @code{"\034"}, and is used to separate the parts of the name of a multi-dimensional array. Thus, if you access @code{foo[12,3]}, it really accesses @code{foo["12\0343"]}. (@xref{Multi-dimensional}).@refill @end table @node Auto-set, , User-modified, Built-in Variables @section Built-in Variables That Convey Information to You This is a list of the variables that are set automatically by @code{awk} on certain occasions so as to provide information for your program. @table @code @item ARGC @itemx ARGV @c @vindex ARGC @c @vindex ARGV The command-line arguments available to @code{awk} are stored in an array called @code{ARGV}. @code{ARGC} is the number of command-line arguments present. @code{ARGV} is indexed from zero to @w{@code{ARGC - 1}}. @xref{Command Line}. For example: @example awk '@{ print ARGV[$1] @}' inventory-shipped BBS-list @end example @noindent In this example, @code{ARGV[0]} contains @code{"awk"}, @code{ARGV[1]} contains @code{"inventory-shipped"}, and @code{ARGV[2]} contains @code{"BBS-list"}. The value of @code{ARGC} is 3, one more than the index of the last element in @code{ARGV} since the elements are numbered from zero.@refill Notice that the @code{awk} program is not entered in @code{ARGV}. The other special command line options, with their arguments, are also not entered. But variable assignments on the command line @emph{are} treated as arguments, and do show up in the @code{ARGV} array. Your program can alter @code{ARGC} and the elements of @code{ARGV}. Each time @code{awk} reaches the end of an input file, it uses the next element of @code{ARGV} as the name of the next input file. By storing a different string there, your program can change which files are read. You can use @code{"-"} to represent the standard input. By storing additional elements and incrementing @code{ARGC} you can cause additional files to be read. If you decrease the value of @code{ARGC}, that eliminates input files from the end of the list. By recording the old value of @code{ARGC} elsewhere, your program can treat the eliminated arguments as something other than file names. To eliminate a file from the middle of the list, store the null string (@code{""}) into @code{ARGV} in place of the file's name. As a special feature, @code{awk} ignores file names that have been replaced with the null string. @item ENVIRON @vindex ENVIRON This is an array that contains the values of the environment. The array indices are the environment variable names; the values are the values of the particular environment variables. For example, @code{ENVIRON["HOME"]} might be @file{/u/close}. Changing this array does not affect the environment passed on to any programs that @code{awk} may spawn via redirection or the @code{system} function. (In a future version of @code{gawk}, it may do so.) Some operating systems may not have environment variables. On such systems, the array @code{ENVIRON} is empty. @item FILENAME @c @vindex FILENAME This is the name of the file that @code{awk} is currently reading. If @code{awk} is reading from the standard input (in other words, there are no files listed on the command line), @code{FILENAME} is set to @code{"-"}. @code{FILENAME} is changed each time a new file is read (@pxref{Reading Files}).@refill @item FNR @c @vindex FNR @code{FNR} is the current record number in the current file. @code{FNR} is incremented each time a new record is read (@pxref{Getline}). It is reinitialized to 0 each time a new input file is started. @item NF @c @vindex NF @code{NF} is the number of fields in the current input record. @code{NF} is set each time a new record is read, when a new field is created, or when @code{$0} changes (@pxref{Fields}).@refill @item NR @c @vindex NR This is the number of input records @code{awk} has processed since the beginning of the program's execution. (@pxref{Records}). @code{NR} is set each time a new record is read.@refill @item RLENGTH @c @vindex RLENGTH @code{RLENGTH} is the length of the substring matched by the @code{match} function (@pxref{String Functions}). @code{RLENGTH} is set by invoking the @code{match} function. Its value is the length of the matched string, or @minus{}1 if no match was found.@refill @item RSTART @c @vindex RSTART @code{RSTART} is the start-index of the substring matched by the @code{match} function (@pxref{String Functions}). @code{RSTART} is set by invoking the @code{match} function. Its value is the position of the string where the matched substring starts, or 0 if no match was found.@refill @end table @node Command Line, Language History, Built-in Variables, Top @c node-name, next, previous, up @chapter Invocation of @code{awk} @cindex command line @cindex invocation of @code{gawk} @cindex arguments, command line @cindex options, command line There are two ways to run @code{awk}: with an explicit program, or with one or more program files. Here are templates for both of them; items enclosed in @samp{@r{[}@dots{}@r{]}} in these templates are optional. @example awk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{} awk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{} @end example @menu * Options:: Command line options and their meanings. * Other Arguments:: Input file names and variable assignments. * AWKPATH Variable:: Searching directories for @code{awk} programs. @end menu @node Options, Other Arguments, Command Line, Command Line @section Command Line Options Options begin with a minus sign, and consist of a single character. The options and their meanings are as follows: @table @code @item -F@var{fs} Sets the @code{FS} variable to @var{fs} (@pxref{Field Separators}). @item -f @var{source-file} Indicates that the @code{awk} program is to be found in @var{source-file} instead of in the first non-option argument. @item -v @var{var}=@var{val} @cindex @samp{-v} option Sets the variable @var{var} to the value @var{val} @emph{before} execution of the program begins. Such variable values are available inside the @code{BEGIN} rule (see below for a fuller explanation). The @samp{-v} option only has room to set one variable, but you can use it more than once, setting another variable each time, like this: @samp{@w{-v foo=1} @w{-v bar=2}}. @item -a Specifies use of traditional @code{awk} syntax for regular expressions. This means that @samp{\} can be used to quote any regular expression operators inside of square brackets, just as it can be outside of them. This mode is currently the default; the @samp{-a} option is useful in shell scripts so that they will not break if the default is changed. @xref{Regexp Operators}. @item -e Specifies use of @code{egrep} syntax for regular expressions. This means that @samp{\} does not serve as a quoting character inside of square brackets; ideosyncratic techniques are needed to include various special characters within them. This mode may become the default at some time in the future. @xref{Regexp Operators}. @item -c @cindex @samp{-c} option Specifies @dfn{compatibility mode}, in which the GNU extensions in @code{gawk} are disabled, so that @code{gawk} behaves just like Unix @code{awk}. These extensions are noted below, where their usage is explained. @xref{Compatibility Mode}. @item -V @cindex @samp{-V} option Prints version information for this particular copy of @code{gawk}. This is so you can determine if your copy of @code{gawk} is up to date with respect to whatever the Free Software Foundation is currently distributing. This option may disappear in a future version of @code{gawk}. @item -C @cindex @samp{-C} option Prints the short version of the General Public License. This option may disappear in a future version of @code{gawk}. @item -- Signals the end of the command line options. The following arguments are not treated as options even if they begin with @samp{-}. This interpretation of @samp{--} follows the POSIX argument parsing conventions. This is useful if you have file names that start with @samp{-}, or in shell scripts, if you have file names that will be specified by the user and that might start with @samp{-}. @end table Any other options are flagged as invalid with a warning message, but are otherwise ignored. In compatibility mode, as a special case, if the value of @var{fs} supplied to the @samp{-F} option is @samp{t}, then @code{FS} is set to the tab character (@code{"\t"}). Also, the @samp{-C} and @samp{-V} options are not recognized.@refill If the @samp{-f} option is @emph{not} used, then the first non-option command line argument is expected to be the program text. The @samp{-f} option may be used more than once on the command line. Then @code{awk} reads its program source from all of the named files, as if they had been concatenated together into one big file. This is useful for creating libraries of @code{awk} functions. Useful functions can be written once, and then retrieved from a standard place, instead of having to be included into each individual program. You can still type in a program at the terminal and use library functions, by specifying @samp{-f /dev/tty}. @code{awk} will read a file from the terminal to use as part of the @code{awk} program. After typing your program, type @kbd{Control-d} (the end-of-file character) to terminate it. @node Other Arguments, AWKPATH Variable, Options, Command Line @section Other Command Line Arguments Any additional arguments on the command line are normally treated as input files to be processed in the order specified. However, an argument that has the form @code{@var{var}=@var{value}}, means to assign the value @var{value} to the variable @var{var}---it does not specify a file at all. @vindex ARGV All these arguments are made available to your @code{awk} program in the @code{ARGV} array (@pxref{Built-in Variables}). Command line options and the program text (if present) are omitted from the @code{ARGV} array. All other arguments, including variable assignments, are included. The distinction between file name arguments and variable-assignment arguments is made when @code{awk} is about to open the next input file. At that point in execution, it checks the ``file name'' to see whether it is really a variable assignment; if so, @code{awk} sets the variable instead of reading a file. Therefore, the variables actually receive the specified values after all previously specified files have been read. In particular, the values of variables assigned in this fashion are @emph{not} available inside a @code{BEGIN} rule (@pxref{BEGIN/END}), since such rules are run before @code{awk} begins scanning the argument list.@refill In some earlier implementations of @code{awk}, when a variable assignment occurred before any file names, the assignment would happen @emph{before} the @code{BEGIN} rule was executed. Some applications came to depend upon this ``feature''. When @code{awk} was changed to be more consistent, the @samp{-v} option was added to accomodate applications that depended upon this old behaviour. The variable assignment feature is most useful for assigning to variables such as @code{RS}, @code{OFS}, and @code{ORS}, which control input and output formats, before scanning the data files. It is also useful for controlling state if multiple passes are needed over a data file. For example:@refill @cindex multiple passes over data @cindex passes, multiple @example awk 'pass == 1 @{ @var{pass 1 stuff} @} pass == 2 @{ @var{pass 2 stuff} @}' pass=1 datafile pass=2 datafile @end example @node AWKPATH Variable,, Other Arguments, Command Line @section The @code{AWKPATH} Environment Variable @cindex @code{AWKPATH} environment variable @cindex search path @cindex directory search @cindex path, search @c @cindex differences between @code{gawk} and @code{awk} The previous section described how @code{awk} program files can be named on the command line with the @samp{-f} option. In some @code{awk} implementations, you must supply a precise path name for each program file, unless the file is in the current directory. But in @code{gawk}, if the file name supplied in the @samp{-f} option does not contain a @samp{/}, then @code{gawk} searches a list of directories (called the @dfn{search path}), one by one, looking for a file with the specified name. The search path is actually a string containing directory names separated by colons. @code{gawk} gets its search path from the @code{AWKPATH} environment variable. If that variable does not exist, @code{gawk} uses the default path, which is @samp{.:/usr/lib/awk:/usr/local/lib/awk}.@refill The search path feature is particularly useful for building up libraries of useful @code{awk} functions. The library files can be placed in a standard directory that is in the default path, and then specified on the command line with a short file name. Otherwise, the full file name would have to be typed for each file. Path searching is not done if @code{gawk} is in compatibility mode. @xref{Command Line}. @strong{Note:} if you want files in the current directory to be found, you must include the current directory in the path, either by writing @file{.} as an entry in the path, or by writing a null entry in the path. (A null entry is indicated by starting or ending the path with a colon, or by placing two colons next to each other (@samp{::}).) If the current directory is not included in the path, then files cannot be found in the current directory. This path search mechanism is identical to the shell's. @c someday, @cite{The Bourne Again Shell}.... @node Language History, Gawk Summary, Command Line, Top @chapter The Evolution of the @code{awk} Language This manual describes the GNU implementation of @code{awk}, which is patterned after the System V Release 4 version. Many @code{awk} users are only familiar with the original @code{awk} implementation in Version 7 Unix, which is also the basis for the version in Berkeley Unix. This chapter briefly describes the evolution of the @code{awk} language. @menu * V7/S5R3.1:: The major changes between V7 and System V Release 3.1. * S5R4:: The minor changes between System V Releases 3.1 and 4. * S5R4/GNU:: The extensions in @code{gawk} not in System V Release 4. @end menu @node V7/S5R3.1, S5R4, Language History, Language History @section Major Changes Between V7 and S5R3.1 The @code{awk} language evolved considerably between the release of Version 7 Unix (1978) and the new version first made widely available in System V Release 3.1 (1987). This section summarizes the changes, with cross-references to further details. @itemize @bullet @item The requirement for @samp{;} to separate rules on a line (@pxref{Statements/Lines}). @item User-defined functions, and the @code{return} statement (@pxref{User-defined}). @item The @code{delete} statement (@pxref{Delete}). @item The @code{do}-@code{while} statement (@pxref{Do Statement}). @item The built-in functions @code{atan2}, @code{cos}, @code{sin}, @code{rand} and @code{srand} (@pxref{Numeric Functions}). @item The built-in functions @code{gsub}, @code{sub}, and @code{match} (@pxref{String Functions}). @item The built-in functions @code{close} and @code{system} (@pxref{I/O Functions}). @item The @code{ARGC}, @code{ARGV}, @code{FNR}, @code{RLENGTH}, @code{RSTART}, and @code{SUBSEP} built-in variables (@pxref{Built-in Variables}). @item The conditional expression using the operators @samp{?} and @samp{:} (@pxref{Conditional Exp}). @item The exponentiation operator @samp{^} (@pxref{Arithmetic Ops}) and its assignment operator form @samp{^=} (@pxref{Assignment Ops}).@refill @item C-compatible operator precedence, which breaks some old @code{awk} programs (@pxref{Precedence}). @item Regexps as the value of @code{FS} (@pxref{Field Separators}), or as the third argument to the @code{split} function (@pxref{String Functions}).@refill @item Dynamic regexps as operands of the @samp{~} and @samp{!~} operators (@pxref{Regexp Usage}). @item Escape sequences (@pxref{Constants}) in regexps.@refill @item The escape sequences @samp{\b}, @samp{\f}, and @samp{\r} (@pxref{Constants}). @item Redirection of input for the @code{getline} function (@pxref{Getline}). @item Multiple @code{BEGIN} and @code{END} rules (@pxref{BEGIN/END}). @item Simulation of multidimensional arrays (@pxref{Multi-dimensional}). @end itemize @node S5R4, S5R4/GNU, V7/S5R3.1, Language History @section Minor Changes between S5R3.1 and S5R4 The System V Release 4 version of Unix @code{awk} added these features: @itemize @bullet @item The @code{ENVIRON} variable (@pxref{Built-in Variables}). @item Multiple @samp{-f} options on the command line (@pxref{Command Line}). @item The @samp{-v} option for assigning variables before program execution begins (@pxref{Command Line}). @item The @samp{--} option for terminating command line options. @item The @samp{\a}, @samp{\v}, and @samp{\x} escape sequences (@pxref{Constants}). @item A defined return value for the @code{srand} built-in function (@pxref{Numeric Functions}). @item The @code{toupper} and @code{tolower} built-in string functions for case translation (@pxref{String Functions}). @item A cleaner specification for the @samp{%c} format-control letter in the @code{printf} function (@pxref{Printf}). @item The use of constant regexps such as @code{/foo/} as expressions, where they are equivalent to use of the matching operator, as in @code{$0 ~ /foo/}. @end itemize @node S5R4/GNU, , S5R4, Language History @section Extensions In @code{gawk} Not In S5R4 The GNU implementation, @code{gawk}, adds these features: @itemize @bullet @item The @code{AWKPATH} environment variable for specifying a path search for the @samp{-f} command line option (@pxref{Command Line}). @item The @samp{-C} and @samp{-V} command line options (@pxref{Command Line}). @item The @code{IGNORECASE} variable and its effects (@pxref{Case-sensitivity}). @item The @file{/dev/stdin}, @file{/dev/stdout}, @file{/dev/stderr}, and @file{/dev/fd/@var{n}} file name interpretation (@pxref{Special Files}). @item The @samp{-c} option to turn off these extensions (@pxref{Command Line}). @item The @samp{-a} and @samp{-e} options to specify the syntax of regular expressions that @code{gawk} will accept (@pxref{Command Line}). @end itemize @node Gawk Summary, Sample Program, Language History, Top @appendix @code{gawk} Summary @ignore See, man pages are good for something. This chapter started life as the gawk.1 man page for 2.11. @end ignore This appendix provides a brief summary of the @code{gawk} command line and the @code{awk} language. It is designed to serve as ``quick reference.'' It is therefore terse, but complete. @menu * Command Line Summary:: Recapitulation of the command line. * Language Summary:: A terse review of the language. * Variables/Fields:: Variables, fields, and arrays. * Rules Summary:: Patterns and Actions, and their component parts. * Functions Summary:: Defining and calling functions. @end menu @node Command Line Summary, Language Summary, Gawk Summary, Gawk Summary @appendixsec Command Line Options Summary The command line consists of options to @code{gawk} itself, the @code{awk} program text (if not supplied via the @samp{-f} option), and values to be made available in the @code{ARGC} and @code{ARGV} predefined @code{awk} variables: @example awk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{} awk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{} @end example The options that @code{gawk} accepts are: @table @code @item -F@var{fs} Use @var{fs} for the input field separator (the value of the @code{FS} predefined variable). @item -f @var{program-file} Read the @code{awk} program source from the file @var{program-file}, instead of from the first command line argument. @item -v @var{var}=@var{val} Assign the variable @var{var} the value @var{val} before program execution begins. @item -a Specifies use of traditional @code{awk} syntax for regular expressions. This means that @samp{\} can be used to quote regular expression operators inside of square brackets, just as it can be outside of them. @item -e Specifies use of @code{egrep} syntax for regular expressions. This means that @samp{\} does not serve as a quoting character inside of square brackets. @item -c Specifies compatibility mode, in which @code{gawk} extensions are turned off. @item -V Print version information for this particular copy of @code{gawk} on the error output. This option may disappear in a future version of @code{gawk}. @item -C Print the short version of the General Public License on the error output. This option may disappear in a future version of @code{gawk}. @item -- Signal the end of options. This is useful to allow further arguments to the @code{awk} program itself to start with a @samp{-}. This is mainly for consistency with the argument parsing conventions of POSIX. @end table Any other options are flagged as invalid, but are otherwise ignored. @xref{Command Line}, for more details. @node Language Summary, Variables/Fields, Command Line Summary, Gawk Summary @appendixsec Language Summary An @code{awk} program consists of a sequence of pattern-action statements and optional function definitions. @example @var{pattern} @{ @var{action statements} @} function @var{name}(@var{parameter list}) @{ @var{action statements} @} @end example @code{gawk} first reads the program source from the @var{program-file}(s) if specified, or from the first non-option argument on the command line. The @samp{-f} option may be used multiple times on the command line. @code{gawk} reads the program text from all the @var{program-file} files, effectively concatenating them in the order they are specified. This is useful for building libraries of @code{awk} functions, without having to include them in each new @code{awk} program that uses them. To use a library function in a file from a program typed in on the command line, specify @samp{-f /dev/tty}; then type your program, and end it with a @kbd{C-d}. @xref{Command Line}. The environment variable @code{AWKPATH} specifies a search path to use when finding source files named with the @samp{-f} option. If the variable @code{AWKPATH} is not set, @code{gawk} uses the default path, @samp{.:/usr/lib/awk:/usr/local/lib/awk}. If a file name given to the @samp{-f} option contains a @samp{/} character, no path search is performed. @xref{AWKPATH Variable}, for a full description of the @code{AWKPATH} environment variable.@refill @code{gawk} compiles the program into an internal form, and then proceeds to read each file named in the @code{ARGV} array. If there are no files named on the command line, @code{gawk} reads the standard input. If a ``file'' named on the command line has the form @samp{@var{var}=@var{val}}, it is treated as a variable assignment: the variable @var{var} is assigned the value @var{val}. For each line in the input, @code{gawk} tests to see if it matches any @var{pattern} in the @code{awk} program. For each pattern that the line matches, the associated @var{action} is executed. @node Variables/Fields, Rules Summary, Language Summary, Gawk Summary @appendixsec Variables and Fields @code{awk} variables are dynamic; they come into existence when they are first used. Their values are either floating-point numbers or strings. @code{awk} also has one-dimension arrays; multiple-dimensional arrays may be simulated. There are several predefined variables that @code{awk} sets as a program runs; these are summarized below. @menu * Fields Summary:: Input field splitting. * Built-in Summary:: @code{awk}'s built-in variables. * Arrays Summary:: Using arrays. * Data Type Summary:: Values in @code{awk} are numbers or strings. @end menu @node Fields Summary, Built-in Summary, Variables/Fields, Variables/Fields @appendixsubsec Fields As each input line is read, @code{gawk} splits the line into @var{fields}, using the value of the @code{FS} variable as the field separator. If @code{FS} is a single character, fields are separated by that character. Otherwise, @code{FS} is expected to be a full regular expression. In the special case that @code{FS} is a single blank, fields are separated by runs of blanks and/or tabs. Note that the value of @code{IGNORECASE} (@pxref{Case-sensitivity}) also affects how fields are split when @code{FS} is a regular expression. Each field in the input line may be referenced by its position, @code{$1}, @code{$2}, and so on. @code{$0} is the whole line. The value of a field may be assigned to as well. Field numbers need not be constants: @example n = 5 print $n @end example @noindent prints the fifth field in the input line. The variable @code{NF} is set to the total number of fields in the input line. References to nonexistent fields (i.e., fields after @code{$NF}) return the null-string. However, assigning to a nonexistent field (e.g., @code{$(NF+2) = 5}) increases the value of @code{NF}, creates any intervening fields with the null string as their value, and causes the value of @code{$0} to be recomputed, with the fields being separated by the value of @code{OFS}.@refill @xref{Reading Files}, for a full description of the way @code{awk} defines and uses fields. @node Built-in Summary, Arrays Summary, Fields Summary, Variables/Fields @appendixsubsec Built-in Variables @code{awk}'s built-in variables are: @table @code @item ARGC The number of command line arguments (not including options or the @code{awk} program itself). @item ARGV The array of command line arguments. The array is indexed from 0 to @code{ARGC} - 1. Dynamically changing the contents of @code{ARGV} can control the files used for data.@refill @item ENVIRON An array containing the values of the environment variables. The array is indexed by variable name, each element being the value of that variable. Thus, the environment variable @code{HOME} would be in @code{ENVIRON["HOME"]}. Its value might be @file{/u/close}. Changing this array does not affect the environment seen by programs which @code{gawk} spawns via redirection or the @code{system} function. (This may change in a future version of @code{gawk}.) Some operating systems do not have environment variables. The array @code{ENVIRON} is empty when running on these systems. @item FILENAME The name of the current input file. If no files are specified on the command line, the value of @code{FILENAME} is @samp{-}. @item FNR The input record number in the current input file. @item FS The input field separator, a blank by default. @item IGNORECASE The case-sensitivity flag for regular expression operations. If @code{IGNORECASE} has a nonzero value, then pattern matching in rules, field splitting with @code{FS}, regular expression matching with @samp{~} and @samp{!~}, and the @code{gsub}, @code{index}, @code{match}, @code{split} and @code{sub} predefined functions all ignore case when doing regular expression operations.@refill @item NF The number of fields in the current input record. @item NR The total number of input records seen so far. @item OFMT The output format for numbers, @code{"%.6g"} by default. @item OFS The output field separator, a blank by default. @item ORS The output record separator, by default a newline. @item RS The input record separator, by default a newline. @code{RS} is exceptional in that only the first character of its string value is used for separating records. If @code{RS} is set to the null string, then records are separated by blank lines. When @code{RS} is set to the null string, then the newline character always acts as a field separator, in addition to whatever value @code{FS} may have.@refill @item RSTART The index of the first character matched by @code{match}; 0 if no match. @item RLENGTH The length of the string matched by @code{match}; @minus{}1 if no match. @item SUBSEP The string used to separate multiple subscripts in array elements, by default @code{"\034"}. @end table @xref{Built-in Variables}. @node Arrays Summary, Data Type Summary, Built-in Summary, Variables/Fields @appendixsubsec Arrays Arrays are subscripted with an expression between square brackets (@samp{[} and @samp{]}). The expression may be either a number or a string. Since arrays are associative, string indices are meaningful and are not converted to numbers. If you use multiple expressions separated by commas inside the square brackets, then the array subscript is a string consisting of the concatenation of the individual subscript values, converted to strings, separated by the subscript separator (the value of @code{SUBSEP}). The special operator @code{in} may be used in an @code{if} or @code{while} statement to see if an array has an index consisting of a particular value. @group @example if (val in array) print array[val] @end example @end group If the array has multiple subscripts, use @code{(i, j, @dots{}) in array} to test for existence of an element. The @code{in} construct may also be used in a @code{for} loop to iterate over all the elements of an array. @xref{Scanning an Array}. An element may be deleted from an array using the @code{delete} statement. @xref{Arrays}, for more detailed information. @node Data Type Summary, , Arrays Summary, Variables/Fields @appendixsubsec Data Types The value of an @code{awk} expression is always either a number or a string. Certain contexts (such as arithmetic operators) require numeric values. They convert strings to numbers by interpreting the text of the string as a numeral. If the string does not look like a numeral, it converts to 0. Certain contexts (such as concatenation) require string values. They convert numbers to strings by effectively printing them. To force conversion of a string value to a number, simply add 0 to it. If the value you start with is already a number, this does not change it. To force conversion of a numeric value to a string, concatenate it with the null string. The @code{awk} language defines comparisons as being done numerically if possible, otherwise one or both operands are converted to strings and a string comparison is performed. Uninitialized variables have the string value @code{""} (the null, or empty, string). In contexts where a number is required, this is equivalent to 0. @xref{Variables}, for more information on variable naming and initialization; @pxref{Conversion}, for more information on how variable values are interpreted.@refill @node Rules Summary, Functions Summary, Variables/Fields, Gawk Summary @appendixsec Patterns and Actions @menu * Pattern Summary:: Quick overview of patterns. * Regexp Summary:: Quick overview of regular expressions. * Actions Summary:: Quick overview of actions. @end menu An @code{awk} program is mostly composed of rules, each consisting of a pattern followed by an action. The action is enclosed in @samp{@{} and @samp{@}}. Either the pattern may be missing, or the action may be missing, but, of course, not both. If the pattern is missing, the action is executed for every single line of input. A missing action is equivalent to this action, @example @{ print @} @end example @noindent which prints the entire line. Comments begin with the @samp{#} character, and continue until the end of the line. Blank lines may be used to separate statements. Normally, a statement ends with a newline, however, this is not the case for lines ending in a @samp{,}, @samp{@{}, @samp{?}, @samp{:}, @samp{&&}, or @samp{||}. Lines ending in @code{do} or @code{else} also have their statements automatically continued on the following line. In other cases, a line can be continued by ending it with a @samp{\}, in which case the newline is ignored.@refill Multiple statements may be put on one line by separating them with a @samp{;}. This applies to both the statements within the action part of a rule (the usual case), and to the rule statements themselves. @xref{Comments}, for information on @code{awk}'s commenting convention; @pxref{Statements/Lines}, for a description of the line continuation mechanism in @code{awk}. @node Pattern Summary, Regexp Summary, Rules Summary, Rules Summary @appendixsubsec Patterns @code{awk} patterns may be one of the following: @example /@var{regular expression}/ @var{relational expression} @var{pattern} && @var{pattern} @var{pattern} || @var{pattern} @var{pattern} ? @var{pattern} : @var{pattern} (@var{pattern}) ! @var{pattern} @var{pattern1}, @var{pattern2} BEGIN END @end example @code{BEGIN} and @code{END} are two special kinds of patterns that are not tested against the input. The action parts of all @code{BEGIN} rules are merged as if all the statements had been written in a single @code{BEGIN} rule. They are executed before any of the input is read. Similarly, all the @code{END} rules are merged, and executed when all the input is exhausted (or when an @code{exit} statement is executed). @code{BEGIN} and @code{END} patterns cannot be combined with other patterns in pattern expressions. @code{BEGIN} and @code{END} rules cannot have missing action parts.@refill For @samp{/@var{regular-expression}/} patterns, the associated statement is executed for each input line that matches the regular expression. Regular expressions are the same as those in @code{egrep}, and are summarized below. A @var{relational expression} may use any of the operators defined below in the section on actions. These generally test whether certain fields match certain regular expressions. The @samp{&&}, @samp{||}, and @samp{!} operators are logical ``and'', logical ``or'', and logical ``not'', respectively, as in C. They do short-circuit evaluation, also as in C, and are used for combining more primitive pattern expressions. As in most languages, parentheses may be used to change the order of evaluation. The @samp{?:} operator is like the same operator in C. If the first pattern matches, then the second pattern is matched against the input record; otherwise, the third is matched. Only one of the second and third patterns is matched. The @samp{@var{pattern1}, @var{pattern2}} form of a pattern is called a range pattern. It matches all input lines starting with a line that matches @var{pattern1}, and continuing until a line that matches @var{pattern2}, inclusive. A range pattern cannot be used as an operand to any of the pattern operators. @xref{Patterns}, for a full description of the pattern part of @code{awk} rules. @node Regexp Summary, Actions Summary, Pattern Summary, Rules Summary @appendixsubsec Regular Expressions Regular expressions are the extended kind found in @code{egrep}. They are composed of characters as follows: @table @code @item @var{c} matches the character @var{c} (assuming @var{c} is a character with no special meaning in regexps). @item \@var{c} matches the literal character @var{c}. @item . matches any character except newline. @item ^ matches the beginning of a line or a string. @item $ matches the end of a line or a string. @item [@var{abc}@dots{}] matches any of the characters @var{abc}@dots{} (character class). @item [^@var{abc}@dots{}] matches any character except @var{abc}@dots{} and newline (negated character class). @item @var{r1}|@var{r2} matches either @var{r1} or @var{r2} (alternation). @item @var{r1r2} matches @var{r1}, and then @var{r2} (concatenation). @item @var{r}+ matches one or more @var{r}'s. @item @var{r}* matches zero or more @var{r}'s. @item @var{r}? matches zero or one @var{r}'s. @item (@var{r}) matches @var{r} (grouping). @end table @xref{Regexp}, for a more detailed explanation of regular expressions. The escape sequences allowed in string constants are also valid in regular expressions (@pxref{Constants}). @node Actions Summary, , Regexp Summary, Rules Summary @appendixsubsec Actions Action statements are enclosed in braces, @samp{@{} and @samp{@}}. Action statements consist of the usual assignment, conditional, and looping statements found in most languages. The operators, control statements, and input/output statements available are patterned after those in C. @menu * Operator Summary:: @code{awk} operators. * Control Flow Summary:: The control statements. * I/O Summary:: The I/O statements. * Printf Summary:: A summary of @code{printf}. * Special File Summary:: Special file names interpreted internally. * Numeric Functions Summary:: Built-in numeric functions. * String Functions Summary:: Built-in string functions. * String Constants Summary:: Escape sequences in strings. @end menu @node Operator Summary, Control Flow Summary, Actions Summary, Actions Summary @appendixsubsubsec Operators The operators in @code{awk}, in order of increasing precedence, are @table @code @item = += -= *= /= %= ^= Assignment. Both absolute assignment (@code{@var{var}=@var{value}}) and operator assignment (the other forms) are supported. @item ?: A conditional expression, as in C. This has the form @code{@var{expr1} ? @var{expr2} : @var{expr3}}. If @var{expr1} is true, the value of the expression is @var{expr2}; otherwise it is @var{expr3}. Only one of @var{expr2} and @var{expr3} is evaluated.@refill @item || Logical ``or''. @item && Logical ``and''. @item ~ !~ Regular expression match, negated match. @item < <= > >= != == The usual relational operators. @item @var{blank} String concatenation. @item + - Addition and subtraction. @item * / % Multiplication, division, and modulus. @item + - ! Unary plus, unary minus, and logical negation. @item ^ Exponentiation (@samp{**} may also be used, and @samp{**=} for the assignment operator). @item ++ -- Increment and decrement, both prefix and postfix. @item $ Field reference. @end table @xref{Expressions}, for a full description of all the operators listed above. @xref{Fields}, for a description of the field reference operator. @node Control Flow Summary, I/O Summary, Operator Summary, Actions Summary @appendixsubsubsec Control Statements The control statements are as follows: @example if (@var{condition}) @var{statement} @r{[} else @var{statement} @r{]} while (@var{condition}) @var{statement} do @var{statement} while (@var{condition}) for (@var{expr1}; @var{expr2}; @var{expr3}) @var{statement} for (@var{var} in @var{array}) @var{statement} break continue delete @var{array}[@var{index}] exit @r{[} @var{expression} @r{]} @{ @var{statements} @} @end example @xref{Statements}, for a full description of all the control statements listed above. @node I/O Summary, Printf Summary, Control Flow Summary, Actions Summary @appendixsubsubsec I/O Statements The input/output statements are as follows: @table @code @item getline Set @code{$0} from next input record; set @code{NF}, @code{NR}, @code{FNR}. @item getline <@var{file} Set @code{$0} from next record of @var{file}; set @code{NF}. @item getline @var{var} Set @var{var} from next input record; set @code{NF}, @code{FNR}. @item getline @var{var} <@var{file} Set @var{var} from next record of @var{file}. @item next Stop processing the current input record. The next input record is read and processing starts over with the first pattern in the @code{awk} program. If the end of the input data is reached, the @code{END} rule(s), if any, are executed. @item print Prints the current record. @item print @var{expr-list} Prints expressions. @item print @var{expr-list} > @var{file} Prints expressions on @var{file}. @item printf @var{fmt, expr-list} Format and print. @item printf @var{fmt, expr-list} > file Format and print on @var{file}. @end table Other input/output redirections are also allowed. For @code{print} and @code{printf}, @samp{>> @var{file}} appends output to the @var{file}, while @samp{| @var{command}} writes on a pipe. In a similar fashion, @samp{@var{command} | getline} pipes input into @code{getline}. @code{getline} returns 0 on end of file, and @minus{}1 on an error.@refill @xref{Getline}, for a full description of the @code{getline} statement. @xref{Printing}, for a full description of @code{print} and @code{printf}. Finally, @pxref{Next Statement}, for a description of how the @code{next} statement works.@refill @node Printf Summary, Special File Summary, I/O Summary, Actions Summary @appendixsubsubsec @code{printf} Summary The @code{awk} @code{printf} statement and @code{sprintf} function accept the following conversion specification formats: @table @code @item %c An ASCII character. If the argument used for @samp{%c} is numeric, it is treated as a character and printed. Otherwise, the argument is assumed to be a string, and the only first character of that string is printed. @item %d A decimal number (the integer part). @item %i Also a decimal integer. @item %e A floating point number of the form @samp{@r{[}-@r{]}d.ddddddE@r{[}+-@r{]}dd}.@refill @item %f A floating point number of the form @r{[}@code{-}@r{]}@code{ddd.dddddd}. @item %g Use @samp{%e} or @samp{%f} conversion, whichever is shorter, with nonsignificant zeros suppressed. @item %o An unsigned octal number (again, an integer). @item %s A character string. @item %x An unsigned hexadecimal number (an integer). @item %X Like @samp{%x}, except use @samp{A} through @samp{F} instead of @samp{a} through @samp{f} for decimal 10 through 15.@refill @item %% A single @samp{%} character; no argument is converted. @end table There are optional, additional parameters that may lie between the @samp{%} and the control letter: @table @code @item - The expression should be left-justified within its field. @item @var{width} The field should be padded to this width. If @var{width} has a leading zero, then the field is padded with zeros. Otherwise it is padded with blanks. @item .@var{prec} A number indicating the maximum width of strings or digits to the right of the decimal point. @end table @xref{Printf}, for examples and for a more detailed description. @node Special File Summary, Numeric Functions Summary, Printf Summary, Actions Summary @appendixsubsubsec Special File Names When doing I/O redirection from either @code{print} or @code{printf} into a file, or via @code{getline} from a file, @code{gawk} recognizes certain special file names internally. These file names allow access to open file descriptors inherited from @code{gawk}'s parent process (usually the shell). The file names are: @table @file @item /dev/stdin The standard input. @item /dev/stdout The standard output. @item /dev/stderr The standard error output. @item /dev/fd/@var{n} The file denoted by the open file descriptor @var{n}. @end table @noindent These file names may also be used on the command line to name data files. @xref{Special Files}, for a longer description that provides the motivation for this feature. @node Numeric Functions Summary, String Functions Summary, Special File Summary, Actions Summary @appendixsubsubsec Numeric Functions @code{awk} has the following predefined arithmetic functions: @table @code @item atan2(@var{y}, @var{x}) returns the arctangent of @var{y/x} in radians. @item cos(@var{expr}) returns the cosine in radians. @item exp(@var{expr}) the exponential function. @item int(@var{expr}) truncates to integer. @item log(@var{expr}) the natural logarithm function. @item rand() returns a random number between 0 and 1. @item sin(@var{expr}) returns the sine in radians. @item sqrt(@var{expr}) the square root function. @item srand(@var{expr}) use @var{expr} as a new seed for the random number generator. If no @var{expr} is provided, the time of day is used. The return value is the previous seed for the random number generator. @end table @node String Functions Summary, String Constants Summary, Numeric Functions Summary, Actions Summary @appendixsubsubsec String Functions @code{awk} has the following predefined string functions: @table @code @item gsub(@var{r}, @var{s}, @var{t}) for each substring matching the regular expression @var{r} in the string @var{t}, substitute the string @var{s}, and return the number of substitutions. If @var{t} is not supplied, use @code{$0}. @item index(@var{s}, @var{t}) returns the index of the string @var{t} in the string @var{s}, or 0 if @var{t} is not present. @item length(@var{s}) returns the length of the string @var{s}. @item match(@var{s}, @var{r}) returns the position in @var{s} where the regular expression @var{r} occurs, or 0 if @var{r} is not present, and sets the values of @code{RSTART} and @code{RLENGTH}. @item split(@var{s}, @var{a}, @var{r}) splits the string @var{s} into the array @var{a} on the regular expression @var{r}, and returns the number of fields. If @var{r} is omitted, @code{FS} is used instead. @item sprintf(@var{fmt}, @var{expr-list}) prints @var{expr-list} according to @var{fmt}, and returns the resulting string. @item sub(@var{r}, @var{s}, @var{t}) this is just like @code{gsub}, but only the first matching substring is replaced. @item substr(@var{s}, @var{i}, @var{n}) returns the @var{n}-character substring of @var{s} starting at @var{i}. If @var{n} is omitted, the rest of @var{s} is used. @item tolower(@var{str}) returns a copy of the string @var{str}, with all the upper-case characters in @var{str} translated to their corresponding lower-case counterparts. Nonalphabetic characters are left unchanged. @item toupper(@var{str}) returns a copy of the string @var{str}, with all the lower-case characters in @var{str} translated to their corresponding upper-case counterparts. Nonalphabetic characters are left unchanged. @item system(@var{cmd-line}) Execute the command @var{cmd-line}, and return the exit status. @end table @xref{Built-in}, for a description of all of @code{awk}'s built-in functions. @node String Constants Summary, , String Functions Summary, Actions Summary @appendixsubsubsec String Constants String constants in @code{awk} are sequences of characters enclosed between double quotes (@code{"}). Within strings, certain @dfn{escape sequences} are recognized, as in C. These are: @table @code @item \\ A literal backslash. @item \a The ``alert'' character; usually the ASCII BEL character. @item \b Backspace. @item \f Formfeed. @item \n Newline. @item \r Carriage return. @item \t Horizontal tab. @item \v Vertical tab. @item \x@var{hex digits} The character represented by the string of hexadecimal digits following the @samp{\x}. As in ANSI C, all following hexadecimal digits are considered part of the escape sequence. (This feature should tell us something about language design by committee.) E.g., @code{"\x1B"} is a string containing the ASCII ESC (escape) character. @item \@var{ddd} The character represented by the 1-, 2-, or 3-digit sequence of octal digits. Thus, @code{"\033"} is also a string containing the ASCII ESC (escape) character. @item \@var{c} The literal character @var{c}. @end table The escape sequences may also be used inside constant regular expressions (e.g., the regexp @code{@w{/[@ \t\f\n\r\v]/}} matches whitespace characters).@refill @xref{Constants}. @node Functions Summary, , Rules Summary, Gawk Summary @appendixsec Functions Functions in @code{awk} are defined as follows: @example function @var{name}(@var{parameter list}) @{ @var{statements} @} @end example Actual parameters supplied in the function call are used to instantiate the formal parameters declared in the function. Arrays are passed by reference, other variables are passed by value. If there are fewer arguments passed than there are names in @var{parameter-list}, the extra names are given the null string as value. Extra names have the effect of local variables. The open-parenthesis in a function call must immediately follow the function name, without any intervening white space. This is to avoid a syntactic ambiguity with the concatenation operator. The word @code{func} may be used in place of @code{function}. @xref{User-defined}, for a more complete description. @node Sample Program, Notes, Gawk Summary, Top @appendix Sample Program The following example is a complete @code{awk} program, which prints the number of occurrences of each word in its input. It illustrates the associative nature of @code{awk} arrays by using strings as subscripts. It also demonstrates the @samp{for @var{x} in @var{array}} construction. Finally, it shows how @code{awk} can be used in conjunction with other utility programs to do a useful task of some complexity with a minimum of effort. Some explanations follow the program listing.@refill @example awk ' # Print list of word frequencies @{ for (i = 1; i <= NF; i++) freq[$i]++ @} END @{ for (word in freq) printf "%s\t%d\n", word, freq[word] @}' @end example The first thing to notice about this program is that it has two rules. The first rule, because it has an empty pattern, is executed on every line of the input. It uses @code{awk}'s field-accessing mechanism (@pxref{Fields}) to pick out the individual words from the line, and the built-in variable @code{NF} (@pxref{Built-in Variables}) to know how many fields are available. For each input word, an element of the array @code{freq} is incremented to reflect that the word has been seen an additional time.@refill The second rule, because it has the pattern @code{END}, is not executed until the input has been exhausted. It prints out the contents of the @code{freq} table that has been built up inside the first action.@refill Note that this program has several problems that would prevent it from being useful by itself on real text files:@refill @itemize @bullet @item Words are detected using the @code{awk} convention that fields are separated by whitespace and that other characters in the input (except newlines) don't have any special meaning to @code{awk}. This means that punctuation characters count as part of words.@refill @item The @code{awk} language considers upper and lower case characters to be distinct. Therefore, @samp{foo} and @samp{Foo} are not treated by this program as the same word. This is undesirable since in normal text, words are capitalized if they begin sentences, and a frequency analyzer should not be sensitive to that.@refill @item The output does not come out in any useful order. You're more likely to be interested in which words occur most frequently, or having an alphabetized table of how frequently each word occurs.@refill @end itemize The way to solve these problems is to use other system utilities to process the input and output of the @code{awk} script. Suppose the script shown above is saved in the file @file{frequency.awk}. Then the shell command:@refill @example tr A-Z a-z < file1 | tr -cd 'a-z\012' \ | awk -f frequency.awk \ | sort +1 -nr @end example @noindent produces a table of the words appearing in @file{file1} in order of decreasing frequency. The first @code{tr} command in this pipeline translates all the upper case characters in @file{file1} to lower case. The second @code{tr} command deletes all the characters in the input except lower case characters and newlines. The second argument to the second @code{tr} is quoted to protect the backslash in it from being interpreted by the shell. The @code{awk} program reads this suitably massaged data and produces a word frequency table, which is not ordered. The @code{awk} script's output is now sorted by the @code{sort} command and printed on the terminal. The options given to @code{sort} in this example specify to sort by the second field of each input line (skipping one field), that the sort keys should be treated as numeric quantities (otherwise @samp{15} would come before @samp{5}), and that the sorting should be done in descending (reverse) order.@refill See the general operating system documentation for more information on how to use the @code{tr} and @code{sort} commands.@refill @ignore @strong{ADR: I have some more substantial programs courtesy of Rick Adams at UUNET. I am planning on incorporating those either in addition to or instead of this program.} @strong{I would also like to incorporate the general @code{translate} function that I have written.} @end ignore @node Notes, Glossary, Sample Program, Top @appendix Implementation Notes This appendix contains information mainly of interest to implementors and maintainers of @code{gawk}. Everything in it applies specifically to @code{gawk}, and not to other implementations. @menu * Compatibility Mode:: How to disable certain @code{gawk} extensions. * Future Extensions:: New features we may implement soon. * Improvements:: Suggestions for improvements by volunteers. @end menu @node Compatibility Mode, Future Extensions, Notes, Notes @appendixsec Downwards Compatibility and Debugging @xref{S5R4/GNU}, for a summary of the GNU extensions to the @code{awk} language and program. All of these features can be turned off either by compiling @code{gawk} with @samp{-DSTRICT} (not recommended), or by invoking @code{gawk} with the @samp{-c} option.@refill If @code{gawk} is compiled for debugging with @samp{-DDEBUG}, then there are two more options available on the command line. @table @samp @item -d Print out debugging information during execution. @item -D Print out the parse stack information as the program is being parsed. @end table Both of these options are intended only for serious @code{gawk} developers, and not for the casual user. They probably have not even been compiled into your version of @code{gawk}, since they slow down execution. The code for recognizing special file names such as @file{/dev/stdin} can be disabled at compile time with @samp{-DNO_DEV_FD}, or with @samp{-DSTRICT}.@refill @node Future Extensions, Improvements, Compatibility Mode, Notes @appendixsec Probable Future Extensions This section briefly lists extensions that indicate the directions we are currently considering for @code{gawk}. @table @asis @item ANSI C compatible @code{printf} The @code{printf} and @code{sprintf} functions may be enhanced to be fully compatible with the specification for the @code{printf} family of functions in ANSI C.@refill @item @code{RS} as a regexp The meaning of @code{RS} may be generalized along the lines of @code{FS}. @item Control of subprocess environment Changes made in @code{gawk} to the array @code{ENVIRON} may be propagated to subprocesses run by @code{gawk}. @item Data bases It may be possible to map an NDBM/GDBM file into an @code{awk} array. @item Single-character fields The null string, @code{""}, as a field separator, will cause field splitting and the split function to separate individual characters. Thus, @code{split(a, "abcd", "")} would yield @code{a[1] == "a"}, @code{a[2] == "b"}, and so on. @item Fixed-length fields and records A mechanism may be provided to allow the specification of fixed length fields and records. @item Regexp syntax The @code{egrep} syntax for regular expressions, now specified with the @samp{-e} option, may become the default, since the POSIX standard may specify this. @c this is @emph{very} long term --- not worth including right now. @ignore @item The C Comma Operator We may add the C comma operator, which takes the form @code{@var{expr1},@var{expr2}}. The first expression is evaluated, and the result is thrown away. The value of the full expression is the value of @var{expr2}.@refill @end ignore @end table @node Improvements,, Future Extensions, Notes @appendixsec Suggestions for Improvements Here are some projects that would-be @code{gawk} hackers might like to take on. They vary in size from a few days to a few weeks of programming, depending on which one you choose and how fast a programmer you are. Please send any improvements you write to the maintainers at the GNU project.@refill @enumerate @item State machine regexp matcher: At present, @code{gawk} uses the backtracking regular expression matcher from the GNU subroutine library. If a regexp is really going to be used a lot of times, it is faster to convert it once to a description of a finite state machine, then run a routine simulating that machine every time you want to match the regexp. You might be able to use the matching routines used by GNU @code{egrep}. @item Compilation of @code{awk} programs: @code{gawk} uses a Bison (YACC-like) parser to convert the script given it into a syntax tree; the syntax tree is then executed by a simple recursive evaluator. Both of these steps incur a lot of overhead, since parsing can be slow (especially if you also do the previous project and convert regular expressions to finite state machines at compile time) and the recursive evaluator performs many procedure calls to do even the simplest things.@refill It should be possible for @code{gawk} to convert the script's parse tree into a C program which the user would then compile, using the normal C compiler and a special @code{gawk} library to provide all the needed functions (regexps, fields, associative arrays, type coercion, and so on).@refill An easier possibility might be for an intermediate phase of @code{awk} to convert the parse tree into a linear byte code form like the one used in GNU Emacs Lisp. The recursive evaluator would then be replaced by a straight line byte code interpreter that would be intermediate in speed between running a compiled program and doing what @code{gawk} does now.@refill @item An error message section has not been included in this version of the manual. Perhaps some nice beta testers will document some of the messages for the future. @end enumerate @node Glossary, Index , Notes, Top @appendix Glossary @table @asis @item Action A series of @code{awk} statements attached to a rule. If the rule's pattern matches an input record, the @code{awk} language executes the rule's action. Actions are always enclosed in curly braces. @xref{Actions}.@refill @item Amazing @code{awk} Assembler Henry Spencer at the University of Toronto wrote a retargetable assembler completely as @code{awk} scripts. It is thousands of lines long, including machine descriptions for several 8-bit microcomputers. It is distributed with @code{gawk} and is a good example of a program that would have been better written in another language.@refill @item Assignment An @code{awk} expression that changes the value of some @code{awk} variable or data object. An object that you can assign to is called an @dfn{lvalue}. @xref{Assignment Ops}.@refill @item @code{awk} Language The language in which @code{awk} programs are written. @item @code{awk} Program An @code{awk} program consists of a series of @dfn{patterns} and @dfn{actions}, collectively known as @dfn{rules}. For each input record given to the program, the program's rules are all processed in turn. @code{awk} programs may also contain function definitions.@refill @item @code{awk} Script Another name for an @code{awk} program. @item Built-in Function The @code{awk} language provides built-in functions that perform various numerical and string computations. Examples are @code{sqrt} (for the square root of a number) and @code{substr} (for a substring of a string). @xref{Built-in}.@refill @item Built-in Variable The variables @code{ARGC}, @code{ARGV}, @code{ENVIRON}, @code{FILENAME}, @code{FNR}, @code{FS}, @code{NF}, @code{IGNORECASE}, @code{NR}, @code{OFMT}, @code{OFS}, @code{ORS}, @code{RLENGTH}, @code{RSTART}, @code{RS}, and @code{SUBSEP}, have special meaning to @code{awk}. Changing some of them affects @code{awk}'s running environment. @xref{Built-in Variables}.@refill @item C The system programming language that most GNU software is written in. The @code{awk} programming language has C-like syntax, and this manual points out similarities between @code{awk} and C when appropriate.@refill @item Compound Statement A series of @code{awk} statements, enclosed in curly braces. Compound statements may be nested. @xref{Statements}.@refill @item Concatenation Concatenating two strings means sticking them together, one after another, giving a new string. For example, the string @samp{foo} concatenated with the string @samp{bar} gives the string @samp{foobar}. @xref{Concatenation}.@refill @item Conditional Expression An expression using the @samp{?:} ternary operator, such as @code{@var{expr1} ? @var{expr2} : @var{expr3}}. The expression @var{expr1} is evaluated; if the result is true, the value of the whole expression is the value of @var{expr2} otherwise the value is @var{expr3}. In either case, only one of @var{expr2} and @var{expr3} is evaluated. @xref{Conditional Exp}.@refill @item Constant Regular Expression A constant regular expression is a regular expression written within slashes, such as @samp{/foo/}. This regular expression is chosen when you write the @code{awk} program, and cannot be changed doing its execution. @xref{Regexp Usage}. @item Comparison Expression A relation that is either true or false, such as @code{(a < b)}. Comparison expressions are used in @code{if} and @code{while} statements, and in patterns to select which input records to process. @xref{Comparison Ops}.@refill @item Curly Braces The characters @samp{@{} and @samp{@}}. Curly braces are used in @code{awk} for delimiting actions, compound statements, and function bodies.@refill @item Data Objects These are numbers and strings of characters. Numbers are converted into strings and vice versa, as needed. @xref{Conversion}.@refill @item Dynamic Regular Expression A dynamic regular expression is a regular expression written as an ordinary expression. It could be a string constant, such as @code{"foo"}, but it may also be an expression whose value may vary. @xref{Regexp Usage}. @item Escape Sequences A special sequence of characters used for describing nonprinting characters, such as @samp{\n} for newline, or @samp{\033} for the ASCII ESC (escape) character. @xref{Constants}. @item Field When @code{awk} reads an input record, it splits the record into pieces separated by whitespace (or by a separator regexp which you can change by setting the built-in variable @code{FS}). Such pieces are called fields. @xref{Records}.@refill @item Format Format strings are used to control the appearance of output in the @code{printf} statement. Also, data conversions from numbers to strings are controlled by the format string contained in the built-in variable @code{OFMT}. @xref{Control Letters}; also @pxref{Output Separators}.@refill @item Function A specialized group of statements often used to encapsulate general or program-specific tasks. @code{awk} has a number of built-in functions, and also allows you to define your own. @xref{Built-in}; also @pxref{User-defined}. @item @code{gawk} The GNU implementation of @code{awk}. @item Input Record A single chunk of data read in by @code{awk}. Usually, an @code{awk} input record consists of one line of text. @xref{Records}.@refill @item Keyword In the @code{awk} language, a keyword is a word that has special meaning. Keywords are reserved and may not be used as variable names. The keywords of @code{awk} are: @code{if}, @code{else}, @code{while}, @code{do@dots{}while}, @code{for}, @code{for@dots{}in}, @code{break}, @code{continue}, @code{delete}, @code{next}, @code{function}, @code{func}, and @code{exit}.@refill @item Lvalue An expression that can appear on the left side of an assignment operator. In most languages, lvalues can be variables or array elements. In @code{awk}, a field designator can also be used as an lvalue.@refill @item Number A numeric valued data object. The @code{gawk} implementation uses double precision floating point to represent numbers.@refill @item Pattern Patterns tell @code{awk} which input records are interesting to which rules. A pattern is an arbitrary conditional expression against which input is tested. If the condition is satisfied, the pattern is said to @dfn{match} the input record. A typical pattern might compare the input record against a regular expression. @xref{Patterns}.@refill @item Range (of input lines) A sequence of consecutive lines from the input file. A pattern can specify ranges of input lines for @code{awk} to process, or it can specify single lines. @xref{Patterns}.@refill @item Recursion When a function calls itself, either directly or indirectly. If this isn't clear, refer to the entry for ``recursion''. @item Redirection Redirection means performing input from other than the standard input stream, or output to other than the standard output stream. You can redirect the output of the @code{print} and @code{printf} statements to a file or a system command, using the @samp{>}, @samp{>>}, and @samp{|} operators. You can redirect input to the @code{getline} statement using the @samp{<} and @samp{|} operators. @xref{Redirection}.@refill @item Regular Expression See ``regexp''. @item Regexp Short for @dfn{regular expression}. A regexp is a pattern that denotes a set of strings, possibly an infinite set. For example, the regexp @samp{R.*xp} matches any string starting with the letter @samp{R} and ending with the letters @samp{xp}. In @code{awk}, regexps are used in patterns and in conditional expressions. Regexps may contain escape sequences. @xref{Regexp}.@refill @item Rule A segment of an @code{awk} program, that specifies how to process single input records. A rule consists of a @dfn{pattern} and an @dfn{action}. @code{awk} reads an input record; then, for each rule, if the input record satisfies the rule's pattern, @code{awk} executes the rule's action. Otherwise, the rule does nothing for that input record.@refill @item Side Effect A side effect occurs when an expression has an effect aside from merely producing a value. Assignment expressions, increment expressions and function calls have side effects. @xref{Assignment Ops}. @item Special File A file name interpreted internally by @code{gawk}, instead of being handed directly to the underlying operating system. For example, @file{/dev/stdin}. @xref{Special Files}. @item Stream Editor A program that reads records from an input stream and processes them one or more at a time. This is in contrast with batch programs, which may expect to read their input files in entirety before starting to do anything, and with interactive programs, which require input from the user.@refill @item String A datum consisting of a sequence of characters, such as @samp{I am a string}. Constant strings are written with double-quotes in the @code{awk} language, and may contain @dfn{escape sequences}. @xref{Constants}. @item Whitespace A sequence of blank or tab characters occurring inside an input record or a string.@refill @end table @node Index, , Glossary, Top @unnumbered Index @printindex cp @summarycontents @contents @bye gawk-2.11/CHANGES 644 11660 0 15417 4527633555 11607 0ustar hackwheelChanges from 2.11beta to 2.11.1 (production) -------------------------------------------- Went from "beta" to production status!!! Now flushes stdout before closing pipes or redirected files to synchonize output. MS-DOS changes added in. Signal handler return type parameterized in Makefile and awk.h and some lint removed. debug.c cleaned up. Fixed FS splitting to never match null strings, per book. Correction to the manual's description of FS. Some compilers break on char *foo = "string" + 4 so fixed version.sh and main.c. Changes from 2.10beta to 2.11beta --------------------------------- This release fixes all reported bugs that we could reproduce. Probably some of the changes are not documented here. The next release will probably not be a beta release! The most important change is the addition of the -nostalgia option. :-) The documentation has been improved and brought up-to-date. There has been a lot of general cleaning up of the code that is not otherwise documented here. There has been a movement toward using standard-conforming library routines and providing them (in missing.d) for systems lacking them. Improved (hopefully) configuration through Makfile modifications and missing.c. In particular, straightened out confusion over vprintf #defines, declarations etc. Deleted RCS log comments from source, to reduce source size by about one third. Most of them were horribly out-of-date, anyway. Renamed source files to reflect (for the most part) their contents. More and improved error messages. Cleanup and fixes to yyerror(). String constants are not altered in input buffer, so error messages come out better. Fixed usage message. Make use of ANSI C strerror() function (provided). Plugged many more memory leaks. The memory consumption is now quite reasonable over a wide range of programs. Uses volatile declaration if STDC > 0 to avoid problems due to longjmp. New -a and -e options to use awk or egrep style regexps, respectively, since POSIX says awk should use egrep regexps. Default is -a. Added -v option for setting variables before the first file is encountered. Version information now uses -V and copyleft uses -C. Added a patchlevel.h file and its use for -V and -C. Append_right() optimized for major improvement to programs with a *lot* of statements. Operator precedence has been corrected to match draft Posix. Tightened up grammar for builtin functions so that only length may be called without arguments or parentheses. /regex/ is now a normal expression that can appear in any expression context. Allow /= to begin a regexp. Allow ..[../..].. in a regexp. Allow empty compound statements ({}). Made return and next illegal outside a function and in BEGIN/END respectively. Division by zero is now illegal and causes a fatal error. Fixed exponentiation so that x ^ 0 and x ^= 0 both return 1. Fixed do_sqrt, do_log, and do_exp to do argument/return checking and print an error message, per the manual. Fixed main to catch SIGSEGV to get source and data file line numbers. Fixed yyerror to print the ^ at the beginning of the bad token, not the end. Fix to substr() builtin: it was failing if the arguments weren't already strings. Added new node value flag NUMERIC to indicate that a variable is purely a number as opposed to type NUM which indicates that the node's numeric value is valid. This is set in make_number(), tmp_number and r_force_number() when appropriate and used in cmp_nodes(). This fixed a bug in comparison of variables that had numeric prefixes. The new code uses strtod() and eliminates is_a_number(). A simple strtod() is provided for systems lacking one. It does no overflow checking, so could be improved. Simplification and efficiency improvement in force_string. Added performance tweak in r_force_number(). Fixed a bug with nested loops and break/continue in functions. Fixed inconsistency in handling of empty fields when $0 has to be rebuilt. Happens to simplify rebuild_record(). Cleaned up the code associated with opening a pipe for reading. Gawk now has its own popen routine (gawk_popen) that allocates an IOBUF and keeps track of the pid of the child process. gawk_pclose marks the appropriate child as defunct in the right struct redirect. Cleaned up and fixed close_redir(). Fixed an obscure bug to do with redirection. Intermingled ">" and ">>" redirects did not output in a predictable order. Improved handling of output bufferring: now all print[f]s redirected to a tty or pipe are flushed immediately and non-redirected output to a tty is flushed before the next input record is read. Fixed a bug in get_a_record() where bcopy() could have copied over a random pointer. Fixed a bug when RS="" and records separated by multiple blank lines. Got rid of SLOWIO code which was out-of-date anyway. Fix in get_field() for case where $0 is changed and then $(n) are changed and then $0 is used. Fixed infinite loop on failure to open file for reading from getline. Now handles redirect file open failures properly. Filenames such as /dev/stdin now allowed on the command line as well as in redirects. Fixed so that gawk '$1' where $1 is a zero tests false. Fixed parsing so that `RLENGTH -1' parses the same as `RLENGTH - 1', for example. The return from a user-defined function now defaults to the Null node. This fixes a core-dump-causing bug when the return value of a function is used and that function returns no value. Now catches floating point exceptions to avoid core dumps. Bug fix for deleting elements of an array -- under some conditions, it was deleting more than one element at a time. Fix in AWKPATH code for running off the end of the string. Fixed handling of precision in *printf calls. %0.2d now works properly, as does %c. [s]printf now recognizes %i and %X. Fixed a bug in printing of very large (>240) strings. Cleaned up erroneous behaviour for RS == "". Added IGNORECASE support to index(). Simplified and fixed newnode/freenode. Fixed reference to $(anything) in a BEGIN block. Eliminated use of USG rand48(). Bug fix in force_string for machines with 16-bit ints. Replaced use of mktemp() with tmpnam() and provided a partial implementation of the latter for systems that don't have it. Added a portability check for includes in io.c. Minor portability fix in alloc.c plus addition of xmalloc(). Portability fix: on UMAX4.2, st_blksize is zero for a pipe, thus breaking iop_alloc() -- fixed. Workaround for compiler bug on Sun386i in do_sprintf. More and improved prototypes in awk.h. Consolidated C escape parsing code into one place. strict flag is now turned on only when invoked with compatability option. It now applies to fewer things. Changed cast of f._ptr in vprintf.c from (unsigned char *) to (char *). Hopefully this is right for the systems that use this code (I don't). Support for pipes under MSDOS added. gawk-2.11/COPYING 644 11660 0 30310 4414720166 11622 0ustar hackwheel GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! gawk-2.11/FUTURES 644 11660 0 1053 4521076634 11634 0ustar hackwheelThis file lists future projects and enhancments for gawk. Synchronize alloca.[cs] and regex.[ch] with the latest versions at GNU. (this will likely be done as a patch to 2.11.) Convert yylex() to allow arbitrary-length program lines. Allow OFMT to be other than a floating point format. Make printf fully compatible with the ANSI C spec. Make it faster and smaller. Allow RS to be a regexp. Read in environment only if necessary. (Is this all that big a deal?) Use faster regex algorithms. Create a gawk-to-C translator? Create a gawk compiler? gawk-2.11/Makefile 644 11660 0 16466 4527633556 12262 0ustar hackwheel# Makefile for GNU Awk. # # Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. # # This file is part of GAWK, the GNU implementation of the # AWK Progamming Language. # # GAWK is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 1, or (at your option) # any later version. # # GAWK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GAWK; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # User tunable macros # CFLAGS: options to the C compiler # # -O optimize # -g include dbx/sdb info # -gg include gdb debugging info; only for GCC (deprecated) # -pg include new (gmon) profiling info # -p include old style profiling info (System V) # # To port GAWK, examine and adjust the following flags carefully. # In addition, you will have to look at alloca below. # The intent (eventual) is to not penalize the most-standard-conforming # systems with a lot of #define's. # # -DBCOPY_MISSING - bcopy() et al. are missing; will replace # with a #define'd memcpy() et al. -- use at # your own risk (should really use a memmove()) # -DSPRINTF_INT - sprintf() returns int (most USG systems) # -DBLKSIZE_MISSING - st_blksize missing from stat() structure # (most USG systems) # -DBSDSTDIO - has a BSD internally-compatible stdio # -DDOPRNT_MISSING - lacks doprnt() routine # -DDUP2_MISSING - lacks dup2() system call (S5Rn, n < 4) # -DGCVT_MISSING - lacks gcvt() routine # -DGETOPT_MISSING - lacks getopt() routine # -DMEMCMP_MISSING - lacks memcmp() routine # -DMEMCPY_MISSING - lacks memcpy() routine # -DMEMSET_MISSING - lacks memset() routine # -DRANDOM_MISSING - lacks random() routine # -DSTRCASE_MISSING - lacks strcasecmp() routine # -DSTRCHR_MISSING - lacks strchr() and strrchr() routines # -DSTRERROR_MISSING - lacks (ANSI C) strerror() routine # -DSTRTOD_MISSING - lacks strtod() routine # -DTMPNAM_MISSING - lacks or deficient tmpnam() routine # -DVPRINTF_MISSING - lacks vprintf and associated routines # -DSIGTYPE=int - signal routines return int (default void) # Sun running SunOS 4.x MISSING = -DSTRERROR_MISSING -DSTRCASE_MISSING # SGI Personal Iris (Sys V derived) # MISSING = -DSPRINTF_INT -DBLKSIZE_MISSING -DSTRERROR_MISSING -DRANDOM_MISSING # VAX running Ultrix 3.x # MISSING = -DSTRERROR_MISSING # A generic 4.2 BSD machine # (eliminate GETOPT_MISSING for 4.3 release) # (eliminate STRCASE_MISSING and TMPNAM_MISSING for Tahoe release) # MISSING = -DBSDSTDIO -DMEMCMP_MISSING -DMEMCPY_MISSING -DMEMSET_MISSING \ # -DSTRERROR_MISSING -DSTRTOD_MISSING -DVPRINTF_MISSING \ # -DSTRCASE_MISSING -DTMPNAM_MISSING \ # -DGETOPT_MISSING -DSTRCHR_MISSING -DSIGTYPE=int # On Amdahl UTS, a SysVr2-derived system # MISSING = -DBCOPY_MISSING -DSPRINTF_INT -DRANDOM_MISSING -DSTRERROR_MISSING \ # -DSTRCASE_MISSING -DDUP2_MISSING # -DBLKSIZE_MISSING ?????? # Comment out the next line if you don't have gcc. # Also choose just one of -g and -O. CC= gcc OPTIMIZE= -O -g PROFILE= #-pg DEBUG= #-DDEBUG #-DMEMDEBUG #-DFUNC_TRACE #-DMPROF DEBUGGER= #-g -Bstatic WARN= #-W -Wunused -Wimplicit -Wreturn-type -Wcomment # for gcc only # Parser to use on grammar -- if you don't have bison use the first one #PARSER = yacc PARSER = bison # ALLOCA # Set equal to alloca.o if your system is S5 and you don't have # alloca. Uncomment one of the rules below to make alloca.o from # either alloca.s or alloca.c. ALLOCA= #alloca.o # # With the exception of the alloca rule referred to above, you shouldn't # need to customize this file below this point. # FLAGS= $(MISSING) $(DEBUG) CFLAGS= $(FLAGS) $(DEBUGGER) $(PROFILE) $(OPTIMIZE) $(WARN) # object files AWKOBJS = main.o eval.o builtin.o msg.o debug.o io.o field.o array.o node.o \ version.o missing.o ALLOBJS = $(AWKOBJS) awk.tab.o # GNUOBJS # GNU stuff that gawk uses as library routines. GNUOBJS= regex.o $(ALLOCA) # source and documentation files SRC = main.c eval.c builtin.c msg.c \ debug.c io.c field.c array.c node.c missing.c ALLSRC= $(SRC) awk.tab.c AWKSRC= awk.h awk.y $(ALLSRC) version.sh patchlevel.h GNUSRC = alloca.c alloca.s regex.c regex.h COPIES = missing.d/dup2.c missing.d/gcvt.c missing.d/getopt.c \ missing.d/memcmp.c missing.d/memcpy.c missing.d/memset.c \ missing.d/random.c missing.d/strcase.c missing.d/strchr.c \ missing.d/strerror.c missing.d/strtod.c missing.d/tmpnam.c \ missing.d/vprintf.c SUPPORT = support/texindex.c support/texinfo.tex DOCS= gawk.1 gawk.texinfo INFOFILES= gawk-info gawk-info-1 gawk-info-2 gawk-info-3 gawk-info-4 \ gawk-info-5 gawk-info-6 gawk.aux gawk.cp gawk.cps gawk.fn \ gawk.fns gawk.ky gawk.kys gawk.pg gawk.pgs gawk.toc \ gawk.tp gawk.tps gawk.vr gawk.vrs MISC = CHANGES COPYING FUTURES Makefile PROBLEMS README PCSTUFF= pc.d/Makefile.pc pc.d/popen.c pc.d/popen.h ALLDOC= gawk.dvi $(INFOFILES) ALLFILES= $(AWKSRC) $(GNUSRC) $(COPIES) $(MISC) $(DOCS) $(ALLDOC) $(PCSTUFF) $(SUPPORT) # Release of gawk. There can be no leading or trailing white space here! REL=2.11 # rules to build gawk gawk: $(ALLOBJS) $(GNUOBJS) $(CC) -o gawk $(CFLAGS) $(ALLOBJS) $(GNUOBJS) -lm $(AWKOBJS): awk.h main.o: patchlevel.h awk.tab.o: awk.h awk.tab.c awk.tab.c: awk.y $(PARSER) -v awk.y -mv -f y.tab.c awk.tab.c version.c: version.sh sh version.sh $(REL) > version.c # Alloca: uncomment this if your system (notably System V boxen) # does not have alloca in /lib/libc.a # #alloca.o: alloca.s # /lib/cpp < alloca.s | sed '/^#/d' > t.s # as t.s -o alloca.o # rm t.s # If your machine is not supported by the assembly version of alloca.s, # use the C version instead. This uses the default rules to make alloca.o. # #alloca.o: alloca.c # auxiliary rules for release maintenance lint: $(ALLSRC) lint -hcbax $(FLAGS) $(ALLSRC) xref: cxref -c $(FLAGS) $(ALLSRC) | grep -v ' /' >xref clean: rm -f gawk *.o core awk.output awk.tab.c gmon.out make.out version.c clobber: clean rm -f $(ALLDOC) gawk.log gawk.dvi: gawk.texinfo tex gawk.texinfo ; texindex gawk.?? tex gawk.texinfo ; texindex gawk.?? tex gawk.texinfo $(INFOFILES): gawk.texinfo makeinfo gawk.texinfo srcrelease: $(AWKSRC) $(GNUSRC) $(DOCS) $(MISC) $(COPIES) $(PCSTUFF) $(SUPPORT) -mkdir gawk-$(REL) cp -p $(AWKSRC) $(GNUSRC) $(DOCS) $(MISC) gawk-$(REL) -mkdir gawk-$(REL)/missing.d cp -p $(COPIES) gawk-$(REL)/missing.d -mkdir gawk-$(REL)/pc.d cp -p $(PCSTUFF) gawk-$(REL)/pc.d -mkdir gawk-$(REL)/support cp -p $(SUPPORT) gawk-$(REL)/support tar -cf - gawk-$(REL) | compress > gawk-$(REL).tar.Z docrelease: $(ALLDOC) -mkdir gawk-$(REL)-doc cp -p $(INFOFILES) gawk.dvi gawk-$(REL)-doc nroff -man gawk.1 > gawk-$(REL)-doc/gawk.1.pr tar -cf - gawk-$(REL)-doc | compress > gawk-doc-$(REL).tar.Z psrelease: docrelease -mkdir gawk-postscript dvi2ps gawk.dvi > gawk-postscript/gawk.postscript psroff -t -man gawk.1 > gawk-postscript/gawk.1.ps tar -cf - gawk-postscript | compress > gawk.postscript.tar.Z release: srcrelease docrelease psrelease rm -fr gawk-postscript gawk-$(REL) gawk-$(REL)-doc diff: for i in RCS/*; do rcsdiff -c -b $$i > `basename $$i ,v`.diff; done gawk-2.11/PROBLEMS 644 11660 0 574 4476306337 11716 0ustar hackwheelThis is a list of known problems in gawk 2.11. Hopefully they will all be fixed in the next major release of gawk. Please keep in mind that this is still beta software and the code is still undergoing significant evolution. 1. The debugging code does not print redirection info. 2. The scanner needs work. 3. Gawk's printf doesn't yet match the latest nawk's. Arnold Robbins gawk-2.11/README 644 11660 0 10632 4527633557 11470 0ustar hackwheelREADME: This is GNU Awk 2.11. It should be upwardly compatible with the System V Release 4 awk. This release is essentially a bug fix release. The files have been renamed and code moved around to organize things by function. Gawk should also be somewhat faster now. More care has been given towards portability across different Unix systems. See the installation instructions, below. Known problems are given in the PROBLEMS file. Work to be done is described briefly in the FUTURES file. The gawk.texinfo included in this release has been revised; it should be in sync with what the code does. The man page should also be accurate, but no promises there. CHANGES FROM 2.10 User visible changes: Compatibility mode is now obtained via new -c option. The new ANSI C \a and \x escapes are now a standard part of gawk as Unix nawk has picked them up. The new tolower() and toupper() functions are also standard. A new undocumented option, -nostalgia, has been added. Command line options have changed somewhat from 2.10. -v is now -V -V is now -C new -v for doing variable assignments before the BEGIN block. new -c for compatibility mode. new -a for awk style regexps (default) new -e for egrep style regexps, per the POSIX draft spec. Some more formats have been added to printf, ala nawk and ANSI C. Other changes (the hard stuff): All known bugs fixed. Still more memory leaks plugged. Lots of changes to improve performance and portability. PC users, you've been saved! As of patchlevel 1, we are now supplying MS-DOS "support." Said support was generously provided by Kent Williams, who is now the contact person for it. See below for his address. INSTALLATION: The Makefile will need some tailoring. Currently it is set up for a Sun running SunOS 4.x and gcc. The changes to make in the Makefile are commented and should be obvious. Starting with 2.11, our intent has been to make the code conform to standards (ANSI, POSIX, SVID, in that order) whenever possible, and to not penalize standard conforming systems. We have included substitute versions of routines not universally available. Simply add the appropriate define for the missing feature(s) on your system. If you have 4.2 or 4.3 BSD, you should add -DTMPNAM_MISSING since the version of tmpnam on these systems won't accept a NULL pointer. This does not apply to 4.3-tahoe or the S5R[23] systems I have access to. You need this if gawk core dumps on something simple like 'BEGIN {print "hi"}'. If you have neither bison nor yacc, use the awk.tab.c file here. It was generated with bison, and should have no AT&T code in it. (Note that modifying awk.y without bison or yacc will be difficult, at best. You might want to get a copy of bison from the FSF too.) If you have an MS-DOS system, use the stuff in pc.d. PRINTING THE MANUAL The 'support' directory contains texinfo.tex 2.1, which will be necessary for printing the manual, and the texindex.c program from the emacs distribution which is also necessary. See the makefile for the steps needed to get a DVI file from the manual. CAVEATS The existence of a patchlevel.h file does *N*O*T* imply a commitment on our part to issue bug fixes or patches. It is there in case we should decide to do so. BUG REPORTS AND FIXES: Please coordinate changes through David Trueman and/or Arnold Robbins. David Trueman Department of Mathematics, Statistics and Computing Science, Dalhousie University, Halifax, Nova Scotia, Canada UUCP {uunet utai watmath}!dalcs!david INTERNET david@cs.dal.ca Arnold Robbins 1315 Kittredge Court, N.E. Atlanta, GA, 30329-3539, USA INTERNET: arnold@skeeve.atl.ga.us UUCP: { gatech, emory, emoryu1 }!skeeve!arnold If you can't contact either of us, try Jay Fenlason, hack@prep.ai.mit.edu AKA mit-eddie!prep!hack. During odd hours he can sometimes be reached at (617) 253-8975, which is an MIT phone in the middle of the corridor, so don't be suprised if someone wierd answers, or if the person on the other end has never heard of him. (Direct them to the microvax about 10 feet to their left.) MS-DOS SUPPORT Support for MSC 5.1 was supplied for 2.11 by Kent Williams, who can be reached at williams@umaxc.weeg.uiowa.edu. It relies heavily on the earlier work done for 2.10 by Conrad Kwok and Scott Garfinkle. Bug reports on the MS-DOS version should go to Kent. Of course, if it's a generic bug, we want to hear about it too, but if it isn't reproducible under Unix, we won't be as interested. gawk-2.11/missing.d/ 755 11660 0 0 4527634010 12362 5ustar hackwheelgawk-2.11/missing.d/dup2.c 644 11660 0 210 4507454501 13434 0ustar hackwheel#ifndef F_DUPFD #include #endif int dup2 (old, new) int old, new; { (void) close(new); return fcntl(old, F_DUPFD, new); } gawk-2.11/missing.d/gcvt.c 644 11660 0 201 4447547413 13535 0ustar hackwheelchar * gcvt(value, digits, buff) double value; int digits; char *buff; { sprintf(buff, "%*g", digits, value); return (buff); } gawk-2.11/missing.d/getopt.c 644 11660 0 4602 4475032715 14120 0ustar hackwheel/* ** @(#)getopt.c 2.5 (smail) 9/15/87 */ /* * Here's something you've all been waiting for: the AT&T public domain * source for getopt(3). It is the code which was given out at the 1985 * UNIFORUM conference in Dallas. I obtained it by electronic mail * directly from AT&T. The people there assure me that it is indeed * in the public domain. * * There is no manual page. That is because the one they gave out at * UNIFORUM was slightly different from the current System V Release 2 * manual page. The difference apparently involved a note about the * famous rules 5 and 6, recommending using white space between an option * and its first argument, and not grouping options that have arguments. * Getopt itself is currently lenient about both of these things White * space is allowed, but not mandatory, and the last option in a group can * have an argument. That particular version of the man page evidently * has no official existence, and my source at AT&T did not send a copy. * The current SVR2 man page reflects the actual behavor of this getopt. * However, I am not about to post a copy of anything licensed by AT&T. */ #if defined(MSDOS) || defined(USG) #define index strchr #endif /*LINTLIBRARY*/ #define NULL 0 #define EOF (-1) #define ERR(s, c) if(opterr){\ extern int write();\ char errbuf[2];\ errbuf[0] = c; errbuf[1] = '\n';\ (void) write(2, argv[0], (unsigned)strlen(argv[0]));\ (void) write(2, s, (unsigned)strlen(s));\ (void) write(2, errbuf, 2);} extern char *index(); int opterr = 1; int optind = 1; int optopt; char *optarg; int getopt(argc, argv, opts) int argc; char **argv, *opts; { static int sp = 1; register int c; register char *cp; if(sp == 1) if(optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') return(EOF); else if(strcmp(argv[optind], "--") == NULL) { optind++; return(EOF); } optopt = c = argv[optind][sp]; if(c == ':' || (cp=index(opts, c)) == NULL) { ERR(": illegal option -- ", c); if(argv[optind][++sp] == '\0') { optind++; sp = 1; } return('?'); } if(*++cp == ':') { if(argv[optind][sp+1] != '\0') optarg = &argv[optind++][sp+1]; else if(++optind >= argc) { ERR(": option requires an argument -- ", c); sp = 1; return('?'); } else optarg = argv[optind++]; sp = 1; } else { if(argv[optind][++sp] == '\0') { sp = 1; optind++; } optarg = NULL; } return(c); } gawk-2.11/missing.d/memcmp.c 644 11660 0 531 4456117415 14051 0ustar hackwheel/* * memcmp --- compare strings. * * We use our own routine since it has to act like strcmp() for return * value, and the BSD manual says bcmp() only returns zero/non-zero. */ int memcmp (s1, s2, l) register char *s1, *s2; register int l; { for (; l--; s1++, s2++) { if (*s1 != *s2) return (*s1 - *s2); } return (*--s1 - *--s2); } gawk-2.11/missing.d/memcpy.c 644 11660 0 405 4466063612 14065 0ustar hackwheel/* * memcpy --- copy strings. * * We supply this routine for those systems that aren't standard yet. */ char * memcpy (dest, src, l) register char *dest, *src; register int l; { register char *ret = dest; while (l--) *dest++ = *src++; return ret; } gawk-2.11/missing.d/memset.c 644 11660 0 405 4466121411 14055 0ustar hackwheel/* * memset --- initialize memory * * We supply this routine for those systems that aren't standard yet. */ char * memset (dest, val, l) register char *dest, val; register int l; { register char *ret = dest; while (l--) *dest++ = val; return ret; } gawk-2.11/missing.d/random.c 644 11660 0 30761 4527633614 14126 0ustar hackwheel/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)random.c 5.5 (Berkeley) 7/6/88"; #endif /* LIBC_SCCS and not lint */ #include /* * random.c: * An improved random number generation package. In addition to the standard * rand()/srand() like interface, this package also has a special state info * interface. The initstate() routine is called with a seed, an array of * bytes, and a count of how many bytes are being passed in; this array is then * initialized to contain information for random number generation with that * much state information. Good sizes for the amount of state information are * 32, 64, 128, and 256 bytes. The state can be switched by calling the * setstate() routine with the same array as was initiallized with initstate(). * By default, the package runs with 128 bytes of state information and * generates far better random numbers than a linear congruential generator. * If the amount of state information is less than 32 bytes, a simple linear * congruential R.N.G. is used. * Internally, the state information is treated as an array of longs; the * zeroeth element of the array is the type of R.N.G. being used (small * integer); the remainder of the array is the state information for the * R.N.G. Thus, 32 bytes of state information will give 7 longs worth of * state information, which will allow a degree seven polynomial. (Note: the * zeroeth word of state information also has some other information stored * in it -- see setstate() for details). * The random number generation technique is a linear feedback shift register * approach, employing trinomials (since there are fewer terms to sum up that * way). In this approach, the least significant bit of all the numbers in * the state table will act as a linear feedback shift register, and will have * period 2^deg - 1 (where deg is the degree of the polynomial being used, * assuming that the polynomial is irreducible and primitive). The higher * order bits will have longer periods, since their values are also influenced * by pseudo-random carries out of the lower bits. The total period of the * generator is approximately deg*(2**deg - 1); thus doubling the amount of * state information has a vast influence on the period of the generator. * Note: the deg*(2**deg - 1) is an approximation only good for large deg, * when the period of the shift register is the dominant factor. With deg * equal to seven, the period is actually much longer than the 7*(2**7 - 1) * predicted by this formula. */ /* * For each of the currently supported random number generators, we have a * break value on the amount of state information (you need at least this * many bytes of state info to support this random number generator), a degree * for the polynomial (actually a trinomial) that the R.N.G. is based on, and * the separation between the two lower order coefficients of the trinomial. */ #define TYPE_0 0 /* linear congruential */ #define BREAK_0 8 #define DEG_0 0 #define SEP_0 0 #define TYPE_1 1 /* x**7 + x**3 + 1 */ #define BREAK_1 32 #define DEG_1 7 #define SEP_1 3 #define TYPE_2 2 /* x**15 + x + 1 */ #define BREAK_2 64 #define DEG_2 15 #define SEP_2 1 #define TYPE_3 3 /* x**31 + x**3 + 1 */ #define BREAK_3 128 #define DEG_3 31 #define SEP_3 3 #define TYPE_4 4 /* x**63 + x + 1 */ #define BREAK_4 256 #define DEG_4 63 #define SEP_4 1 /* * Array versions of the above information to make code run faster -- relies * on fact that TYPE_i == i. */ #define MAX_TYPES 5 /* max number of types above */ static int degrees[ MAX_TYPES ] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 }; static int seps[ MAX_TYPES ] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 }; /* * Initially, everything is set up as if from : * initstate( 1, &randtbl, 128 ); * Note that this initialization takes advantage of the fact that srandom() * advances the front and rear pointers 10*rand_deg times, and hence the * rear pointer which starts at 0 will also end up at zero; thus the zeroeth * element of the state information, which contains info about the current * position of the rear pointer is just * MAX_TYPES*(rptr - state) + TYPE_3 == TYPE_3. */ static long randtbl[ DEG_3 + 1 ] = { TYPE_3, 0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5, 0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd, 0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88, 0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc, 0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b, 0x27fb47b9 }; /* * fptr and rptr are two pointers into the state info, a front and a rear * pointer. These two pointers are always rand_sep places aparts, as they cycle * cyclically through the state information. (Yes, this does mean we could get * away with just one pointer, but the code for random() is more efficient this * way). The pointers are left positioned as they would be from the call * initstate( 1, randtbl, 128 ) * (The position of the rear pointer, rptr, is really 0 (as explained above * in the initialization of randtbl) because the state table pointer is set * to point to randtbl[1] (as explained below). */ static long *fptr = &randtbl[ SEP_3 + 1 ]; static long *rptr = &randtbl[ 1 ]; /* * The following things are the pointer to the state information table, * the type of the current generator, the degree of the current polynomial * being used, and the separation between the two pointers. * Note that for efficiency of random(), we remember the first location of * the state information, not the zeroeth. Hence it is valid to access * state[-1], which is used to store the type of the R.N.G. * Also, we remember the last location, since this is more efficient than * indexing every time to find the address of the last element to see if * the front and rear pointers have wrapped. */ static long *state = &randtbl[ 1 ]; static int rand_type = TYPE_3; static int rand_deg = DEG_3; static int rand_sep = SEP_3; static long *end_ptr = &randtbl[ DEG_3 + 1 ]; /* * srandom: * Initialize the random number generator based on the given seed. If the * type is the trivial no-state-information type, just remember the seed. * Otherwise, initializes state[] based on the given "seed" via a linear * congruential generator. Then, the pointers are set to known locations * that are exactly rand_sep places apart. Lastly, it cycles the state * information a given number of times to get rid of any initial dependencies * introduced by the L.C.R.N.G. * Note that the initialization of randtbl[] for default usage relies on * values produced by this routine. */ srandom( x ) unsigned x; { register int i, j; long random(); if( rand_type == TYPE_0 ) { state[ 0 ] = x; } else { j = 1; state[ 0 ] = x; for( i = 1; i < rand_deg; i++ ) { state[i] = 1103515245*state[i - 1] + 12345; } fptr = &state[ rand_sep ]; rptr = &state[ 0 ]; for( i = 0; i < 10*rand_deg; i++ ) random(); } } /* * initstate: * Initialize the state information in the given array of n bytes for * future random number generation. Based on the number of bytes we * are given, and the break values for the different R.N.G.'s, we choose * the best (largest) one we can and set things up for it. srandom() is * then called to initialize the state information. * Note that on return from srandom(), we set state[-1] to be the type * multiplexed with the current value of the rear pointer; this is so * successive calls to initstate() won't lose this information and will * be able to restart with setstate(). * Note: the first thing we do is save the current state, if any, just like * setstate() so that it doesn't matter when initstate is called. * Returns a pointer to the old state. */ char * initstate( seed, arg_state, n ) unsigned seed; /* seed for R. N. G. */ char *arg_state; /* pointer to state array */ int n; /* # bytes of state info */ { register char *ostate = (char *)( &state[ -1 ] ); if( rand_type == TYPE_0 ) state[ -1 ] = rand_type; else state[ -1 ] = MAX_TYPES*(rptr - state) + rand_type; if( n < BREAK_1 ) { if( n < BREAK_0 ) { fprintf( stderr, "initstate: not enough state (%d bytes) with which to do jack; ignored.\n", n ); return 0; } rand_type = TYPE_0; rand_deg = DEG_0; rand_sep = SEP_0; } else { if( n < BREAK_2 ) { rand_type = TYPE_1; rand_deg = DEG_1; rand_sep = SEP_1; } else { if( n < BREAK_3 ) { rand_type = TYPE_2; rand_deg = DEG_2; rand_sep = SEP_2; } else { if( n < BREAK_4 ) { rand_type = TYPE_3; rand_deg = DEG_3; rand_sep = SEP_3; } else { rand_type = TYPE_4; rand_deg = DEG_4; rand_sep = SEP_4; } } } } state = &( ( (long *)arg_state )[1] ); /* first location */ end_ptr = &state[ rand_deg ]; /* must set end_ptr before srandom */ srandom( seed ); if( rand_type == TYPE_0 ) state[ -1 ] = rand_type; else state[ -1 ] = MAX_TYPES*(rptr - state) + rand_type; return( ostate ); } /* * setstate: * Restore the state from the given state array. * Note: it is important that we also remember the locations of the pointers * in the current state information, and restore the locations of the pointers * from the old state information. This is done by multiplexing the pointer * location into the zeroeth word of the state information. * Note that due to the order in which things are done, it is OK to call * setstate() with the same state as the current state. * Returns a pointer to the old state information. */ char * setstate( arg_state ) char *arg_state; { register long *new_state = (long *)arg_state; register int type = new_state[0]%MAX_TYPES; register int rear = new_state[0]/MAX_TYPES; char *ostate = (char *)( &state[ -1 ] ); if( rand_type == TYPE_0 ) state[ -1 ] = rand_type; else state[ -1 ] = MAX_TYPES*(rptr - state) + rand_type; switch( type ) { case TYPE_0: case TYPE_1: case TYPE_2: case TYPE_3: case TYPE_4: rand_type = type; rand_deg = degrees[ type ]; rand_sep = seps[ type ]; break; default: fprintf( stderr, "setstate: state info has been munged; not changed.\n" ); } state = &new_state[ 1 ]; if( rand_type != TYPE_0 ) { rptr = &state[ rear ]; fptr = &state[ (rear + rand_sep)%rand_deg ]; } end_ptr = &state[ rand_deg ]; /* set end_ptr too */ return( ostate ); } /* * random: * If we are using the trivial TYPE_0 R.N.G., just do the old linear * congruential bit. Otherwise, we do our fancy trinomial stuff, which is the * same in all ther other cases due to all the global variables that have been * set up. The basic operation is to add the number at the rear pointer into * the one at the front pointer. Then both pointers are advanced to the next * location cyclically in the table. The value returned is the sum generated, * reduced to 31 bits by throwing away the "least random" low bit. * Note: the code takes advantage of the fact that both the front and * rear pointers can't wrap on the same call by not testing the rear * pointer if the front one has wrapped. * Returns a 31-bit random number. */ long random() { long i; if( rand_type == TYPE_0 ) { i = state[0] = ( state[0]*1103515245 + 12345 )&0x7fffffff; } else { *fptr += *rptr; i = (*fptr >> 1)&0x7fffffff; /* chucking least random bit */ if( ++fptr >= end_ptr ) { fptr = state; ++rptr; } else { if( ++rptr >= end_ptr ) rptr = state; } } return( i ); } gawk-2.11/missing.d/strcase.c 644 11660 0 7355 4507454501 14267 0ustar hackwheel/* * Copyright (c) 1987 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strcasecmp.c 5.6 (Berkeley) 6/27/88"; #endif /* LIBC_SCCS and not lint */ #ifndef USG #include #else #define u_char unsigned char #endif /* * This array is designed for mapping upper and lower case letter * together for a case independent comparison. The mappings are * based upon ascii character sequences. */ static u_char charmap[] = { '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247', '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257', '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267', '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\333', '\334', '\335', '\336', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377', }; strcasecmp(s1, s2) char *s1, *s2; { register u_char *cm = charmap, *us1 = (u_char *)s1, *us2 = (u_char *)s2; while (cm[*us1] == cm[*us2++]) if (*us1++ == '\0') return(0); return(cm[*us1] - cm[*--us2]); } strncasecmp(s1, s2, n) char *s1, *s2; register int n; { register u_char *cm = charmap, *us1 = (u_char *)s1, *us2 = (u_char *)s2; while (--n >= 0 && cm[*us1] == cm[*us2++]) if (*us1++ == '\0') return(0); return(n < 0 ? 0 : cm[*us1] - cm[*--us2]); } gawk-2.11/missing.d/strchr.c 644 11660 0 1037 4506452766 14131 0ustar hackwheel/* * strchr --- search a string for a character * * We supply this routine for those systems that aren't standard yet. */ char * strchr (str, c) register char *str, c; { for (; *str; str++) if (*str == c) return str; return NULL; } /* * strrchr --- find the last occurrence of a character in a string * * We supply this routine for those systems that aren't standard yet. */ char * strrchr (str, c) register char *str, c; { register char *save = NULL; for (; *str; str++) if (*str == c) save = str; return save; } gawk-2.11/missing.d/strerror.c 644 11660 0 2360 4474611464 14502 0ustar hackwheel/* * strerror.c --- ANSI C compatible system error routine */ /* * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. * * This file is part of GAWK, the GNU implementation of the * AWK Progamming Language. * * GAWK is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * GAWK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GAWK; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ extern int sys_nerr; extern char *sys_errlist[]; /* have to get right decl of sprintf early on */ #ifndef BUFSIZ /* stdio specific definition */ #include #endif char * strerror(n) int n; { static char mesg[30]; if (n < 0 || n > sys_nerr) { sprintf (mesg, "Unknown error (%d)", n); return mesg; } else return sys_errlist[n]; } gawk-2.11/missing.d/strtod.c 644 11660 0 3747 4464064564 14153 0ustar hackwheel/* * strtod.c * * Stupid version of System V strtod(3) library routine. * Does no overflow/underflow checking. * * A real number is defined to be * optional leading white space * optional sign * string of digits with optional decimal point * optional 'e' or 'E' * followed by optional sign or space * followed by an integer * * if ptr is not NULL a pointer to the character terminating the * scan is returned in *ptr. If no number formed, *ptr is set to str * and 0 is returned. * * For speed, we don't do the conversion ourselves. Instead, we find * the end of the number and then call atof() to do the dirty work. * This bought us a 10% speedup on a sample program at uunet.uu.net. */ #include extern double atof(); double strtod (s, ptr) register char *s, **ptr; { double ret = 0.0; char *start = s; char *begin = NULL; int success = 0; /* optional white space */ while (isspace(*s)) s++; /* optional sign */ if (*s == '+' || *s == '-') { s++; if (*(s-1) == '-') begin = s - 1; else begin = s; } /* string of digits with optional decimal point */ if (isdigit(*s) && ! begin) begin = s; while (isdigit(*s)) { s++; success++; } if (*s == '.') { if (! begin) begin = s; s++; while (isdigit(*s)) s++; success++; } if (s == start || success == 0) /* nothing there */ goto out; /* * optional 'e' or 'E' * followed by optional sign or space * followed by an integer */ if (*s == 'e' || *s == 'E') { s++; /* XXX - atof probably doesn't allow spaces here */ while (isspace(*s)) s++; if (*s == '+' || *s == '-') s++; while (isdigit(*s)) s++; } /* go for it */ ret = atof(begin); out: if (! success) s = start; /* in case all we did was skip whitespace */ if (ptr) *ptr = s; return ret; } #ifdef TEST main (argc, argv) int argc; char **argv; { double d; char *p; for (argc--, argv++; argc; argc--, argv++) { d = strtod (*argv, & p); printf ("%lf [%s]\n", d, p); } } #endif gawk-2.11/missing.d/tmpnam.c 644 11660 0 744 4466120234 14067 0ustar hackwheel/* * tmpnam - an implementation for systems lacking a library version * this version does not rely on the P_tmpdir and L_tmpnam constants. */ #ifndef NULL #define NULL 0 #endif static char template[] = "/tmp/gawkXXXXXX"; char * tmpnam(tmp) char *tmp; { static char tmpbuf[sizeof(template)]; if (tmp == NULL) { (void) strcpy(tmpbuf, template); (void) mktemp(tmpbuf); return tmpbuf; } else { (void) strcpy(tmp, template); (void) mktemp(tmp); return tmp; } } gawk-2.11/missing.d/vprintf.c 644 11660 0 1514 4464063540 14303 0ustar hackwheel#include #include #ifndef BUFSIZ #include #endif #ifndef va_dcl #include #endif int vsprintf(str, fmt, ap) char *str, *fmt; va_list ap; { FILE f; int len; f._flag = _IOWRT+_IOSTRG; f._ptr = (char *)str; /* My copy of BSD stdio.h has this as (char *) * with a comment that it should be * (unsigned char *). Since this code is * intended for use on a vanilla BSD system, * we'll stick with (char *) for now. */ f._cnt = 32767; len = _doprnt(fmt, ap, &f); *f._ptr = 0; return (len); } int vfprintf(iop, fmt, ap) FILE *iop; char *fmt; va_list ap; { int len; len = _doprnt(fmt, ap, iop); return (ferror(iop) ? EOF : len); } int vprintf(fmt, ap) char *fmt; va_list ap; { int len; len = _doprnt(fmt, ap, stdout); return (ferror(stdout) ? EOF : len); } gawk-2.11/pc.d/ 755 11660 0 0 4527633754 11331 5ustar hackwheelgawk-2.11/pc.d/Makefile.pc 666 11660 0 20467 4527633621 13500 0ustar hackwheel# Makefile for GNU Awk. # # Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc. # # This file is part of GAWK, the GNU implementation of the # AWK Progamming Language. # # GAWK is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 1, or (at your option) # any later version. # # GAWK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GAWK; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # User tunable macros # CFLAGS: options to the C compiler # # -O optimize # -g include dbx/sdb info # -gg include gdb debugging info; only for GCC (deprecated) # -pg include new (gmon) profiling info # -p include old style profiling info (System V) # # To port GAWK, examine and adjust the following flags carefully. # In addition, you will have to look at alloca below. # The intent (eventual) is to not penalize the most-standard-conforming # systems with a lot of #define's. # # -DBCOPY_MISSING - bcopy() et al. are missing; will replace # with a #define'd memcpy() et al. -- use at # your own risk (should really use a memmove()) # -DSPRINTF_INT - sprintf() returns int (most USG systems) # -DBLKSIZE_MISSING - st_blksize missing from stat() structure # (most USG systems) # -DBSDSTDIO - has a BSD internally-compatible stdio # -DDOPRNT_MISSING - lacks doprnt() routine # -DDUP2_MISSING - lacks dup2() system call (S5Rn, n < 4) # -DGCVT_MISSING - lacks gcvt() routine # -DGETOPT_MISSING - lacks getopt() routine # -DMEMCMP_MISSING - lacks memcmp() routine # -DMEMCPY_MISSING - lacks memcpy() routine # -DMEMSET_MISSING - lacks memset() routine # -DRANDOM_MISSING - lacks random() routine # -DSTRCASE_MISSING - lacks strcasecmp() routine # -DSTRCHR_MISSING - lacks strchr() and strrchr() routines # -DSTRERROR_MISSING - lacks (ANSI C) strerror() routine # -DSTRTOD_MISSING - lacks strtod() routine # -DTMPNAM_MISSING - lacks or deficient tmpnam() routine # -DVPRINTF_MISSING - lacks vprintf and associated routines # -DSIGTYPE=int - signal routines return int (default void) # Sun running SunOS 4.x # MISSING = -DSTRERROR_MISSING -DSTRCASE_MISSING # SGI Personal Iris (Sys V derived) # MISSING = -DSPRINTF_INT -DBLKSIZE_MISSING -DSTRERROR_MISSING -DRANDOM_MISSING # VAX running Ultrix 3.x # MISSING = -DSTRERROR_MISSING # A generic 4.2 BSD machine # (eliminate GETOPT_MISSING for 4.3 release) # (eliminate STRCASE_MISSING and TMPNAM_MISSING for Tahoe release) # MISSING = -DBSDSTDIO -DMEMCMP_MISSING -DMEMCPY_MISSING -DMEMSET_MISSING \ # -DSTRERROR_MISSING -DSTRTOD_MISSING -DVPRINTF_MISSING \ # -DSTRCASE_MISSING -DTMPNAM_MISSING \ # -DGETOPT_MISSING -DSTRCHR_MISSING -DSIGTYPE=int # On Amdahl UTS, a SysVr2-derived system # MISSING = -DBCOPY_MISSING -DSPRINTF_INT -DRANDOM_MISSING -DSTRERROR_MISSING \ # -DSTRCASE_MISSING -DDUP2_MISSING # -DBLKSIZE_MISSING ?????? # Comment out the next line if you don't have gcc. # Also choose just one of -g and -O. # CC= gcc # for DOS CC= cl POPEN = popen.o # for DOS, most of the missing symbols are defined in MISSING.C in order to # get around the command line length limitations MISSING = -DSPRINTF_INT -DBLKSIZE_MISSING -DBCOPY_MISSING LINKFLAGS= /MAP /CO /FAR /PACKC /NOE /NOIG /st:0x1800 # also give suffixes and explicit rule for DOS .SUFFIXES : .o .c .c.o: $(CC) -c $(CFLAGS) -Ipc.d -W2 -AL -Fo$*.o $< OPTIMIZE= -Od -Zi PROFILE= #-pg DEBUG= #-DDEBUG #-DMEMDEBUG #-DFUNC_TRACE #-DMPROF DEBUGGER= #-g -Bstatic WARN= #-W -Wunused -Wimplicit -Wreturn-type -Wcomment # for gcc only # Parser to use on grammar -- if you don't have bison use the first one #PARSER = yacc PARSER = bison # ALLOCA # Set equal to alloca.o if your system is S5 and you don't have # alloca. Uncomment one of the rules below to make alloca.o from # either alloca.s or alloca.c. ALLOCA= #alloca.o # # With the exception of the alloca rule referred to above, you shouldn't # need to customize this file below this point. # FLAGS= $(MISSING) $(DEBUG) CFLAGS= $(FLAGS) $(DEBUGGER) $(PROFILE) $(OPTIMIZE) $(WARN) # object files O1 = main.o eval.o builtin.o msg.o debug.o io.o field.o array.o node.o O2 = version.o missing.o $(POPEN) AWKOBJS = $(O1) $(O2) # for unix # AWKTAB = awk.tab.o # for dos AWKTAB = awk_tab.o ALLOBJS = $(AWKOBJS) $(AWKTAB) # GNUOBJS # GNU stuff that gawk uses as library routines. GNUOBJS= regex.o $(ALLOCA) # source and documentation files SRC = main.c eval.c builtin.c msg.c \ debug.c io.c field.c array.c node.c missing.c ALLSRC= $(SRC) awk.tab.c AWKSRC= awk.h awk.y $(ALLSRC) version.sh patchlevel.h GNUSRC = alloca.c alloca.s regex.c regex.h COPIES = missing.d/dup2.c missing.d/gcvt.c missing.d/getopt.c \ missing.d/memcmp.c missing.d/memcpy.c missing.d/memset.c \ missing.d/random.c missing.d/strcase.c missing.d/strchr.c \ missing.d/strerror.c missing.d/strtod.c missing.d/tmpnam.c \ missing.d/vprintf.c SUPPORT = support/texindex.c support/texinfo.tex DOCS= gawk.1 gawk.texinfo INFOFILES= gawk-info gawk-info-1 gawk-info-2 gawk-info-3 gawk-info-4 \ gawk-info-5 gawk-info-6 gawk.aux gawk.cp gawk.cps gawk.fn \ gawk.fns gawk.ky gawk.kys gawk.pg gawk.pgs gawk.toc \ gawk.tp gawk.tps gawk.vr gawk.vrs MISC = CHANGES COPYING FUTURES Makefile PROBLEMS README PCSTUFF= pc.d/Makefile.pc pc.d/popen.c pc.d/popen.h ALLDOC= gawk.dvi $(INFOFILES) ALLFILES= $(AWKSRC) $(GNUSRC) $(COPIES) $(MISC) $(DOCS) $(ALLDOC) $(PCSTUFF) $(SUPPORT) # Release of gawk. There can be no leading or trailing white space here! REL=2.11 # for unix # GAWK = gawk # for DOS GAWK = gawk.exe $(GAWK) : $(ALLOBJS) $(GNUOBJS) names.lnk link @names.lnk #GNULIB = ..\lib\lgnu.lib GNULIB = names.lnk : makefile echo $(O1) + > $@ echo $(O2) + >> $@ echo $(AWKTAB) + >> $@ echo $(GNUOBJS) >> $@ echo $(GAWK) >> $@ echo gawk.map >> $@ echo $(GNULIB) $(LINKFLAGS) >> $@ popen.o : pc.d\popen.c $(CC) -c $(CFLAGS) -Ipc.d -W2 -AL -Fo$*.o pc.d\popen.c # rules to build gawk #$(GAWK) : $(ALLOBJS) $(GNUOBJS) # $(CC) -o gawk $(CFLAGS) $(ALLOBJS) $(GNUOBJS) -lm $(AWKOBJS): awk.h main.o: patchlevel.h #awk.tab.o: awk.h awk.tab.c # #awk.tab.c: awk.y # $(PARSER) -v awk.y # -mv -f y.tab.c awk.tab.c # for dos awk_tab.o : awk.y awk.h bison -y awk.y $(CC) -c $(CFLAGS) -Ipc.d -W2 -AL -Fo$@ y_tab.c @-rm y_tab.c version.c: version.sh sh version.sh $(REL) > version.c # Alloca: uncomment this if your system (notably System V boxen) # does not have alloca in /lib/libc.a # #alloca.o: alloca.s # /lib/cpp < alloca.s | sed '/^#/d' > t.s # as t.s -o alloca.o # rm t.s # If your machine is not supported by the assembly version of alloca.s, # use the C version instead. This uses the default rules to make alloca.o. # #alloca.o: alloca.c # auxiliary rules for release maintenance lint: $(ALLSRC) lint -hcbax $(FLAGS) $(ALLSRC) xref: cxref -c $(FLAGS) $(ALLSRC) | grep -v ' /' >xref clean: rm -f gawk *.o core awk.output awk.tab.c gmon.out make.out version.c clobber: clean rm -f $(ALLDOC) gawk.log gawk.dvi: gawk.texinfo tex gawk.texinfo ; texindex gawk.?? tex gawk.texinfo ; texindex gawk.?? tex gawk.texinfo $(INFOFILES): gawk.texinfo makeinfo gawk.texinfo srcrelease: $(AWKSRC) $(GNUSRC) $(DOCS) $(MISC) $(COPIES) $(PCSTUFF) $(SUPPORT) -mkdir gawk-$(REL) cp -p $(AWKSRC) $(GNUSRC) $(DOCS) $(MISC) gawk-$(REL) -mkdir gawk-$(REL)/missing.d cp -p $(COPIES) gawk-$(REL)/missing.d -mkdir gawk-$(REL)/pc.d cp -p $(PCSTUFF) gawk-$(REL)/pc.d -mkdir gawk-$(REL)/support cp -p $(SUPPORT) gawk-$(REL)/support tar -cf - gawk-$(REL) | compress > gawk-$(REL).tar.Z docrelease: $(ALLDOC) -mkdir gawk-$(REL)-doc cp -p $(INFOFILES) gawk.dvi gawk-$(REL)-doc nroff -man gawk.1 > gawk-$(REL)-doc/gawk.1.pr tar -cf - gawk-$(REL)-doc | compress > gawk-doc-$(REL).tar.Z psrelease: docrelease -mkdir gawk-postscript dvi2ps gawk.dvi > gawk-postscript/gawk.postscript psroff -t -man gawk.1 > gawk-postscript/gawk.1.ps tar -cf - gawk-postscript | compress > gawk.postscript.tar.Z release: srcrelease docrelease psrelease rm -fr gawk-postscript gawk-$(REL) gawk-$(REL)-doc diff: for i in RCS/*; do rcsdiff -c -b $$i > `basename $$i ,v`.diff; done gawk-2.11/pc.d/popen.c 644 11660 0 3776 4472334574 12710 0ustar hackwheel#include #include "popen.h" #include #include #include static char template[] = "piXXXXXX"; typedef enum { unopened = 0, reading, writing } pipemode; static struct { char *command; char *name; pipemode pmode; } pipes[_NFILE]; FILE * popen( char *command, char *mode ) { FILE *current; char *name; int cur; pipemode curmode; /* ** decide on mode. */ if(strcmp(mode,"r") == 0) curmode = reading; else if(strcmp(mode,"w") == 0) curmode = writing; else return NULL; /* ** get a name to use. */ if((name = tempnam(".","pip"))==NULL) return NULL; /* ** If we're reading, just call system to get a file filled with ** output. */ if(curmode == reading) { char cmd[256]; sprintf(cmd,"%s > %s",command,name); system(cmd); if((current = fopen(name,"r")) == NULL) return NULL; } else { if((current = fopen(name,"w")) == NULL) return NULL; } cur = fileno(current); pipes[cur].name = name; pipes[cur].pmode = curmode; pipes[cur].command = strdup(command); return current; } int pclose( FILE * current) { int cur = fileno(current),rval; /* ** check for an open file. */ if(pipes[cur].pmode == unopened) return -1; if(pipes[cur].pmode == reading) { /* ** input pipes are just files we're done with. */ rval = fclose(current); unlink(pipes[cur].name); } else { /* ** output pipes are temporary files we have ** to cram down the throats of programs. */ char command[256]; fclose(current); sprintf(command,"%s < %s",pipes[cur].command,pipes[cur].name); rval = system(command); unlink(pipes[cur].name); } /* ** clean up current pipe. */ pipes[cur].pmode = unopened; free(pipes[cur].name); free(pipes[cur].command); return rval; } gawk-2.11/pc.d/popen.h 644 11660 0 206 4472334574 12656 0ustar hackwheel/* ** popen.h -- prototypes for pipe functions */ #if !defined(FILE) #include #endif extern FILE *popen( char *, char * ); gawk-2.11/support/ 755 11660 0 0 4527633434 12214 5ustar hackwheelgawk-2.11/support/texindex.c 666 11660 0 123426 4266235527 14345 0ustar hackwheel/* Prepare Tex index dribble output into an actual index. Copyright (C) 1987 Free Software Foundation, Inc. NO WARRANTY BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. GENERAL PUBLIC LICENSE TO COPY 1. You may copy and distribute verbatim copies of this source file as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy a valid copyright notice "Copyright (C) 1987 Free Software Foundation, Inc.", and include following the copyright notice a verbatim copy of the above disclaimer of warranty and of this License. 2. You may modify your copy or copies of this source file or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains or is a derivative of this program or any part thereof, to be licensed at no charge to all third parties on terms identical to those contained in this License Agreement (except that you may choose to grant more extensive warranty protection to some or all third parties, at your option). c) You may charge a distribution fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another unrelated program with this program (or its derivative) on a volume of a storage or distribution medium does not bring the other program under the scope of these terms. 3. You may copy and distribute this program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal shipping charge) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs. 4. You may not copy, sublicense, distribute or transfer this program except as expressly provided under this License Agreement. Any attempt otherwise to copy, sublicense, distribute or transfer this program is void and your rights to use the program under this License agreement shall be automatically terminated. However, parties who have received computer software programs from you with this License Agreement will not have their licenses terminated so long as such parties remain in full compliance. 5. If you wish to incorporate parts of this program into other free programs whose distribution conditions are different, write to the Free Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet worked out a simple rule that can be stated here, but we will often permit this. We will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software. In other words, you are welcome to use, share and improve this program. You are forbidden to forbid anyone else to use, share and improve what you give them. Help stamp out software-hoarding! */ #include #include #ifdef VMS #include #define EXIT_SUCCESS ((1 << 28) | 1) #define EXIT_FATAL ((1 << 28) | 4) #define unlink delete #define tell(fd) lseek(fd, 0L, 1) #else #include #define EXIT_SUCCESS 0 #define EXIT_FATAL 1 #endif #ifndef L_XTND #define L_XTND 2 #endif /* When sorting in core, this structure describes one line and the position and length of its first keyfield. */ struct lineinfo { char *text; /* The actual text of the line */ union { /* The start of the key (for textual comparison) */ char *text; long number; /* or the numeric value (for numeric comparison) */ } key; long keylen; /* Length of key field */ }; /* This structure describes a field to use as a sort key */ struct keyfield { int startwords; /* # words to skip */ int startchars; /* and # additional chars to skip, to start of field */ int endwords; /* similar, from beg (or end) of line, to find end of field */ int endchars; char ignore_blanks; /* Ignore spaces and tabs within the field */ char fold_case; /* Convert upper case to lower before comparing */ char reverse; /* Compare in reverse order */ char numeric; /* Parse text as an integer and compare the integers */ char positional; /* Sort according to position within the file */ char braced; /* Count balanced-braced groupings as fields */ }; /* Vector of keyfields to use */ struct keyfield keyfields[3]; /* Number of keyfields stored in that vector. */ int num_keyfields = 3; /* Vector of input file names, terminated with a zero (null pointer) */ char **infiles; /* Vector of corresponding output file names, or zero meaning default it */ char **outfiles; /* Length of `infiles' */ int num_infiles; /* Pointer to the array of pointers to lines being sorted */ char **linearray; /* The allocated length of `linearray'. */ long lines; /* Directory to use for temporary files. On Unix, it ends with a slash. */ char *tempdir; /* Start of filename to use for temporary files. */ char *tempbase; /* Number of last temporary file. */ int tempcount; /* Number of last temporary file already deleted. Temporary files are deleted by `flush_tempfiles' in order of creation. */ int last_deleted_tempcount; /* During in-core sort, this points to the base of the data block which contains all the lines of data. */ char *text_base; /* Additional command switches */ int keep_tempfiles; /* Nonzero means do not delete tempfiles -- for debugging */ /* Forward declarations of functions in this file */ void decode_command (); void sort_in_core (); void sort_offline (); char **parsefile (); char *find_field (); char *find_pos (); long find_value (); char *find_braced_pos (); char *find_braced_end (); void writelines (); int compare_full (); long readline (); int merge_files (); int merge_direct (); char *concat (); char *maketempname (); void flush_tempfiles (); char *tempcopy (); extern char *mktemp (); #define MAX_IN_CORE_SORT 500000 int main (argc, argv) int argc; char **argv; { int i; tempcount = 0; last_deleted_tempcount = 0; /* Describe the kind of sorting to do. */ /* The first keyfield uses the first braced field and folds case */ keyfields[0].braced = 1; keyfields[0].fold_case = 1; keyfields[0].endwords = -1; keyfields[0].endchars = -1; /* The second keyfield uses the second braced field, numerically */ keyfields[1].braced = 1; keyfields[1].numeric = 1; keyfields[1].startwords = 1; keyfields[1].endwords = -1; keyfields[1].endchars = -1; /* The third keyfield (which is ignored while discarding duplicates) compares the whole line */ keyfields[2].endwords = -1; keyfields[2].endchars = -1; decode_command (argc, argv); tempbase = mktemp (concat ("txiXXXXXX", "", "")); /* Process input files completely, one by one. */ for (i = 0; i < num_infiles; i++) { int desc; long ptr; char *outfile; char *p; desc = open (infiles[i], 0, 0); if (desc < 0) pfatal_with_name (infiles[i]); lseek (desc, 0, L_XTND); ptr = tell (desc); close (desc); outfile = outfiles[i]; if (!outfile) { outfile = concat (infiles[i], "s", ""); } if (ptr < MAX_IN_CORE_SORT) /* Sort a small amount of data */ sort_in_core (infiles[i], ptr, outfile); else sort_offline (infiles[i], ptr, outfile); } flush_tempfiles (tempcount); exit (EXIT_SUCCESS); } /* This page decodes the command line arguments to set the parameter variables and set up the vector of keyfields and the vector of input files */ void decode_command (argc, argv) int argc; char **argv; { int i; char **ip; char **op; /* Store default values into parameter variables */ #ifdef VMS tempdir = "sys$scratch:"; #else tempdir = "/tmp/"; #endif keep_tempfiles = 0; /* Allocate argc input files, which must be enough. */ infiles = (char **) xmalloc (argc * sizeof (char *)); outfiles = (char **) xmalloc (argc * sizeof (char *)); ip = infiles; op = outfiles; /* First find all switches that control the default kind-of-sort */ for (i = 1; i < argc; i++) { int tem = classify_arg (argv[i]); char c; char *p; if (tem <= 0) { *ip++ = argv[i]; *op++ = 0; continue; } if (tem > 1) { if (i + 1 == argc) fatal ("switch %s given with no argument following it", argv[i]); else if (!strcmp (argv[i], "-T")) tempdir = argv[i + 1]; else if (!strcmp (argv[i], "-o")) *(op - 1) = argv[i + 1]; i += tem - 1; continue; } p = &argv[i][1]; while (c = *p++) switch (c) { case 'k': keep_tempfiles = 1; break; default: fatal ("invalid command switch %c", c); } switchdone: ; } /* Record number of keyfields, terminate list of filenames */ num_infiles = ip - infiles; *ip = 0; } /* Return 0 for an argument that is not a switch; for a switch, return 1 plus the number of following arguments that the switch swallows. */ int classify_arg (arg) char *arg; { if (!strcmp (arg, "-T") || !strcmp (arg, "-o")) return 2; if (arg[0] == '-') return 1; return 0; } /* Create a name for a temporary file */ char * maketempname (count) int count; { char tempsuffix[10]; sprintf (tempsuffix, "%d", count); return concat (tempdir, tempbase, tempsuffix); } /* Delete all temporary files up to the specified count */ void flush_tempfiles (to_count) int to_count; { if (keep_tempfiles) return; while (last_deleted_tempcount < to_count) unlink (maketempname (++last_deleted_tempcount)); } /* Copy an input file into a temporary file, and return the temporary file name */ #define BUFSIZE 1024 char * tempcopy (idesc) int idesc; { char *outfile = maketempname (++tempcount); int odesc; char buffer[BUFSIZE]; odesc = open (outfile, O_WRONLY | O_CREAT, 0666); if (odesc < 0) pfatal_with_name (outfile); while (1) { int nread = read (idesc, buffer, BUFSIZE); write (odesc, buffer, nread); if (!nread) break; } close (odesc); return outfile; } /* Compare two lines, provided as pointers to pointers to text, according to the specified set of keyfields */ int compare_full (line1, line2) char **line1, **line2; { int i; /* Compare using the first keyfield; if that does not distinguish the lines, try the second keyfield; and so on. */ for (i = 0; i < num_keyfields; i++) { long length1, length2; char *start1 = find_field (&keyfields[i], *line1, &length1); char *start2 = find_field (&keyfields[i], *line2, &length2); int tem = compare_field (&keyfields[i], start1, length1, *line1 - text_base, start2, length2, *line2 - text_base); if (tem) { if (keyfields[i].reverse) return - tem; return tem; } } return 0; /* Lines match exactly */ } /* Compare two lines described by structures in which the first keyfield is identified in advance. For positional sorting, assumes that the order of the lines in core reflects their nominal order. */ int compare_prepared (line1, line2) struct lineinfo *line1, *line2; { int i; int tem; char *text1, *text2; /* Compare using the first keyfield, which has been found for us already */ if (keyfields->positional) { if (line1->text - text_base > line2->text - text_base) tem = 1; else tem = -1; } else if (keyfields->numeric) tem = line1->key.number - line2->key.number; else tem = compare_field (keyfields, line1->key.text, line1->keylen, 0, line2->key.text, line2->keylen, 0); if (tem) { if (keyfields->reverse) return - tem; return tem; } text1 = line1->text; text2 = line2->text; /* Compare using the second keyfield; if that does not distinguish the lines, try the third keyfield; and so on. */ for (i = 1; i < num_keyfields; i++) { long length1, length2; char *start1 = find_field (&keyfields[i], text1, &length1); char *start2 = find_field (&keyfields[i], text2, &length2); int tem = compare_field (&keyfields[i], start1, length1, text1 - text_base, start2, length2, text2 - text_base); if (tem) { if (keyfields[i].reverse) return - tem; return tem; } } return 0; /* Lines match exactly */ } /* Like compare_full but more general. You can pass any strings, and you can say how many keyfields to use. `pos1' and `pos2' should indicate the nominal positional ordering of the two lines in the input. */ int compare_general (str1, str2, pos1, pos2, use_keyfields) char *str1, *str2; long pos1, pos2; int use_keyfields; { int i; /* Compare using the first keyfield; if that does not distinguish the lines, try the second keyfield; and so on. */ for (i = 0; i < use_keyfields; i++) { long length1, length2; char *start1 = find_field (&keyfields[i], str1, &length1); char *start2 = find_field (&keyfields[i], str2, &length2); int tem = compare_field (&keyfields[i], start1, length1, pos1, start2, length2, pos2); if (tem) { if (keyfields[i].reverse) return - tem; return tem; } } return 0; /* Lines match exactly */ } /* Find the start and length of a field in `str' according to `keyfield'. A pointer to the starting character is returned, and the length is stored into the int that `lengthptr' points to. */ char * find_field (keyfield, str, lengthptr) struct keyfield *keyfield; char *str; long *lengthptr; { char *start; char *end; char *(*fun) (); if (keyfield->braced) fun = find_braced_pos; else fun = find_pos; start = ( *fun )(str, keyfield->startwords, keyfield->startchars, keyfield->ignore_blanks); if (keyfield->endwords < 0) { if (keyfield->braced) end = find_braced_end (start); else { end = start; while (*end && *end != '\n') end++; } } else { end = ( *fun )(str, keyfield->endwords, keyfield->endchars, 0); if (end - str < start - str) end = start; } *lengthptr = end - start; return start; } /* Find a pointer to a specified place within `str', skipping (from the beginning) `words' words and then `chars' chars. If `ignore_blanks' is nonzero, we skip all blanks after finding the specified word. */ char * find_pos (str, words, chars, ignore_blanks) char *str; int words, chars; int ignore_blanks; { int i; char *p = str; for (i = 0; i < words; i++) { char c; /* Find next bunch of nonblanks and skip them. */ while ((c = *p) == ' ' || c == '\t') p++; while ((c = *p) && c != '\n' && !(c == ' ' || c == '\t')) p++; if (!*p || *p == '\n') return p; } while (*p == ' ' || *p == '\t') p++; for (i = 0; i < chars; i++) { if (!*p || *p == '\n') break; p++; } return p; } /* Like find_pos but assumes that each field is surrounded by braces and that braces within fields are balanced. */ char * find_braced_pos (str, words, chars, ignore_blanks) char *str; int words, chars; int ignore_blanks; { int i; int bracelevel; char *p = str; char c; for (i = 0; i < words; i++) { bracelevel = 1; while ((c = *p++) != '{' && c != '\n' && c); if (c != '{') return p - 1; while (bracelevel) { c = *p++; if (c == '{') bracelevel++; if (c == '}') bracelevel--; if (c == '\\') c = *p++; /* \ quotes braces and \ */ if (c == 0 || c == '\n') return p-1; } } while ((c = *p++) != '{' && c != '\n' && c); if (c != '{') return p-1; if (ignore_blanks) while ((c = *p) == ' ' || c == '\t') p++; for (i = 0; i < chars; i++) { if (!*p || *p == '\n') break; p++; } return p; } /* Find the end of the balanced-brace field which starts at `str'. The position returned is just before the closing brace. */ char * find_braced_end (str) char *str; { int bracelevel; char *p = str; char c; bracelevel = 1; while (bracelevel) { c = *p++; if (c == '{') bracelevel++; if (c == '}') bracelevel--; if (c == '\\') c = *p++; if (c == 0 || c == '\n') return p-1; } return p - 1; } long find_value (start, length) char *start; long length; { while (length != 0L) { if (isdigit(*start)) return atol(start); length--; start++; } return 0l; } /* Vector used to translate characters for comparison. This is how we make all alphanumerics follow all else, and ignore case in the first sorting. */ int char_order[256]; init_char_order () { int i; for (i = 1; i < 256; i++) char_order[i] = i; for (i = '0'; i <= '9'; i++) char_order[i] += 512; for (i = 'a'; i <= 'z'; i++) { char_order[i] = 512 + i; char_order[i + 'A' - 'a'] = 512 + i; } } /* Compare two fields (each specified as a start pointer and a character count) according to `keyfield'. The sign of the value reports the relation between the fields */ int compare_field (keyfield, start1, length1, pos1, start2, length2, pos2) struct keyfield *keyfield; char *start1; long length1; long pos1; char *start2; long length2; long pos2; { if (keyfields->positional) { if (pos1 > pos2) return 1; else return -1; } if (keyfield->numeric) { long value = find_value (start1, length1) - find_value (start2, length2); if (value > 0) return 1; if (value < 0) return -1; return 0; } else { char *p1 = start1; char *p2 = start2; char *e1 = start1 + length1; char *e2 = start2 + length2; int fold_case = keyfield->fold_case; while (1) { int c1, c2; if (p1 == e1) c1 = 0; else c1 = *p1++; if (p2 == e2) c2 = 0; else c2 = *p2++; if (char_order[c1] != char_order[c2]) return char_order[c1] - char_order[c2]; if (!c1) break; } /* Strings are equal except possibly for case. */ p1 = start1; p2 = start2; while (1) { int c1, c2; if (p1 == e1) c1 = 0; else c1 = *p1++; if (p2 == e2) c2 = 0; else c2 = *p2++; if (c1 != c2) /* Reverse sign here so upper case comes out last. */ return c2 - c1; if (!c1) break; } return 0; } } /* A `struct linebuffer' is a structure which holds a line of text. `readline' reads a line from a stream into a linebuffer and works regardless of the length of the line. */ struct linebuffer { long size; char *buffer; }; /* Initialize a linebuffer for use */ void initbuffer (linebuffer) struct linebuffer *linebuffer; { linebuffer->size = 200; linebuffer->buffer = (char *) xmalloc (200); } /* Read a line of text from `stream' into `linebuffer'. Return the length of the line. */ long readline (linebuffer, stream) struct linebuffer *linebuffer; FILE *stream; { char *buffer = linebuffer->buffer; char *p = linebuffer->buffer; char *end = p + linebuffer->size; while (1) { int c = getc (stream); if (p == end) { buffer = (char *) xrealloc (buffer, linebuffer->size *= 2); p += buffer - linebuffer->buffer; end += buffer - linebuffer->buffer; linebuffer->buffer = buffer; } if (c < 0 || c == '\n') { *p = 0; break; } *p++ = c; } return p - buffer; } /* Sort an input file too big to sort in core. */ void sort_offline (infile, nfiles, total, outfile) char *infile; long total; char *outfile; { int ntemps = 2 * (total + MAX_IN_CORE_SORT - 1) / MAX_IN_CORE_SORT; /* More than enough */ char **tempfiles = (char **) xmalloc (ntemps * sizeof (char *)); FILE *istream = fopen (infile, "r"); int i; struct linebuffer lb; long linelength; int failure = 0; initbuffer (&lb); /* Read in one line of input data. */ linelength = readline (&lb, istream); if (lb.buffer[0] != '\\') { error ("%s: not a texinfo index file", infile); return; } /* Split up the input into `ntemps' temporary files, or maybe fewer, and put the new files' names into `tempfiles' */ for (i = 0; i < ntemps; i++) { char *outname = maketempname (++tempcount); FILE *ostream = fopen (outname, "w"); long tempsize = 0; if (!ostream) pfatal_with_name (outname); tempfiles[i] = outname; /* Copy lines into this temp file as long as it does not make file "too big" or until there are no more lines. */ while (tempsize + linelength + 1 <= MAX_IN_CORE_SORT) { tempsize += linelength + 1; fputs (lb.buffer, ostream); putc ('\n', ostream); /* Read another line of input data. */ linelength = readline (&lb, istream); if (!linelength && feof (istream)) break; if (lb.buffer[0] != '\\') { error ("%s: not a texinfo index file", infile); failure = 1; goto fail; } } fclose (ostream); if (feof (istream)) break; } free (lb.buffer); fail: /* Record number of temp files we actually needed. */ ntemps = i; /* Sort each tempfile into another tempfile. Delete the first set of tempfiles and put the names of the second into `tempfiles' */ for (i = 0; i < ntemps; i++) { char *newtemp = maketempname (++tempcount); sort_in_core (&tempfiles[i], MAX_IN_CORE_SORT, newtemp); if (!keep_tempfiles) unlink (tempfiles[i]); tempfiles[i] = newtemp; } if (failure) return; /* Merge the tempfiles together and indexify */ merge_files (tempfiles, ntemps, outfile); } /* Sort `infile', whose size is `total', assuming that is small enough to be done in-core, then indexify it and send the output to `outfile' (or to stdout). */ void sort_in_core (infile, total, outfile) char *infile; long total; char *outfile; { char **nextline; char *data = (char *) xmalloc (total + 1); char *file_data; long file_size; int i; FILE *ostream = stdout; struct lineinfo *lineinfo; /* Read the contents of the file into the moby array `data' */ int desc = open (infile, 0, 0); if (desc < 0) fatal ("failure reopening %s", infile); for (file_size = 0; ; ) { if ((i = read (desc, data + file_size, total - file_size)) <= 0) break; file_size += i; } file_data = data; data[file_size] = 0; close (desc); if (file_size > 0 && data[0] != '\\') { error ("%s: not a texinfo index file", infile); return; } init_char_order (); /* Sort routines want to know this address */ text_base = data; /* Create the array of pointers to lines, with a default size frequently enough. */ lines = total / 50; if (!lines) lines = 2; linearray = (char **) xmalloc (lines * sizeof (char *)); /* `nextline' points to the next free slot in this array. `lines' is the allocated size. */ nextline = linearray; /* Parse the input file's data, and make entries for the lines. */ nextline = parsefile (infile, nextline, file_data, file_size); if (nextline == 0) { error ("%s: not a texinfo index file", infile); return; } /* Sort the lines */ /* If we have enough space, find the first keyfield of each line in advance. Make a `struct lineinfo' for each line, which records the keyfield as well as the line, and sort them. */ lineinfo = (struct lineinfo *) malloc ((nextline - linearray) * sizeof (struct lineinfo)); if (lineinfo) { struct lineinfo *lp; char **p; for (lp = lineinfo, p = linearray; p != nextline; lp++, p++) { lp->text = *p; lp->key.text = find_field (keyfields, *p, &lp->keylen); if (keyfields->numeric) lp->key.number = find_value (lp->key.text, lp->keylen); } qsort (lineinfo, nextline - linearray, sizeof (struct lineinfo), compare_prepared); for (lp = lineinfo, p = linearray; p != nextline; lp++, p++) *p = lp->text; free (lineinfo); } else qsort (linearray, nextline - linearray, sizeof (char *), compare_full); /* Open the output file */ if (outfile) { ostream = fopen (outfile, "w"); if (!ostream) pfatal_with_name (outfile); } writelines (linearray, nextline - linearray, ostream); if (outfile) fclose (ostream); free (linearray); free (data); } /* Parse an input string in core into lines. DATA is the input string, and SIZE is its length. Data goes in LINEARRAY starting at NEXTLINE. The value returned is the first entry in LINEARRAY still unused. Value 0 means input file contents are invalid. */ char ** parsefile (filename, nextline, data, size) char *filename; char **nextline; char *data; long size; { char *p, *end; char **line = nextline; p = data; end = p + size; *end = 0; while (p != end) { if (p[0] != '\\') return 0; *line = p; while (*p && *p != '\n') p++; if (p != end) p++; line++; if (line == linearray + lines) { char **old = linearray; linearray = (char **) xrealloc (linearray, sizeof (char *) * (lines *= 4)); line += linearray - old; } } return line; } /* Indexification is a filter applied to the sorted lines as they are being written to the output file. Multiple entries for the same name, with different page numbers, get combined into a single entry with multiple page numbers. The first braced field, which is used for sorting, is discarded. However, its first character is examined, folded to lower case, and if it is different from that in the previous line fed to us a \initial line is written with one argument, the new initial. If an entry has four braced fields, then the second and third constitute primary and secondary names. In this case, each change of primary name generates a \primary line which contains only the primary name, and in between these are \secondary lines which contain just a secondary name and page numbers. */ /* The last primary name we wrote a \primary entry for. If only one level of indexing is being done, this is the last name seen */ char *lastprimary; int lastprimarylength; /* Length of storage allocated for lastprimary */ /* Similar, for the secondary name. */ char *lastsecondary; int lastsecondarylength; /* Zero if we are not in the middle of writing an entry. One if we have written the beginning of an entry but have not yet written any page numbers into it. Greater than one if we have written the beginning of an entry plus at least one page number. */ int pending; /* The initial (for sorting purposes) of the last primary entry written. When this changes, a \initial {c} line is written */ char * lastinitial; int lastinitiallength; /* When we need a string of length 1 for the value of lastinitial, store it here. */ char lastinitial1[2]; /* Initialize static storage for writing an index */ void init_index () { pending = 0; lastinitial = lastinitial1; lastinitial1[0] = 0; lastinitial1[1] = 0; lastinitiallength = 0; lastprimarylength = 100; lastprimary = (char *) xmalloc (lastprimarylength + 1); bzero (lastprimary, lastprimarylength + 1); lastsecondarylength = 100; lastsecondary = (char *) xmalloc (lastsecondarylength + 1); bzero (lastsecondary, lastsecondarylength + 1); } /* Indexify. Merge entries for the same name, insert headers for each initial character, etc. */ indexify (line, ostream) char *line; FILE *ostream; { char *primary, *secondary, *pagenumber; int primarylength, secondarylength, pagelength; int len = strlen (line); int nosecondary; int initiallength; char *initial; char initial1[2]; register char *p; /* First, analyze the parts of the entry fed to us this time */ p = find_braced_pos (line, 0, 0, 0); if (*p == '{') { initial = p; /* Get length of inner pair of braces starting at p, including that inner pair of braces. */ initiallength = find_braced_end (p + 1) + 1 - p; } else { initial = initial1; initial1[0] = *p; initial1[1] = 0; initiallength = 1; if (initial1[0] >= 'a' && initial1[0] <= 'z') initial1[0] -= 040; } pagenumber = find_braced_pos (line, 1, 0, 0); pagelength = find_braced_end (pagenumber) - pagenumber; if (pagelength == 0) abort (); primary = find_braced_pos (line, 2, 0, 0); primarylength = find_braced_end (primary) - primary; secondary = find_braced_pos (line, 3, 0, 0); nosecondary = !*secondary; if (!nosecondary) secondarylength = find_braced_end (secondary) - secondary; /* If the primary is different from before, make a new primary entry */ if (strncmp (primary, lastprimary, primarylength)) { /* Close off current secondary entry first, if one is open */ if (pending) { fputs ("}\n", ostream); pending = 0; } /* If this primary has a different initial, include an entry for the initial */ if (initiallength != lastinitiallength || strncmp (initial, lastinitial, initiallength)) { fprintf (ostream, "\\initial {"); fwrite (initial, 1, initiallength, ostream); fprintf (ostream, "}\n", initial); if (initial == initial1) { lastinitial = lastinitial1; *lastinitial1 = *initial1; } else { lastinitial = initial; } lastinitiallength = initiallength; } /* Make the entry for the primary. */ if (nosecondary) fputs ("\\entry {", ostream); else fputs ("\\primary {", ostream); fwrite (primary, primarylength, 1, ostream); if (nosecondary) { fputs ("}{", ostream); pending = 1; } else fputs ("}\n", ostream); /* Record name of most recent primary */ if (lastprimarylength < primarylength) { lastprimarylength = primarylength + 100; lastprimary = (char *) xrealloc (lastprimary, 1 + lastprimarylength); } strncpy (lastprimary, primary, primarylength); lastprimary[primarylength] = 0; /* There is no current secondary within this primary, now */ lastsecondary[0] = 0; } /* Should not have an entry with no subtopic following one with a subtopic */ if (nosecondary && *lastsecondary) error ("entry %s follows an entry with a secondary name", line); /* Start a new secondary entry if necessary */ if (!nosecondary && strncmp (secondary, lastsecondary, secondarylength)) { if (pending) { fputs ("}\n", ostream); pending = 0; } /* Write the entry for the secondary. */ fputs ("\\secondary {", ostream); fwrite (secondary, secondarylength, 1, ostream); fputs ("}{", ostream); pending = 1; /* Record name of most recent secondary */ if (lastsecondarylength < secondarylength) { lastsecondarylength = secondarylength + 100; lastsecondary = (char *) xrealloc (lastsecondary, 1 + lastsecondarylength); } strncpy (lastsecondary, secondary, secondarylength); lastsecondary[secondarylength] = 0; } /* Here to add one more page number to the current entry */ if (pending++ != 1) fputs (", ", ostream); /* Punctuate first, if this is not the first */ fwrite (pagenumber, pagelength, 1, ostream); } /* Close out any unfinished output entry */ void finish_index (ostream) FILE *ostream; { if (pending) fputs ("}\n", ostream); free (lastprimary); free (lastsecondary); } /* Copy the lines in the sorted order. Each line is copied out of the input file it was found in. */ void writelines (linearray, nlines, ostream) char **linearray; int nlines; FILE *ostream; { char **stop_line = linearray + nlines; char **next_line; init_index (); /* Output the text of the lines, and free the buffer space */ for (next_line = linearray; next_line != stop_line; next_line++) { /* If -u was specified, output the line only if distinct from previous one. */ if (next_line == linearray /* Compare previous line with this one, using only the explicitly specd keyfields */ || compare_general (*(next_line - 1), *next_line, 0L, 0L, num_keyfields - 1)) { char *p = *next_line; char c; while ((c = *p++) && c != '\n'); *(p-1) = 0; indexify (*next_line, ostream); } } finish_index (ostream); } /* Assume (and optionally verify) that each input file is sorted; merge them and output the result. Returns nonzero if any input file fails to be sorted. This is the high-level interface that can handle an unlimited number of files. */ #define MAX_DIRECT_MERGE 10 int merge_files (infiles, nfiles, outfile) char **infiles; int nfiles; char *outfile; { char **tempfiles; int ntemps; int i; int value = 0; int start_tempcount = tempcount; if (nfiles <= MAX_DIRECT_MERGE) return merge_direct (infiles, nfiles, outfile); /* Merge groups of MAX_DIRECT_MERGE input files at a time, making a temporary file to hold each group's result. */ ntemps = (nfiles + MAX_DIRECT_MERGE - 1) / MAX_DIRECT_MERGE; tempfiles = (char **) xmalloc (ntemps * sizeof (char *)); for (i = 0; i < ntemps; i++) { int nf = MAX_DIRECT_MERGE; if (i + 1 == ntemps) nf = nfiles - i * MAX_DIRECT_MERGE; tempfiles[i] = maketempname (++tempcount); value |= merge_direct (&infiles[i * MAX_DIRECT_MERGE], nf, tempfiles[i]); } /* All temporary files that existed before are no longer needed since their contents have been merged into our new tempfiles. So delete them. */ flush_tempfiles (start_tempcount); /* Now merge the temporary files we created. */ merge_files (tempfiles, ntemps, outfile); free (tempfiles); return value; } /* Assume (and optionally verify) that each input file is sorted; merge them and output the result. Returns nonzero if any input file fails to be sorted. This version of merging will not work if the number of input files gets too high. Higher level functions use it only with a bounded number of input files. */ int merge_direct (infiles, nfiles, outfile) char **infiles; int nfiles; char *outfile; { char **ip = infiles; struct linebuffer *lb1, *lb2; struct linebuffer **thisline, **prevline; FILE **streams; int i; int nleft; int lossage = 0; int *file_lossage; struct linebuffer *prev_out = 0; FILE *ostream = stdout; if (outfile) { ostream = fopen (outfile, "w"); } if (!ostream) pfatal_with_name (outfile); init_index (); if (nfiles == 0) { if (outfile) fclose (ostream); return 0; } /* For each file, make two line buffers. Also, for each file, there is an element of `thisline' which points at any time to one of the file's two buffers, and an element of `prevline' which points to the other buffer. `thisline' is supposed to point to the next available line from the file, while `prevline' holds the last file line used, which is remembered so that we can verify that the file is properly sorted. */ /* lb1 and lb2 contain one buffer each per file */ lb1 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer)); lb2 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer)); /* thisline[i] points to the linebuffer holding the next available line in file i, or is zero if there are no lines left in that file. */ thisline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *)); /* prevline[i] points to the linebuffer holding the last used line from file i. This is just for verifying that file i is properly sorted. */ prevline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *)); /* streams[i] holds the input stream for file i. */ streams = (FILE **) xmalloc (nfiles * sizeof (FILE *)); /* file_lossage[i] is nonzero if we already know file i is not properly sorted. */ file_lossage = (int *) xmalloc (nfiles * sizeof (int)); /* Allocate and initialize all that storage */ for (i = 0; i < nfiles; i++) { initbuffer (&lb1[i]); initbuffer (&lb2[i]); thisline[i] = &lb1[i]; prevline[i] = &lb2[i]; file_lossage[i] = 0; streams[i] = fopen (infiles[i], "r"); if (!streams[i]) pfatal_with_name (infiles[i]); readline (thisline[i], streams[i]); } /* Keep count of number of files not at eof */ nleft = nfiles; while (nleft) { struct linebuffer *best = 0; struct linebuffer *exch; int bestfile = -1; int i; /* Look at the next avail line of each file; choose the least one. */ for (i = 0; i < nfiles; i++) { if (thisline[i] && (!best || 0 < compare_general (best->buffer, thisline[i]->buffer, (long) bestfile, (long) i, num_keyfields))) { best = thisline[i]; bestfile = i; } } /* Output that line, unless it matches the previous one and we don't want duplicates */ if (!(prev_out && !compare_general (prev_out->buffer, best->buffer, 0L, 1L, num_keyfields - 1))) indexify (best->buffer, ostream); prev_out = best; /* Now make the line the previous of its file, and fetch a new line from that file */ exch = prevline[bestfile]; prevline[bestfile] = thisline[bestfile]; thisline[bestfile] = exch; while (1) { /* If the file has no more, mark it empty */ if (feof (streams[bestfile])) { thisline[bestfile] = 0; nleft--; /* Update the number of files still not empty */ break; } readline (thisline[bestfile], streams[bestfile]); if (thisline[bestfile]->buffer[0] || !feof (streams[bestfile])) break; } } finish_index (ostream); /* Free all storage and close all input streams */ for (i = 0; i < nfiles; i++) { fclose (streams[i]); free (lb1[i].buffer); free (lb2[i].buffer); } free (file_lossage); free (lb1); free (lb2); free (thisline); free (prevline); free (streams); if (outfile) fclose (ostream); return lossage; } /* Print error message and exit. */ fatal (s1, s2) char *s1, *s2; { error (s1, s2); exit (EXIT_FATAL); } /* Print error message. `s1' is printf control string, `s2' is arg for it. */ error (s1, s2) char *s1, *s2; { printf ("texindex: "); printf (s1, s2); printf ("\n"); } perror_with_name (name) char *name; { #ifdef VMS #include extern noshare int sys_nerr; extern noshare char *sys_errlist[]; #else extern int errno, sys_nerr; extern char *sys_errlist[]; #endif char *s; if (errno < sys_nerr) s = concat ("", sys_errlist[errno], " for %s"); else s = "cannot open %s"; error (s, name); } pfatal_with_name (name) char *name; { extern int errno, sys_nerr; extern char *sys_errlist[]; char *s; if (errno < sys_nerr) s = concat ("", sys_errlist[errno], " for %s"); else s = "cannot open %s"; fatal (s, name); } /* Return a newly-allocated string whose contents concatenate those of s1, s2, s3. */ char * concat (s1, s2, s3) char *s1, *s2, *s3; { int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3); char *result = (char *) xmalloc (len1 + len2 + len3 + 1); strcpy (result, s1); strcpy (result + len1, s2); strcpy (result + len1 + len2, s3); *(result + len1 + len2 + len3) = 0; return result; } /* Like malloc but get fatal error if memory is exhausted. */ int xmalloc (size) int size; { int result = malloc (size); if (!result) fatal ("virtual memory exhausted", 0); return result; } int xrealloc (ptr, size) char *ptr; int size; { int result = realloc (ptr, size); if (!result) fatal ("virtual memory exhausted"); return result; } bzero (b, length) register char *b; register int length; { #ifdef VMS short zero = 0; long max_str = 65535; while (length > max_str) { (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b); length -= max_str; b += max_str; } (void) LIB$MOVC5 (&zero, &zero, &zero, &length, b); #else while (length-- > 0) *b++ = 0; #endif /* not VMS */ } gawk-2.11/support/texinfo.tex 644 11660 0 222206 4507516523 14533 0ustar hackwheel%% TeX macros to handle texinfo files % Copyright (C) 1985, 1986, 1988 Free Software Foundation, Inc. %GNU CC is free software; you can redistribute it and/or modify %it under the terms of the GNU General Public License as published by %the Free Software Foundation; either version 1, or (at your option) %any later version. %GNU CC is distributed in the hope that it will be useful, %but WITHOUT ANY WARRANTY; without even the implied warranty of %MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %GNU General Public License for more details. %You should have received a copy of the GNU General Public License %along with GNU CC; see the file COPYING. If not, write to %the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. %In other words, you are welcome to use, share and improve this program. %You are forbidden to forbid anyone else to use, share and improve %what you give them. Help stamp out software-hoarding! \def\texinfoversion{2.1} \message{Loading texinfo package [Version \texinfoversion]:} \message{} % Save some parts of plain tex whose names we will redefine. \let\ptexlbrace=\{ \let\ptexrbrace=\} \let\ptexdot=\. \let\ptexstar=\* \let\ptexend=\end \let\ptexbullet=\bullet \let\ptexb=\b \let\ptexc=\c \let\ptexi=\i \let\ptext=\t \let\ptexl=\l \let\ptexL=\L \def\tie{\penalty 10000\ } % Save plain tex definition of ~. \message{Basics,} \chardef\other=12 \hyphenation{ap-pen-dix} \hyphenation{mini-buf-fer mini-buf-fers} \hyphenation{eshell} % Margin to add to right of even pages, to left of odd pages. \newdimen \bindingoffset \bindingoffset=0pt \newdimen \normaloffset \normaloffset=\hoffset \newdimen\pagewidth \newdimen\pageheight \pagewidth=\hsize \pageheight=\vsize %---------------------Begin change----------------------- % % Dimensions to add cropmarks at corners Added by P. A. MacKay, 12 Nov. 1986 % \newdimen\cornerlong \newdimen\cornerthick \newdimen \topandbottommargin \newdimen \outerhsize \newdimen \outervsize \cornerlong=1pc\cornerthick=.3pt % These set size of cropmarks \outerhsize=7in \outervsize=9.5in \topandbottommargin=.75in % %---------------------End change----------------------- % \onepageout takes a vbox as an argument. Note that \pagecontents % does insertions itself, but you have to call it yourself. \chardef\PAGE=255 \output={\onepageout{\pagecontents\PAGE}} \def\onepageout#1{\hoffset=\normaloffset \ifodd\pageno \advance\hoffset by \bindingoffset \else \advance\hoffset by -\bindingoffset\fi \shipout\vbox{{\let\hsize=\pagewidth \makeheadline} \pagebody{#1}% {\let\hsize=\pagewidth \makefootline}} \advancepageno \ifnum\outputpenalty>-20000 \else\dosupereject\fi} % Here is a modification of the main output routine for Near East Publications % This provides right-angle cropmarks at all four corners. % The contents of the page are centerlined into the cropmarks, % and any desired binding offset is added as an \hskip on either % site of the centerlined box. (P. A. MacKay, 12 November, 1986) % \def\croppageout#1{\hoffset=0pt % make sure this doesn't mess things up \shipout \vbox to \outervsize{\hsize=\outerhsize \vbox{\line{\ewtop\hfill\ewtop}} \nointerlineskip \line{\vbox{\moveleft\cornerthick\nstop} \hfill \vbox{\moveright\cornerthick\nstop}} \vskip \topandbottommargin \centerline{\ifodd\pageno\hskip\bindingoffset\fi \vbox{ {\let\hsize=\pagewidth \makeheadline} \pagebody{#1} {\let\hsize=\pagewidth \makefootline}} \ifodd\pageno\else\hskip\bindingoffset\fi} \vskip \topandbottommargin plus1fill minus1fill \boxmaxdepth\cornerthick \line{\vbox{\moveleft\cornerthick\nsbot} \hfill \vbox{\moveright\cornerthick\nsbot}} \nointerlineskip \vbox{\line{\ewbot\hfill\ewbot}} } \advancepageno \ifnum\outputpenalty>-20000 \else\dosupereject\fi} % % Do @cropmarks to get crop marks \def\cropmarks{\let\onepageout=\croppageout } \def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}} {\catcode`\@ =11 \gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi \dimen@=\dp#1 \unvbox#1 \ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi \ifr@ggedbottom \kern-\dimen@ \vfil \fi} } % % Here are the rules for the cropmarks. Note that they are % offset so that the space between them is truly \outerhsize or \outervsize % (P. A. MacKay, 12 November, 1986) % \def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong} \def\nstop{\vbox {\hrule height\cornerthick depth\cornerlong width\cornerthick}} \def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong} \def\nsbot{\vbox {\hrule height\cornerlong depth\cornerthick width\cornerthick}} % Parse an argument, then pass it to #1. % The argument can be delimited with [...] or with "..." or braces % or it can be a whole line. % #1 should be a macro which expects % an ordinary undelimited TeX argument. \def\parsearg #1{\let\next=#1\begingroup\obeylines\futurelet\temp\parseargx} \def\parseargx{% \ifx \obeyedspace\temp \aftergroup\parseargdiscardspace \else% \aftergroup \parseargline % \fi \endgroup} {\obeyspaces % \gdef\parseargdiscardspace {\begingroup\obeylines\futurelet\temp\parseargx}} \gdef\obeyedspace{\ } \def\parseargline{\begingroup \obeylines \parsearglinex} {\obeylines % \gdef\parsearglinex #1^^M{\endgroup \next {#1}}} \def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next} %% These are used to keep @begin/@end levels from running away %% Call \inENV within environments (after a \begingroup) \newif\ifENV \ENVfalse \def\inENV{\ifENV\relax\else\ENVtrue\fi} \def\ENVcheck{% \ifENV\errmessage{Still within an environment. Type Return to continue.} \endgroup\fi} % This is not perfect, but it should reduce lossage % @begin foo is the same as @foo, for now. \newhelp\EMsimple{Type to continue} \outer\def\begin{\parsearg\beginxxx} \def\beginxxx #1{% \expandafter\ifx\csname #1\endcsname\relax {\errhelp=\EMsimple \errmessage{Undefined command @begin #1}}\else \csname #1\endcsname\fi} %% @end foo executes the definition of \Efoo. %% foo can be delimited by doublequotes or brackets. \def\end{\parsearg\endxxx} \def\endxxx #1{% \expandafter\ifx\csname E#1\endcsname\relax \expandafter\ifx\csname #1\endcsname\relax \errmessage{Undefined command @end #1}\else \errorE{#1}\fi\fi \csname E#1\endcsname} \def\errorE#1{ {\errhelp=\EMsimple \errmessage{@end #1 not within #1 environment}}} % Single-spacing is done by various environments. \newskip\singlespaceskip \singlespaceskip = \baselineskip \def\singlespace{% {\advance \baselineskip by -\singlespaceskip \kern \baselineskip}% \baselineskip=\singlespaceskip } %% Simple single-character @ commands % @@ prints an @ % Kludge this until the fonts are right (grr). \def\@{{\sf \char '100}} % Define @` and @' to be the same as ` and ' % but suppressing ligatures. \def\`{{`}} \def\'{{'}} % Used to generate quoted braces. \def\mylbrace {{\tt \char '173}} \def\myrbrace {{\tt \char '175}} \let\{=\mylbrace \let\}=\myrbrace % @: forces normal size whitespace following. \def\:{\spacefactor=1000 } % @* forces a line break. \def\*{\hfil\break} % @. is an end-of-sentence period. \def\.{.\spacefactor=3000 } % @w prevents a word break \def\w #1{\hbox{#1}} % @group ... @end group forces ... to be all on one page. \def\group{\begingroup% \inENV ??? \def \Egroup{\egroup\endgroup} \vbox\bgroup} % @br forces paragraph break \let\br = \par % @dots{} output some dots \def\dots{$\ldots$} % @page forces the start of a new page \def\page{\par\vfill\supereject} % @exdent text.... % outputs text on separate line in roman font, starting at standard page margin \def\exdent{\errmessage{@exdent in filled text}} % @lisp, etc, define \exdent locally from \internalexdent {\obeyspaces \gdef\internalexdent{\parsearg\exdentzzz}} \def\exdentzzz #1{{\advance \leftskip by -\lispnarrowing \advance \hsize by -\leftskip \advance \hsize by -\rightskip \leftline{{\rm#1}}}} % @include file insert text of that file as input. \def\include{\parsearg\includezzz} \def\includezzz #1{{\def\thisfile{#1}\input #1 }} \def\thisfile{} % @center line outputs that line, centered \def\center{\parsearg\centerzzz} \def\centerzzz #1{{\advance\hsize by -\leftskip \advance\hsize by -\rightskip \centerline{#1}}} % @sp n outputs n lines of vertical space \def\sp{\parsearg\spxxx} \def\spxxx #1{\par \vskip #1\baselineskip} % @comment ...line which is ignored... % @c is the same as @comment % @ignore ... @end ignore is another way to write a comment \def\comment{\parsearg \commentxxx} \def\commentxxx #1{} \let\c=\comment % Prevent errors for section commands. % Used in @ignore and in failing conditionals. \def\ignoresections{% \let\chapter=\relax \let\unnumbered=\relax \let\unnumberedsec=\relax \let\unnumberedsection=\relax \let\unnumberedsubsec=\relax \let\unnumberedsubsection=\relax \let\unnumberedsubsubsec=\relax \let\unnumberedsubsubsection=\relax \let\section=\relax \let\subsec=\relax \let\subsubsec=\relax \let\subsection=\relax \let\subsubsection=\relax \let\appendix=\relax \let\appendixsec=\relax \let\appendixsection=\relax \let\appendixsubsec=\relax \let\appendixsubsection=\relax \let\appendixsubsubsec=\relax \let\appendixsubsubsection=\relax } \def\ignore{\begingroup\ignoresections\ignorexxx} \long\def\ignorexxx #1\end ignore{\endgroup} % Conditionals to test whether a flag is set. \outer\def\ifset{\begingroup\ignoresections\parsearg\ifsetxxx} \def\ifsetxxx #1{\endgroup \expandafter\ifx\csname IF#1\endcsname\relax \let\temp=\ifsetfail \else \let\temp=\relax \fi \temp} \def\Eifset{} \def\ifsetfail{\begingroup\ignoresections\ifsetfailxxx} \long\def\ifsetfailxxx #1\end ifset{\endgroup} \outer\def\ifclear{\begingroup\ignoresections\parsearg\ifclearxxx} \def\ifclearxxx #1{\endgroup \expandafter\ifx\csname IF#1\endcsname\relax \let\temp=\relax \else \let\temp=\ifclearfail \fi \temp} \def\Eifclear{} \def\ifclearfail{\begingroup\ignoresections\ifclearfailxxx} \long\def\ifclearfailxxx #1\end ifclear{\endgroup} % Some texinfo constructs that are trivial in tex \def\iftex{} \def\Eiftex{} \def\ifinfo{\begingroup\ignoresections\ifinfoxxx} \long\def\ifinfoxxx #1\end ifinfo{\endgroup} \long\def\menu #1\end menu{} \def\asis#1{#1} \def\node{\ENVcheck\parsearg\nodezzz} \def\nodezzz#1{\nodexxx [#1,]} \def\nodexxx[#1,#2]{\gdef\lastnode{#1}} \let\lastnode=\relax \def\donoderef{\ifx\lastnode\relax\else \expandafter\expandafter\expandafter\setref{\lastnode}\fi \let\lastnode=\relax} \def\unnumbnoderef{\ifx\lastnode\relax\else \expandafter\expandafter\expandafter\unnumbsetref{\lastnode}\fi \let\lastnode=\relax} \def\appendixnoderef{\ifx\lastnode\relax\else \expandafter\expandafter\expandafter\appendixsetref{\lastnode}\fi \let\lastnode=\relax} \let\refill=\relax % @setfilename is done at the beginning of every texinfo file. % So open here the files we need to have open while reading the input. % This makes it possible to make a .fmt file for texinfo. \def\setfilename{% \readauxfile \opencontents \openindices \fixbackslash % Turn off hack to swallow `\input texinfo'. \comment % Ignore the actual filename. } \outer\def\bye{\pagealignmacro\tracingstats=1\ptexend} \def\inforef #1{\inforefzzz #1,,,,**} \def\inforefzzz #1,#2,#3,#4**{See Info file \file{\losespace#3{}}, node `\losespace#1{}'} \def\losespace #1{#1} \message{fonts,} % Font-change commands. %% Try out Computer Modern fonts at \magstephalf \font\tenrm=cmr10 scaled \magstephalf \font\tentt=cmtt10 scaled \magstephalf % Instead of cmb10, you many want to use cmbx10. % cmbx10 is a prettier font on its own, but cmb10 % looks better when embedded in a line with cmr10. \font\tenbf=cmb10 scaled \magstephalf \font\tenit=cmti10 scaled \magstephalf \font\tensl=cmsl10 scaled \magstephalf \font\tensf=cmss10 scaled \magstephalf \def\li{\sf} \font\tensc=cmcsc10 scaled \magstephalf % Fonts for @defun, etc. \font\defbf=cmbx10 scaled \magstep1 %was 1314 \let\deftt=\tentt \def\df{\let\tt=\deftt \defbf} % Font for title \font\titlerm = cmbx10 scaled \magstep5 % Fonts for indices \font\indit=cmti9 \font\indrm=cmr9 \font\indtt=cmtt9 \def\indbf{\indrm} \def\indsl{\indit} \def\indexfonts{\let\it=\indit \let\sl=\indsl \let\bf=\indbf \let\rm=\indrm \let\tt=\indtt} % Fonts for headings \font\chaprm=cmbx10 scaled \magstep3 \font\chapit=cmti10 scaled \magstep3 \font\chapsl=cmsl10 scaled \magstep3 \font\chaptt=cmtt10 scaled \magstep3 \font\chapsf=cmss10 scaled \magstep3 \let\chapbf=\chaprm \font\secrm=cmbx10 scaled \magstep2 \font\secit=cmti10 scaled \magstep2 \font\secsl=cmsl10 scaled \magstep2 \font\sectt=cmtt10 scaled \magstep2 \font\secsf=cmss10 scaled \magstep2 \let\secbf=\secrm % \font\ssecrm=cmbx10 scaled \magstep1 % This size an fontlooked bad. % \font\ssecit=cmti10 scaled \magstep1 % The letters were too crowded. % \font\ssecsl=cmsl10 scaled \magstep1 % \font\ssectt=cmtt10 scaled \magstep1 % \font\ssecsf=cmss10 scaled \magstep1 \font\ssecrm=cmb10 at 13pt % Note the use of cmb rather than cmbx. \font\ssecit=cmti10 at 13pt % Also, the size is a little larger than \font\ssecsl=cmsl10 at 13pt % being scaled magstep1. \font\ssectt=cmtt10 at 13pt \font\ssecsf=cmss10 at 13pt \let\ssecbf=\ssecrm \def\textfonts{\let\rm=\tenrm\let\it=\tenit\let\sl=\tensl\let\bf=\tenbf% \let\smallcaps=\tensc\let\sf=\tensf} \def\chapfonts{\let\rm=\chaprm\let\it=\chapit\let\sl=\chapsl\let\bf=\chapbf\let\tt=\chaptt\let\sf=\chapsf} \def\secfonts{\let\rm=\secrm\let\it=\secit\let\sl=\secsl\let\bf=\secbf\let\tt=\sectt\let\sf=\secsf} \def\subsecfonts{\let\rm=\ssecrm\let\it=\ssecit\let\sl=\ssecsl\let\bf=\ssecbf\let\tt=\ssectt\let\sf=\ssecsf} % Count depth in font-changes, for error checks \newcount\fontdepth \fontdepth=0 % Font for table of contents. \font\truesecrm=cmr12 %% Add scribe-like font environments, plus @l for inline lisp (usually sans %% serif) and @ii for TeX italic % \smartitalic{ARG} outputs arg in italics, followed by an italic correction % unless the following character is such as not to need one. \def\smartitalicx{\ifx\next,\else\ifx\next-\else\ifx\next.\else\/\fi\fi\fi} \def\smartitalic#1{{\sl #1}\futurelet\next\smartitalicx} \let\i=\smartitalic \let\var=\smartitalic \let\dfn=\smartitalic \let\emph=\smartitalic \let\cite=\smartitalic \def\b#1{{\bf #1}} \let\strong=\b \def\t#1{{\tt \rawbackslash \frenchspacing #1}\null} \let\ttfont = \t %\def\samp #1{`{\tt \rawbackslash \frenchspacing #1}'\null} \def\samp #1{`\tclose{#1}'\null} \def\key #1{{\tt \uppercase{#1}}\null} \def\ctrl #1{{\tt \rawbackslash \hat}#1} \let\file=\samp % @code is a modification of @t, % which makes spaces the same size as normal in the surrounding text. \newdimen\tclosesave \newdimen\tcloserm \def\tclose#1{{\rm \tcloserm=\fontdimen2\font \tt \tclosesave=\fontdimen2\font \fontdimen2\font=\tcloserm \def\ {{\fontdimen2\font=\tclosesave{} }}% \rawbackslash \frenchspacing #1\fontdimen2\font=\tclosesave}\null} \let\code=\tclose %\let\exp=\tclose %Was temporary % @kbd is like @code, except that if the argument is just one @key command, % then @kbd has no effect. \def\xkey{\key} \def\kbdfoo#1#2#3*{\def\one{#1}\def\three{#3}\def\threex{??}% \ifx\one\xkey\ifx\threex\three \key{#2} \else\tclose{\look}\fi \else\tclose{\look}\fi} \def\kbd#1{\def\look{#1}\expandafter\kbdfoo\look??*} \def\l#1{{\li #1}\null} % \def\r#1{{\rm #1}} % roman font \def\sc#1{{\smallcaps #1}} % smallcaps font \def\ii#1{{\it #1}} % italic font \message{page headings,} \newskip\titlepagetopglue \titlepagetopglue = 1.5in \newskip\titlepagebottomglue \titlepagebottomglue = 2pc % First the title page. Must do @settitle before @titlepage. \font\titlerm = cmbx12 scaled \magstep2 \def\titlefont#1{{\titlerm #1}} \newtoks\realeverypar \newif\ifseenauthor \def\titlepage{\begingroup \parindent=0pt \textfonts \font\subtitlerm = cmr10 scaled \magstephalf \def\subtitlefont{\subtitlerm \normalbaselineskip = 12pt \normalbaselines}% % \font\authorrm = cmbx12 scaled \magstep1 \def\authorfont{\authorrm \normalbaselineskip = 16pt \normalbaselines}% % % The first subtitle should have some space before it, but not the % others. They all should be ragged left. % This code caused a bug, since two groups were started, but only % one was ended. Also, I can't see the point of this code. % \begingroup \realeverypar = {\leftskip = 2in plus 3em minus 1em % \parfillskip = 0pt}% % \everypar = {\vglue \baselineskip \the\realeverypar % \everypar={\the\realeverypar}}% % % Now you can print the title using @title. \def\title{\parsearg\titlezzz}% \def\titlezzz##1{\leftline{\titlefont{##1} \vskip4pt \hrule height 4pt \vskip4pt}}% \vglue\titlepagetopglue % % Now you can put text using @subtitle. \def\subtitle{\parsearg\subtitlezzz}% \def\subtitlezzz##1{{\subtitlefont \rightline{##1}}}% % % @author should come last, but may come many times. \def\author{\parsearg\authorzzz}% \def\authorzzz##1{\ifseenauthor\else\vskip 0pt plus 1filll\seenauthortrue\fi {\authorfont \leftline{##1}}}% % % Most title ``pages'' are actually two pages long, with space % at the top of the second. We don't want the ragged left on the second. \let\oldpage = \page % \def\page{\vskip4pt \hrule height 2pt \vskip\titlepagebottomglue % \oldpage \endgroup\hrule height0pt\relax}% \def\page{\oldpage \hbox{}} } \def\Etitlepage{\endgroup\page\HEADINGSon} %%% Set up page headings and footings. \let\thispage=\folio \newtoks \evenheadline % Token sequence for heading line of even pages \newtoks \oddheadline % Token sequence for heading line of odd pages \newtoks \evenfootline % Token sequence for footing line of even pages \newtoks \oddfootline % Token sequence for footing line of odd pages % Now make Tex use those variables \headline={{\textfonts\rm \ifodd\pageno \the\oddheadline \else \the\evenheadline \fi}} \footline={{\textfonts\rm \ifodd\pageno \the\oddfootline \else \the\evenfootline \fi}} % Commands to set those variables. % For example, this is what @headings on does % @evenheading @thistitle|@thispage|@thischapter % @oddheading @thischapter|@thispage|@thistitle % @evenfooting @thisfile|| % @oddfooting ||@thisfile \def\evenheading{\parsearg\evenheadingxxx} \def\oddheading{\parsearg\oddheadingxxx} \def\everyheading{\parsearg\everyheadingxxx} \def\evenfooting{\parsearg\evenfootingxxx} \def\oddfooting{\parsearg\oddfootingxxx} \def\everyfooting{\parsearg\everyfootingxxx} {\catcode`\@=0 % \gdef\evenheadingxxx #1{\evenheadingyyy #1@|@|@|@|\finish} \gdef\evenheadingyyy #1@|#2@|#3@|#4\finish{% \global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \gdef\oddheadingxxx #1{\oddheadingyyy #1@|@|@|@|\finish} \gdef\oddheadingyyy #1@|#2@|#3@|#4\finish{% \global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \gdef\everyheadingxxx #1{\everyheadingyyy #1@|@|@|@|\finish} \gdef\everyheadingyyy #1@|#2@|#3@|#4\finish{% \global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}} \global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \gdef\evenfootingxxx #1{\evenfootingyyy #1@|@|@|@|\finish} \gdef\evenfootingyyy #1@|#2@|#3@|#4\finish{% \global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \gdef\oddfootingxxx #1{\oddfootingyyy #1@|@|@|@|\finish} \gdef\oddfootingyyy #1@|#2@|#3@|#4\finish{% \global\oddfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \gdef\everyfootingxxx #1{\everyfootingyyy #1@|@|@|@|\finish} \gdef\everyfootingyyy #1@|#2@|#3@|#4\finish{% \global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}} \global\oddfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} % }% unbind the catcode of @. % @headings double turns headings on for double-sided printing. % @headings single turns headings on for single-sided printing. % @headings off turns them off. % @headings on same as @headings double, retained for compatibility. % By default, they are off. \def\headings #1 {\csname HEADINGS#1\endcsname} \def\HEADINGSoff{ \global\evenheadline={\hfil} \global\evenfootline={\hfil} \global\oddheadline={\hfil} \global\oddfootline={\hfil}} \HEADINGSoff % When we turn headings on, set the page number to 1. % For double-sided printing, put current file name in lower left corner, % chapter name on inside top of right hand pages, document % title on inside top of left hand pages, and page numbers on outside top % edge of all pages. \def\HEADINGSdouble{ %\pagealignmacro \global\pageno=1 \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\folio\hfil\thistitle}} \global\oddheadline={\line{\thischapter\hfil\folio}} } % For single-sided printing, chapter title goes across top left of page, % page number on top right. \def\HEADINGSsingle{ %\pagealignmacro \global\pageno=1 \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} \global\oddheadline={\line{\thischapter\hfil\folio}} } \def\HEADINGSon{\HEADINGSdouble} % Subroutines used in generating headings % Produces Day Month Year style of output. \def\today{\number\day\space \ifcase\month\or January\or February\or March\or April\or May\or June\or July\or August\or September\or October\or November\or December\fi \space\number\year} % Use this if you want the Month Day, Year style of output. %\def\today{\ifcase\month\or %January\or February\or March\or April\or May\or June\or %July\or August\or September\or October\or November\or December\fi %\space\number\day, \number\year} % @settitle line... specifies the title of the document, for headings % It generates no output of its own \def\thistitle{No Title} \def\settitle{\parsearg\settitlezzz} \def\settitlezzz #1{\gdef\thistitle{#1}} \message{tables,} % Tables -- @table, @ftable, @item(x), @kitem(x), @xitem(x). % default indentation of table text \newdimen\tableindent \tableindent=.8in % default indentation of @itemize and @enumerate text \newdimen\itemindent \itemindent=.3in % margin between end of table item and start of table text. \newdimen\itemmargin \itemmargin=.1in % used internally for \itemindent minus \itemmargin \newdimen\itemmax % Note @table and @ftable define @item, @itemx, etc., with these defs. % They also define \itemindex % to index the item name in whatever manner is desired (perhaps none). \def\internalBitem{\smallbreak \parsearg\itemzzz} \def\internalBitemx{\par \parsearg\itemzzz} \def\internalBxitem "#1"{\def\xitemsubtopix{#1} \smallbreak \parsearg\xitemzzz} \def\internalBxitemx "#1"{\def\xitemsubtopix{#1} \par \parsearg\xitemzzz} \def\internalBkitem{\smallbreak \parsearg\kitemzzz} \def\internalBkitemx{\par \parsearg\kitemzzz} \def\kitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \lastfunction}}\itemzzz {#1}} \def\xitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \xitemsubtopic}}\itemzzz {#1}} \def\itemzzz #1{\begingroup % \advance \hsize by -\rightskip % \advance \hsize by -\leftskip % \setbox0=\hbox{\itemfont{#1}}% \itemindex{#1}% \parskip=0in % \noindent % \ifdim \wd0>\itemmax % \vadjust{\penalty 10000}% \hbox to \hsize{\hskip -\tableindent\box0\hss}\ % \else % \hbox to 0pt{\hskip -\tableindent\box0\hss}% \fi % \endgroup % } \def\item{\errmessage{@item while not in a table}} \def\itemx{\errmessage{@itemx while not in a table}} \def\kitem{\errmessage{@kitem while not in a table}} \def\kitemx{\errmessage{@kitemx while not in a table}} \def\xitem{\errmessage{@xitem while not in a table}} \def\xitemx{\errmessage{@xitemx while not in a table}} %% Contains a kludge to get @end[description] to work \def\description{\tablez{\dontindex}{1}{}{}{}{}} \def\table{\begingroup\inENV\obeylines\obeyspaces\tablex} {\obeylines\obeyspaces% \gdef\tablex #1^^M{% \tabley\dontindex#1 \endtabley}} \def\ftable{\begingroup\inENV\obeylines\obeyspaces\ftablex} {\obeylines\obeyspaces% \gdef\ftablex #1^^M{% \tabley\fnitemindex#1 \endtabley}} \def\dontindex #1{} \def\fnitemindex #1{\doind {fn}{\code{#1}}}% {\obeyspaces % \gdef\tabley#1#2 #3 #4 #5 #6 #7\endtabley{\endgroup% \tablez{#1}{#2}{#3}{#4}{#5}{#6}}} \def\tablez #1#2#3#4#5#6{% \aboveenvbreak % \begingroup % \def\Edescription{\Etable}% Neccessary kludge. \let\itemindex=#1% \ifnum 0#3>0 \advance \leftskip by #3\mil \fi % \ifnum 0#4>0 \tableindent=#4\mil \fi % \ifnum 0#5>0 \advance \rightskip by #5\mil \fi % \def\itemfont{#2}% \itemmax=\tableindent % \advance \itemmax by -\itemmargin % \advance \leftskip by \tableindent % \parindent = 0pt \parskip = \smallskipamount \ifdim \parskip=0pt \parskip=2pt \fi% \def\Etable{\endgraf\endgroup\afterenvbreak}% \let\item = \internalBitem % \let\itemx = \internalBitemx % \let\kitem = \internalBkitem % \let\kitemx = \internalBkitemx % \let\xitem = \internalBxitem % \let\xitemx = \internalBxitemx % } % This is the counter used by @enumerate, which is really @itemize \newcount \itemno \def\itemize{\parsearg\itemizezzz} \def\itemizezzz #1{\itemizey {#1}{\Eitemize}} \def\itemizey #1#2{% \aboveenvbreak % \begingroup % \itemno = 0 % \itemmax=\itemindent % \advance \itemmax by -\itemmargin % \advance \leftskip by \itemindent % \parindent = 0pt \parskip = \smallskipamount \ifdim \parskip=0pt \parskip=2pt \fi% \def#2{\endgraf\endgroup\afterenvbreak}% \def\itemcontents{#1}% \let\item=\itemizeitem} \def\bullet{$\ptexbullet$} \def\minus{$-$} % Set sfcode to normal for the chars that usually have another value. % These are `.?!:;,' \def\frenchspacing{\sfcode46=1000 \sfcode63=1000 \sfcode33=1000 \sfcode58=1000 \sfcode59=1000 \sfcode44=1000 } \def\enumerate{\itemizey{\the\itemno.}\Eenumerate\flushcr} % Definition of @item while inside @itemize. \def\itemizeitem{% \advance\itemno by 1 {\let\par=\endgraf \smallbreak}% \ifhmode \errmessage{\in hmode at itemizeitem}\fi {\parskip=0in \hskip 0pt \hbox to 0pt{\hss \itemcontents\hskip \itemmargin}% \vadjust{\penalty 300}}% \flushcr} \message{indexing,} % Index generation facilities % Define \newwrite to be identical to plain tex's \newwrite % except not \outer, so it can be used within \newindex. {\catcode`\@=11 \gdef\newwrite{\alloc@7\write\chardef\sixt@@n}} % \newindex {foo} defines an index named foo. % It automatically defines \fooindex such that % \fooindex ...rest of line... puts an entry in the index foo. % It also defines \fooindfile to be the number of the output channel for % the file that accumulates this index. The file's extension is foo. % The name of an index should be no more than 2 characters long % for the sake of vms. \def\newindex #1{ \expandafter\newwrite \csname#1indfile\endcsname% Define number for output file \openout \csname#1indfile\endcsname \jobname.#1 % Open the file \expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex \noexpand\doindex {#1}} } % @defindex foo == \newindex{foo} \def\defindex{\parsearg\newindex} % Define @defcodeindex, like @defindex except put all entries in @code. \def\newcodeindex #1{ \expandafter\newwrite \csname#1indfile\endcsname% Define number for output file \openout \csname#1indfile\endcsname \jobname.#1 % Open the file \expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex \noexpand\docodeindex {#1}} } \def\defcodeindex{\parsearg\newcodeindex} % @synindex foo bar makes index foo feed into index bar. % Do this instead of @defindex foo if you don't want it as a separate index. \def\synindex #1 #2 {% \expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex \noexpand\doindex {#2}}% } % @syncodeindex foo bar similar, but put all entries made for index foo % inside @code. \def\syncodeindex #1 #2 {% \expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex \noexpand\docodeindex {#2}}% } % Define \doindex, the driver for all \fooindex macros. % Argument #1 is generated by the calling \fooindex macro, % and it is "foo", the name of the index. % \doindex just uses \parsearg; it calls \doind for the actual work. % This is because \doind is more useful to call from other macros. % There is also \dosubind {index}{topic}{subtopic} % which makes an entry in a two-level index such as the operation index. \def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer} \def\singleindexer #1{\doind{\indexname}{#1}} % like the previous two, but they put @code around the argument. \def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer} \def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}} \def\indexdummies{% \def\bf{\realbackslash bf }% \def\rm{\realbackslash rm }% \def\sl{\realbackslash sl }% \def\dots{\realbackslash dots }% \def\copyright{\realbackslash copyright }% \def\tclose##1{\realbackslash tclose {##1}}% \def\code##1{\realbackslash code {##1}}% \def\samp##1{\realbackslash samp {##1}}% \def\r##1{\realbackslash r {##1}}% \def\i##1{\realbackslash i {##1}}% \def\b##1{\realbackslash b {##1}}% \def\cite##1{\realbackslash cite {##1}}% \def\key##1{\realbackslash key {##1}}% \def\file##1{\realbackslash file {##1}}% \def\var##1{\realbackslash var {##1}}% \def\kbd##1{\realbackslash kbd {##1}}% } % \indexnofonts no-ops all font-change commands. % This is used when outputting the strings to sort the index by. \def\indexdummyfont#1{#1} \def\indexnofonts{% \let\r=\indexdummyfont \let\i=\indexdummyfont \let\b=\indexdummyfont \let\emph=\indexdummyfont \let\strong=\indexdummyfont \let\cite=\indexdummyfont \let\sc=\indexdummyfont %Don't no-op \tt, since it isn't a user-level command % and is used in the definitions of the actuve chars like <, >, |... %\let\tt=\indexdummyfont \let\tclose=\indexdummyfont \let\code=\indexdummyfont \let\file=\indexdummyfont \let\samp=\indexdummyfont \let\kbd=\indexdummyfont \let\key=\indexdummyfont \let\var=\indexdummyfont } % To define \realbackslash, we must make \ not be an escape. % We must first make another character (@) an escape % so we do not become unable to do a definition. {\catcode`\@=0 \catcode`\\=\other @gdef@realbackslash{\}} \let\indexbackslash=0 %overridden during \printindex. \def\doind #1#2{% {\indexdummies % Must do this here, since \bf, etc expand at this stage \count10=\lastpenalty % \escapechar=`\\% {\let\folio=0% Expand all macros now EXCEPT \folio \def\rawbackslashxx{\indexbackslash}% \indexbackslash isn't defined now % so it will be output as is; and it will print as backslash in the indx. % % Now process the index-string once, with all font commands turned off, % to get the string to sort the index by. {\indexnofonts \xdef\temp1{#2}% }% % Now produce the complete index entry. We process the index-string again, % this time with font commands expanded, to get what to print in the index. \edef\temp{% \write \csname#1indfile\endcsname{% \realbackslash entry {\temp1}{\folio}{#2}}}% \temp }% \penalty\count10}} \def\dosubind #1#2#3{% {\indexdummies % Must do this here, since \bf, etc expand at this stage \count10=\lastpenalty % \escapechar=`\\% {\let\folio=0% \def\rawbackslashxx{\indexbackslash}% % % Now process the index-string once, with all font commands turned off, % to get the string to sort the index by. {\indexnofonts \xdef\temp1{#2 #3}% }% % Now produce the complete index entry. We process the index-string again, % this time with font commands expanded, to get what to print in the index. \edef\temp{% \write \csname#1indfile\endcsname{% \realbackslash entry {\temp1}{\folio}{#2}{#3}}}% \temp }% \penalty\count10}} % The index entry written in the file actually looks like % \entry {sortstring}{page}{topic} % or % \entry {sortstring}{page}{topic}{subtopic} % The texindex program reads in these files and writes files % containing these kinds of lines: % \initial {c} % before the first topic whose initial is c % \entry {topic}{pagelist} % for a topic that is used without subtopics % \primary {topic} % for the beginning of a topic that is used with subtopics % \secondary {subtopic}{pagelist} % for each subtopic. % Define the user-accessible indexing commands % @findex, @vindex, @kindex, @cindex. \def\findex {\fnindex} \def\kindex {\kyindex} \def\cindex {\cpindex} \def\vindex {\vrindex} \def\tindex {\tpindex} \def\pindex {\pgindex} \def\cindexsub {\begingroup\obeylines\cindexsub} {\obeylines % \gdef\cindexsub "#1" #2^^M{\endgroup % \dosubind{cp}{#2}{#1}}} % Define the macros used in formatting output of the sorted index material. % This is what you call to cause a particular index to get printed. % Write % @unnumbered Function Index % @printindex fn \def\printindex{\parsearg\doprintindex} \def\doprintindex#1{\tex % \catcode`\%=\other\catcode`\&=\other\catcode`\#=\other \catcode`\$=\other\catcode`\_=\other \catcode`\~=\other % The following don't help, since the chars were translated % when the raw index was written, and their fonts were discarded % due to \indexnofonts. %\catcode`\"=\active %\catcode`\^=\active %\catcode`\_=\active %\catcode`\|=\active %\catcode`\<=\active %\catcode`\>=\active \def\indexbackslash{\rawbackslashxx} \indexfonts\rm \tolerance=9500 \advance\baselineskip -1pt \begindoublecolumns \openin 1 \jobname.#1s \ifeof 1 \else \closein 1 \input \jobname.#1s \fi \enddoublecolumns \Etex} % These macros are used by the sorted index file itself. % Change them to control the appearance of the index. % Same as \bigskipamount except no shrink. % \balancecolumns gets confused if there is any shrink. \newskip\initialskipamount \initialskipamount 12pt plus4pt \outer\def\initial #1{% {\let\tentt=\sectt \let\sf=\sectt \ifdim\lastskip<\initialskipamount \removelastskip \penalty-200 \vskip \initialskipamount\fi \line{\secbf#1\hfill}\kern 2pt\penalty10000}} \outer\def\entry #1#2{ {\parfillskip=0in \parskip=0in \parindent=0in \hangindent=1in \hangafter=1% \noindent\hbox{#1}\dotfill #2\par }} \def\primary #1{\line{#1\hfil}} \newskip\secondaryindent \secondaryindent=0.5cm \def\secondary #1#2{ {\parfillskip=0in \parskip=0in \hangindent =1in \hangafter=1 \noindent\hskip\secondaryindent\hbox{#1}\dotfill #2\par }} %% Define two-column mode, which is used in indexes. %% Adapted from the TeXBook, page 416 \catcode `\@=11 \newbox\partialpage \newdimen\doublecolumnhsize \doublecolumnhsize = 3.11in \newdimen\doublecolumnvsize \doublecolumnvsize = 19.1in \newdimen\availdimen@ \def\begindoublecolumns{\begingroup \output={\global\setbox\partialpage=\vbox{\unvbox255\kern -\topskip \kern \baselineskip}}\eject \output={\doublecolumnout} \hsize=\doublecolumnhsize \vsize=\doublecolumnvsize} \def\enddoublecolumns{\output={\balancecolumns}\eject \endgroup \pagegoal=\vsize} \def\doublecolumnout{\splittopskip=\topskip \splitmaxdepth=\maxdepth \dimen@=\pageheight \advance\dimen@ by-\ht\partialpage \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@ \onepageout\pagesofar \unvbox255 \penalty\outputpenalty} \def\pagesofar{\unvbox\partialpage % \hsize=\doublecolumnhsize % have to restore this since output routine % changes it to set cropmarks (P. A. MacKay, 12 Nov. 1986) \wd0=\hsize \wd2=\hsize \hbox to\pagewidth{\box0\hfil\box2}} \def\balancecolumns{% % Unset the glue. \setbox255=\vbox{\unvbox255} \dimen@=\ht255 \advance\dimen@ by\topskip \advance\dimen@ by-\baselineskip \divide\dimen@ by2 \availdimen@=\pageheight \advance\availdimen@ by-\ht\partialpage % If the remaining data is too big for one page, % output one page normally, then work with what remains. \ifdim \dimen@>\availdimen@ { \splittopskip=\topskip \splitmaxdepth=\maxdepth \dimen@=\pageheight \advance\dimen@ by-\ht\partialpage \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@ \onepageout\pagesofar } % Recompute size of what remains, in case we just output some of it. \dimen@=\ht255 \advance\dimen@ by\topskip \advance\dimen@ by-\baselineskip \divide\dimen@ by2 \fi \setbox0=\vbox{\unvbox255} \splittopskip=\topskip {\vbadness=10000 \loop \global\setbox3=\copy0 \global\setbox1=\vsplit3 to\dimen@ \ifdim\ht3>\dimen@ \global\advance\dimen@ by1pt \repeat} \setbox0=\vbox to\dimen@{\unvbox1} \setbox2=\vbox to\dimen@{\unvbox3} \pagesofar} \catcode `\@=\other \message{sectioning,} % Define chapters, sections, etc. \newcount \chapno \newcount \secno \newcount \subsecno \newcount \subsubsecno % This counter is funny since it counts through charcodes of letters A, B, ... \newcount \appendixno \appendixno = `\@ \def\appendixletter{\char\the\appendixno} \newwrite \contentsfile % This is called from \setfilename. \def\opencontents{\openout \contentsfile = \jobname.toc} % Each @chapter defines this as the name of the chapter. % page headings and footings can use it. @section does likewise \def\thischapter{} \def\thissection{} \def\seccheck#1{\if \pageno<0 % \errmessage{@#1 not allowed after generating table of contents}\fi % } \def\chapternofonts{% \let\rawbackslash=\relax% \let\frenchspacing=\relax% \def\char{\realbackslash char} \def\tclose##1{\realbackslash tclose {##1}} \def\code##1{\realbackslash code {##1}} \def\samp##1{\realbackslash samp {##1}} \def\r##1{\realbackslash r {##1}} \def\i##1{\realbackslash i {##1}} \def\b##1{\realbackslash b {##1}} \def\cite##1{\realbackslash cite {##1}} \def\key##1{\realbackslash key {##1}} \def\file##1{\realbackslash file {##1}} \def\var##1{\realbackslash var {##1}} \def\kbd##1{\realbackslash kbd {##1}} } \outer\def\chapter{\parsearg\chapterzzz} \def\chapterzzz #1{\seccheck{chapter}% \secno=0 \subsecno=0 \subsubsecno=0 \global\advance \chapno by 1 \message{Chapter \the\chapno}% \chapmacro {#1}{\the\chapno}% \gdef\thissection{#1}\gdef\thischapter{#1}% {\chapternofonts% \edef\temp{{\realbackslash chapentry {#1}{\the\chapno}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \donoderef % }} \outer\def\appendix{\parsearg\appendixzzz} \def\appendixzzz #1{\seccheck{appendix}% \secno=0 \subsecno=0 \subsubsecno=0 \global\advance \appendixno by 1 \message{Appendix \appendixletter}% \chapmacro {#1}{Appendix \appendixletter}% \gdef\thischapter{#1}\gdef\thissection{#1}% {\chapternofonts% \edef\temp{{\realbackslash chapentry {#1}{Appendix \appendixletter}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \appendixnoderef % }} \outer\def\unnumbered{\parsearg\unnumberedzzz} \def\unnumberedzzz #1{\seccheck{unnumbered}% \secno=0 \subsecno=0 \subsubsecno=0 \message{(#1)} \unnumbchapmacro {#1}% \gdef\thischapter{#1}\gdef\thissection{#1}% {\chapternofonts% \edef\temp{{\realbackslash unnumbchapentry {#1}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \unnumbnoderef % }} \outer\def\section{\parsearg\sectionzzz} \def\sectionzzz #1{\seccheck{section}% \subsecno=0 \subsubsecno=0 \global\advance \secno by 1 % \gdef\thissection{#1}\secheading {#1}{\the\chapno}{\the\secno}% {\chapternofonts% \edef\temp{{\realbackslash secentry % {#1}{\the\chapno}{\the\secno}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \donoderef % \penalty 10000 % }} \outer\def\appendixsection{\parsearg\appendixsectionzzz} \outer\def\appendixsec{\parsearg\appendixsectionzzz} \def\appendixsectionzzz #1{\seccheck{appendixsection}% \subsecno=0 \subsubsecno=0 \global\advance \secno by 1 % \gdef\thissection{#1}\secheading {#1}{\appendixletter}{\the\secno}% {\chapternofonts% \edef\temp{{\realbackslash secentry % {#1}{\appendixletter}{\the\secno}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \appendixnoderef % \penalty 10000 % }} \outer\def\unnumberedsec{\parsearg\unnumberedseczzz} \def\unnumberedseczzz #1{\seccheck{unnumberedsec}% \plainsecheading {#1}\gdef\thissection{#1}% {\chapternofonts% \edef\temp{{\realbackslash unnumbsecentry{#1}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \unnumbnoderef % \penalty 10000 % }} \outer\def\subsection{\parsearg\subsectionzzz} \def\subsectionzzz #1{\seccheck{subsection}% \gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 % \subsecheading {#1}{\the\chapno}{\the\secno}{\the\subsecno}% {\chapternofonts% \edef\temp{{\realbackslash subsecentry % {#1}{\the\chapno}{\the\secno}{\the\subsecno}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \donoderef % \penalty 10000 % }} \outer\def\appendixsubsec{\parsearg\appendixsubseczzz} \def\appendixsubseczzz #1{\seccheck{appendixsubsec}% \gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 % \subsecheading {#1}{\appendixletter}{\the\secno}{\the\subsecno}% {\chapternofonts% \edef\temp{{\realbackslash subsecentry % {#1}{\appendixletter}{\the\secno}{\the\subsecno}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \appendixnoderef % \penalty 10000 % }} \outer\def\unnumberedsubsec{\parsearg\unnumberedsubseczzz} \def\unnumberedsubseczzz #1{\seccheck{unnumberedsubsec}% \plainsecheading {#1}\gdef\thissection{#1}% {\chapternofonts% \edef\temp{{\realbackslash unnumbsubsecentry{#1}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \unnumbnoderef % \penalty 10000 % }} \outer\def\subsubsection{\parsearg\subsubsectionzzz} \def\subsubsectionzzz #1{\seccheck{subsubsection}% \gdef\thissection{#1}\global\advance \subsubsecno by 1 % \subsubsecheading {#1}{\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}% {\chapternofonts% \edef\temp{{\realbackslash subsubsecentry % {#1}{\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}{\noexpand\folio}}}%\ \escapechar=`\\% \write \contentsfile \temp % \donoderef % \penalty 10000 % }} \outer\def\appendixsubsubsec{\parsearg\appendixsubsubseczzz} \def\appendixsubsubseczzz #1{\seccheck{appendixsubsubsec}% \gdef\thissection{#1}\global\advance \subsubsecno by 1 % \subsubsecheading {#1}{\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}% {\chapternofonts% \edef\temp{{\realbackslash subsubsecentry{#1}% {\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}{\noexpand\folio}}}%\ \escapechar=`\\% \write \contentsfile \temp % \appendixnoderef % \penalty 10000 % }} \outer\def\unnumberedsubsubsec{\parsearg\unnumberedsubsubseczzz} \def\unnumberedsubsubseczzz #1{\seccheck{unnumberedsubsubsec}% \plainsecheading {#1}\gdef\thissection{#1}% {\chapternofonts% \edef\temp{{\realbackslash unnumbsubsubsecentry{#1}{\noexpand\folio}}}% \escapechar=`\\% \write \contentsfile \temp % \unnumbnoderef % \penalty 10000 % }} % These are variants which are not "outer", so they can appear in @ifinfo. \def\infounnumbered{\parsearg\unnumberedzzz} \def\infounnumberedsec{\parsearg\unnumberedseczzz} \def\infounnumberedsubsec{\parsearg\unnumberedsubseczzz} \def\infounnumberedsubsubsec{\parsearg\unnumberedsubsubseczzz} \def\infoappendix{\parsearg\appendixzzz} \def\infoappendixsec{\parsearg\appendixseczzz} \def\infoappendixsubsec{\parsearg\appendixsubseczzz} \def\infoappendixsubsubsec{\parsearg\appendixsubsubseczzz} \def\infochapter{\parsearg\chapterzzz} \def\infosection{\parsearg\sectionzzz} \def\infosubsection{\parsearg\subsectionzzz} \def\infosubsubsection{\parsearg\subsubsectionzzz} % Define @majorheading, @heading and @subheading \def\majorheading #1{% {\advance\chapheadingskip by 10pt \chapbreak }% {\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 200} \def\chapheading #1{\chapbreak % {\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 200} \def\heading{\parsearg\secheadingi} % These macros generate a chapter, section, etc. heading only % (including whitespace, linebreaking, etc. around it), % given all the information in convenient, parsed form. %%% Args are the skip and penalty (usually negative) \def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi} \def\setchapterstyle #1 {\csname CHAPF#1\endcsname} %%% Define plain chapter starts, and page on/off switching for it % Parameter controlling skip before chapter headings (if needed) \newskip \chapheadingskip \chapheadingskip = 30pt plus 8pt minus 4pt \def\chapbreak{\dobreak \chapheadingskip {-4000}} \def\chappager{\par\vfill\supereject} \def\chapoddpage{\chappager \ifodd\pageno \else \hbox to 0pt{} \chappager\fi} \def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname} \def\CHAPPAGoff{ \global\let\pchapsepmacro=\chapbreak \global\let\pagealignmacro=\chappager} \def\CHAPPAGon{ \global\let\pchapsepmacro=\chappager \global\let\pagealignmacro=\chappager \global\def\HEADINGSon{\HEADINGSsingle}} \def\CHAPPAGodd{ \global\let\pchapsepmacro=\chapoddpage \global\let\pagealignmacro=\chapoddpage \global\def\HEADINGSon{\HEADINGSdouble}} \CHAPPAGon \def\CHAPFplain{ \global\let\chapmacro=\chfplain \global\let\unnumbchapmacro=\unnchfplain} \def\chfplain #1#2{% \pchapsepmacro % {\chapfonts \line{\rm #2.\enspace #1\hfill}}\bigskip \par\penalty 5000 % } \def\unnchfplain #1{% \pchapsepmacro % {\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 10000 % } \CHAPFplain % The default \def\unnchfopen #1{% \chapoddpage {\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 10000 % } \def\chfopen #1#2{\chapoddpage {\chapfonts \vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}% \par\penalty 5000 % } \def\CHAPFopen{ \global\let\chapmacro=\chfopen \global\let\unnumbchapmacro=\unnchfopen} % Parameter controlling skip before section headings. \newskip \subsecheadingskip \subsecheadingskip = 17pt plus 8pt minus 4pt \def\subsecheadingbreak{\dobreak \subsecheadingskip {-500}} \newskip \secheadingskip \secheadingskip = 21pt plus 8pt minus 4pt \def\secheadingbreak{\dobreak \secheadingskip {-1000}} % Section fonts are the base font at magstep2, which produces % a size a bit more than 14 points in the default situation. \def\secheading #1#2#3{\secheadingi {#2.#3\enspace #1}} \def\plainsecheading #1{\secheadingi {#1}} \def\secheadingi #1{{\advance \secheadingskip by \parskip % \secheadingbreak}% {\secfonts \line{\rm #1\hfill}}% \ifdim \parskip<10pt \kern 10pt\kern -\parskip\fi \penalty 10000 } % Subsection fonts are the base font at magstep1, % which produces a size of 12 points. \def\subsecheading #1#2#3#4{{\advance \subsecheadingskip by \parskip % \subsecheadingbreak}% {\subsecfonts \line{\rm#2.#3.#4\enspace #1\hfill}}% \ifdim \parskip<10pt \kern 10pt\kern -\parskip\fi \penalty 10000 } \def\subsubsecfonts{\subsecfonts} % Maybe this should change: % Perhaps make sssec fonts scaled % magstep half \def\subsubsecheading #1#2#3#4#5{{\advance \subsecheadingskip by \parskip % \subsecheadingbreak}% {\subsubsecfonts \line{\rm#2.#3.#4.#5\enspace #1\hfill}}% \ifdim \parskip<10pt \kern 10pt\kern -\parskip\fi \penalty 10000} \message{toc printing,} % Finish up the main text and prepare to read what we've written % to \contentsfile. \def\startcontents#1{% \ifnum \pageno>0 \pagealignmacro \immediate\closeout \contentsfile \pageno = -1 % Request roman numbered pages. \fi \unnumbchapmacro{#1}\def\thischapter{#1}% \begingroup % Set up to handle contents files properly. \catcode`\\=0 \catcode`\{=1 \catcode`\}=2 \catcode`\@=11 \raggedbottom % Worry more about breakpoints than the bottom. \advance\hsize by -1in % Don't use the full line length. } % Normal (long) toc. \outer\def\contents{% \startcontents{Table of Contents}% \input \jobname.toc \endgroup \vfill \eject } % And just the chapters. \outer\def\summarycontents{% \startcontents{Short Contents}% % \let\chapentry = \shortchapentry \let\unnumbchapentry = \shortunnumberedentry % We want a true roman here for the page numbers. \secfonts \let\rm = \truesecrm \rm \advance\baselineskip by 1pt % Open it up a little. \def\secentry ##1##2##3##4{} \def\unnumbsecentry ##1##2{} \def\subsecentry ##1##2##3##4##5{} \def\unnumbsubsecentry ##1##2{} \def\subsubsecentry ##1##2##3##4##5##6{} \def\unnumbsubsubsecentry ##1##2{} \input \jobname.toc \endgroup \vfill \eject } \let\shortcontents = \summarycontents % These macros generate individual entries in the table of contents. % The first argument is the chapter or section name. % The last argument is the page number. % The arguments in between are the chapter number, section number, ... % Chapter-level things, for both the long and short contents. \def\chapentry#1#2#3{\dochapentry{#2\labelspace#1}{#3}} \def\shortchapentry#1#2#3{% \line{{#2\labelspace #1}\dotfill\doshortpageno{#3}}% } \def\unnumbchapentry#1#2{\dochapentry{#1}{#2}} \def\shortunnumberedentry#1#2{% \line{#1\dotfill\doshortpageno{#2}}% } % Sections. \def\secentry#1#2#3#4{\dosecentry{#2.#3\labelspace#1}{#4}} \def\unnumbsecentry#1#2{\dosecentry{#1}{#2}} % Subsections. \def\subsecentry#1#2#3#4#5{\dosubsecentry{#2.#3.#4\labelspace#1}{#5}} \def\unnumbsubsecentry#1#2{\dosubsecentry{#1}{#2}} % And subsubsections. \def\subsubsecentry#1#2#3#4#5#6{\dosubsubsecentry{#2.#3.#4.#5\labelspace#1}{#6}} \def\unnumbsubsecentry#1#2{\dosubsubsecentry{#1}{#2}} % This parameter controls the indentation of the various levels. \newdimen\tocindent \tocindent = 3pc % Now for the actual typesetting. In all these, #1 is the text and #2 is the % page number. % % If the toc has to be broken over pages, we would want to be at chapters % if at all possible; hence the \penalty. \def\dochapentry#1#2{% \penalty-300 \vskip\baselineskip \line{\chapentryfonts #1\dotfill \dopageno{#2}}% \nobreak\vskip .25\baselineskip } \def\dosecentry#1#2{% \line{\secentryfonts \hskip\tocindent #1\dotfill \dopageno{#2}}% } \def\dosubsecentry#1#2{% \line{\subsecentryfonts \hskip2\tocindent #1\dotfill \dopageno{#2}}% } \def\dosubsubsecentry#1#2{% \line{\subsubsecentryfonts \hskip3\tocindent #1\dotfill \dopageno{#2}}% } % Space between chapter (or whatever) number and the title. \def\labelspace{\hskip1em \relax} \def\dopageno#1{{\rm #1}} \def\doshortpageno#1{{\rm #1}} \def\chapentryfonts{\secfonts \rm} \def\secentryfonts{\textfonts} \let\subsecentryfonts = \textfonts \let\subsubsecentryfonts = \textfonts \message{environments,} % Since these characters are used in examples, it should be an even number of % \tt widths. Each \tt character is 1en, so two makes it 1em. % Furthermore, these definitions must come after we define our fonts. \newbox\dblarrowbox \newbox\longdblarrowbox \newbox\pushcharbox \newbox\bullbox \newbox\equivbox \newbox\errorbox \let\ptexequiv = \equiv {\tentt \global\setbox\dblarrowbox = \hbox to 1em{\hfil$\Rightarrow$\hfil} \global\setbox\longdblarrowbox = \hbox to 1em{\hfil$\mapsto$\hfil} \global\setbox\pushcharbox = \hbox to 1em{\hfil$\dashv$\hfil} \global\setbox\equivbox = \hbox to 1em{\hfil$\ptexequiv$\hfil} % Adapted from the manmac format (p.420 of TeXbook) \global\setbox\bullbox = \hbox to 1em{\kern.15em\vrule height .75ex width .85ex depth .1ex\hfil} } \def\point{$\star$} \def\result{\leavevmode\raise.15ex\copy\dblarrowbox} \def\expansion{\leavevmode\raise.1ex\copy\longdblarrowbox} \def\print{\leavevmode\lower.1ex\copy\pushcharbox} \def\equiv{\leavevmode\lower.1ex\copy\equivbox} % Does anyone really want this? % \def\bull{\leavevmode\copy\bullbox} % Adapted from the TeXbook's \boxit. \dimen0 = 3em % Width of the box. \dimen2 = .55pt % Thickness of rules % The text. (`r' is open on the right, `e' somewhat less so on the left.) \setbox0 = \hbox{\kern-.75pt \tensf error\kern-1.5pt} \global\setbox\errorbox=\hbox to \dimen0{\hfil \vbox{\hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right. \advance\hsize by -2\dimen2 % Rules. \hrule height\dimen2 \hbox{\vrule width\dimen2 \kern3pt % Space to left of text. \vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below. \kern3pt\vrule width\dimen2}% Space to right. \hrule height\dimen2} \hfil} % The @error{} command. \def\error{\leavevmode\lower.7ex\copy\errorbox} % @tex ... @end tex escapes into raw Tex temporarily. % One exception: @ is still an escape character, so that @end tex works. % But \@ or @@ will get a plain tex @ character. \def\tex{\begingroup \catcode `\\=0 \catcode `\{=1 \catcode `\}=2 \catcode `\$=3 \catcode `\&=4 \catcode `\#=6 \catcode `\^=7 \catcode `\_=8 \catcode `\~=13 \let~=\tie \catcode `\%=14 \catcode`\"=12 \catcode`\==12 \catcode`\|=12 \catcode`\<=12 \catcode`\>=12 \escapechar=`\\ % \let\{=\ptexlbrace \let\}=\ptexrbrace \let\.=\ptexdot \let\*=\ptexstar \def\@={@}% \let\bullet=\ptexbullet \let\b=\ptexb \let\c=\ptexc \let\i=\ptexi \let\t=\ptext \let\l=\ptexl \let\L=\ptexL % \let\Etex=\endgroup} % Define @lisp ... @endlisp. % @lisp does a \begingroup so it can rebind things, % including the definition of @endlisp (which normally is erroneous). % Amount to narrow the margins by for @lisp. \newskip\lispnarrowing \lispnarrowing=0.4in % This is the definition that ^M gets inside @lisp % phr: changed space to \null, to avoid overfull hbox problems. {\obeyspaces% \gdef\lisppar{\null\endgraf}} % Cause \obeyspaces to make each Space cause a word-separation % rather than the default which is that it acts punctuation. % This is because space in tt font looks funny. {\obeyspaces % \gdef\sepspaces{\def {\ }}} \newskip\aboveenvskipamount \aboveenvskipamount= 0pt \def\aboveenvbreak{{\advance\aboveenvskipamount by \parskip \endgraf \ifdim\lastskip<\aboveenvskipamount \removelastskip \penalty-50 \vskip\aboveenvskipamount \fi}} \def\afterenvbreak{\endgraf \ifdim\lastskip<\aboveenvskipamount \removelastskip \penalty-50 \vskip\aboveenvskipamount \fi} \def\lisp{\aboveenvbreak\begingroup\inENV %This group ends at the end of the @lisp body \hfuzz=12truept % Don't be fussy % Make spaces be word-separators rather than space tokens. \sepspaces % % Single space lines \singlespace % % The following causes blank lines not to be ignored % by adding a space to the end of each line. \let\par=\lisppar \def\Elisp{\endgroup\afterenvbreak}% \parskip=0pt \advance \leftskip by \lispnarrowing \parindent=0pt \let\exdent=\internalexdent \obeyspaces \obeylines \tt \rawbackslash \def\next##1{}\next} \let\example=\lisp \def\Eexample{\Elisp} \let\smallexample=\lisp \def\Esmallexample{\Elisp} % Macro for 9 pt. examples, necessary to print with 5" lines. % From Pavel@xerox. This is not really used unless the % @smallbook command is given. \def\smalllispx{\aboveenvbreak\begingroup\inENV % This group ends at the end of the @lisp body \hfuzz=12truept % Don't be fussy % Make spaces be word-separators rather than space tokens. \sepspaces % % Single space lines \singlespace % % The following causes blank lines not to be ignored % by adding a space to the end of each line. \let\par=\lisppar \def\Esmalllisp{\endgroup\afterenvbreak}% \parskip=0pt \advance \leftskip by \lispnarrowing \parindent=0pt \let\exdent=\internalexdent \obeyspaces \obeylines \ninett \rawbackslash \def\next##1{}\next} % This is @display; same as @lisp except use roman font. \def\display{\begingroup\inENV %This group ends at the end of the @display body \aboveenvbreak % Make spaces be word-separators rather than space tokens. \sepspaces % % Single space lines \singlespace % % The following causes blank lines not to be ignored % by adding a space to the end of each line. \let\par=\lisppar \def\Edisplay{\endgroup\afterenvbreak}% \parskip=0pt \advance \leftskip by \lispnarrowing \parindent=0pt \let\exdent=\internalexdent \obeyspaces \obeylines \def\next##1{}\next} % This is @format; same as @lisp except use roman font and don't narrow margins \def\format{\begingroup\inENV %This group ends at the end of the @format body \aboveenvbreak % Make spaces be word-separators rather than space tokens. \sepspaces % \singlespace % % The following causes blank lines not to be ignored % by adding a space to the end of each line. \let\par=\lisppar \def\Eformat{\endgroup\afterenvbreak} \parskip=0pt \parindent=0pt \obeyspaces \obeylines \def\next##1{}\next} % @flushleft and @flushright \def\flushleft{\begingroup\inENV %This group ends at the end of the @format body \aboveenvbreak % Make spaces be word-separators rather than space tokens. \sepspaces % % The following causes blank lines not to be ignored % by adding a space to the end of each line. % This also causes @ to work when the directive name % is terminated by end of line. \let\par=\lisppar \def\Eflushleft{\endgroup\afterenvbreak}% \parskip=0pt \parindent=0pt \obeyspaces \obeylines \def\next##1{}\next} \def\flushright{\begingroup\inENV %This group ends at the end of the @format body \aboveenvbreak % Make spaces be word-separators rather than space tokens. \sepspaces % % The following causes blank lines not to be ignored % by adding a space to the end of each line. % This also causes @ to work when the directive name % is terminated by end of line. \let\par=\lisppar \def\Eflushright{\endgroup\afterenvbreak}% \parskip=0pt \parindent=0pt \advance \leftskip by 0pt plus 1fill \obeyspaces \obeylines \def\next##1{}\next} % @quotation - narrow the margins. \def\quotation{\begingroup\inENV %This group ends at the end of the @quotation body {\parskip=0pt % because we will skip by \parskip too, later \aboveenvbreak}% \singlespace \parindent=0pt \def\Equotation{\par\endgroup\afterenvbreak}% \advance \rightskip by \lispnarrowing \advance \leftskip by \lispnarrowing} \message{defuns,} % Define formatter for defuns % First, allow user to change definition object font (\df) internally \def\setdeffont #1 {\csname DEF#1\endcsname} \newskip\defbodyindent \defbodyindent=.4in \newskip\defargsindent \defargsindent=50pt \newskip\deftypemargin \deftypemargin=12pt \newskip\deflastargmargin \deflastargmargin=18pt \newcount\parencount % define \functionparens, which makes ( and ) and & do special things. % \functionparens affects the group it is contained in. \def\activeparens{% \catcode`\(=\active \catcode`\)=\active \catcode`\&=\active \catcode`\[=\active \catcode`\]=\active} {\activeparens % Now, smart parens don't turn on until &foo (see \amprm) \gdef\functionparens{\boldbrax\let&=\amprm\parencount=0 } \gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb} % Definitions of (, ) and & used in args for functions. % This is the definition of ( outside of all parentheses. \gdef\oprm#1 {{\rm\char`\(}#1 \bf \let(=\opnested % \global\advance\parencount by 1 } % % This is the definition of ( when already inside a level of parens. \gdef\opnested{\char`\(\global\advance\parencount by 1 } % \gdef\clrm{% Print a paren in roman if it is taking us back to depth of 0. % also in that case restore the outer-level definition of (. \ifnum \parencount=1 {\rm \char `\)}\sl \let(=\oprm \else \char `\) \fi \global\advance \parencount by -1 } % If we encounter &foo, then turn on ()-hacking afterwards \gdef\amprm#1 {{\rm\}\let(=\oprm \let)=\clrm\ } % \gdef\normalparens{\boldbrax\let&=\ampnr} } % End of definition inside \activeparens %% These parens (in \boldbrax) actually are a little bolder than the %% contained text. This is especially needed for [ and ] \def\opnr{{\sf\char`\(}} \def\clnr{{\sf\char`\)}} \def\ampnr{\&} \def\lbrb{{\tt\char`\[}} \def\rbrb{{\tt\char`\]}} % First, defname, which formats the header line itself. % #1 should be the function name. % #2 should be the type of definition, such as "Function". \def\defname #1#2{% \leftskip = 0in % \noindent % \setbox0=\hbox{\hskip \deflastargmargin{\rm #2}\hskip \deftypemargin}% \dimen0=\hsize \advance \dimen0 by -\wd0 % compute size for first line \dimen1=\hsize \advance \dimen1 by -\defargsindent %size for continuations \parshape 2 0in \dimen0 \defargsindent \dimen1 % % Now output arg 2 ("Function" or some such) % ending at \deftypemargin from the right margin, % but stuck inside a box of width 0 so it does not interfere with linebreaking \rlap{\rightline{{\rm #2}\hskip \deftypemargin}}% \tolerance=10000 \hbadness=10000 % Make all lines underfull and no complaints {\df #1}\enskip % Generate function name } % Actually process the body of a definition % #1 should be the terminating control sequence, such as \Edefun. % #2 should be the "another name" control sequence, such as \defunx. % #3 should be the control sequence that actually processes the header, % such as \defunheader. \def\defparsebody #1#2#3{\begingroup\inENV% Environment for definitionbody \medbreak % % Define the end token that this defining construct specifies % so that it will exit this group. \def#1{\endgraf\endgroup\medbreak}% \def#2{\begingroup\obeylines\activeparens\spacesplit#3}% \parindent=0in \leftskip=\defbodyindent \rightskip=\defbodyindent % \begingroup\obeylines\activeparens\spacesplit#3} \def\defmethparsebody #1#2#3#4 {\begingroup\inENV % \medbreak % % Define the end token that this defining construct specifies % so that it will exit this group. \def#1{\endgraf\endgroup\medbreak}% \def#2##1 {\begingroup\obeylines\activeparens\spacesplit{#3{##1}}}% \parindent=0in \leftskip=\defbodyindent \rightskip=\defbodyindent % \begingroup\obeylines\activeparens\spacesplit{#3{#4}}} \def\defopparsebody #1#2#3#4#5 {\begingroup\inENV % \medbreak % % Define the end token that this defining construct specifies % so that it will exit this group. \def#1{\endgraf\endgroup\medbreak}% \def#2##1 ##2 {\def#4{##1}% \begingroup\obeylines\activeparens\spacesplit{#3{##2}}}% \parindent=0in \leftskip=\defbodyindent % \begingroup\obeylines\activeparens\spacesplit{#3{#5}}} % Split up #2 at the first space token. % call #1 with two arguments: % the first is all of #2 before the space token, % the second is all of #2 after that space token. % If #2 contains no space token, all of it is passed as the first arg % and the second is passed as empty. {\obeylines \gdef\spacesplit#1#2^^M{\endgroup\spacesplitfoo{#1}#2 \relax\spacesplitfoo}% \long\gdef\spacesplitfoo#1#2 #3#4\spacesplitfoo{% \ifx\relax #3% #1{#2}{}\else #1{#2}{#3#4}\fi}} % So much for the things common to all kinds of definitions. % Define @defun. % First, define the processing that is wanted for arguments of \defun % Use this to expand the args and terminate the paragraph they make up \def\defunargs #1{\functionparens \sl % Expand, preventing hyphenation at `-' chars. % Note that groups don't affect changes in \hyphenchar. \hyphenchar\sl=0 #1% \hyphenchar\sl=45 \ifnum\parencount=0 \else \errmessage{unbalanced parens in @def arguments}\fi% \interlinepenalty=10000 \endgraf\penalty10000\vskip -\parskip } % Do complete processing of one @defun or @defunx line already parsed. % @deffn Command forward-char nchars \def\deffn{\defmethparsebody\Edeffn\deffnx\deffnheader} \def\deffnheader #1#2#3{\doind {fn}{\code{#2}}% \begingroup\defname {#2}{#1}\defunargs{#3}\endgroup} % @defun == @deffn Function \def\defun{\defparsebody\Edefun\defunx\defunheader} \def\defunheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index \begingroup\defname {#1}{Function}% \defunargs {#2}\endgroup % } % @defmac == @deffn Macro \def\defmac{\defparsebody\Edefmac\defmacx\defmacheader} \def\defmacheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index \begingroup\defname {#1}{Macro}% \defunargs {#2}\endgroup % } % @defspec == @deffn Special Form \def\defspec{\defparsebody\Edefspec\defspecx\defspecheader} \def\defspecheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index \begingroup\defname {#1}{Special form}% \defunargs {#2}\endgroup % } % This definition is run if you use @defunx % anywhere other than immediately after a @defun or @defunx. \def\deffnx #1 {\errmessage{@deffnx in invalid context}} \def\defunx #1 {\errmessage{@defunx in invalid context}} \def\defmacx #1 {\errmessage{@defmacx in invalid context}} \def\defspecx #1 {\errmessage{@defspecx in invalid context}} % @defmethod, and so on % @defop {Funny Method} foo-class frobnicate argument \def\defop #1 {\def\defoptype{#1}% \defopparsebody\Edefop\defopx\defopheader\defoptype} \def\defopheader #1#2#3{\dosubind {fn}{\code{#2}}{on #1}% Make entry in function index \begingroup\defname {#2}{\defoptype{} on #1}% \defunargs {#3}\endgroup % } % @defmethod == @defop Method \def\defmethod{\defmethparsebody\Edefmethod\defmethodx\defmethodheader} \def\defmethodheader #1#2#3{\dosubind {fn}{\code{#2}}{on #1}% entry in function index \begingroup\defname {#2}{Operation on #1}% \defunargs {#3}\endgroup % } % @defcv {Class Option} foo-class foo-flag \def\defcv #1 {\def\defcvtype{#1}% \defopparsebody\Edefcv\defcvx\defcvheader\defcvtype} \def\defcvarheader #1#2#3{% \dosubind {vr}{\code{#2}}{of #1}% Make entry in var index \begingroup\defname {#2}{\defcvtype of #1}% \defvarargs {#3}\endgroup % } % @defivar == @defcv {Instance Variable} \def\defivar{\defmethparsebody\Edefivar\defivarx\defivarheader} \def\defivarheader #1#2#3{% \dosubind {vr}{\code{#2}}{of #1}% Make entry in var index \begingroup\defname {#2}{Instance variable of #1}% \defvarargs {#3}\endgroup % } % These definitions are run if you use @defmethodx, etc., % anywhere other than immediately after a @defmethod, etc. \def\defopx #1 {\errmessage{@defopx in invalid context}} \def\defmethodx #1 {\errmessage{@defmethodx in invalid context}} \def\defcvx #1 {\errmessage{@defcvx in invalid context}} \def\defivarx #1 {\errmessage{@defivarx in invalid context}} % Now @defvar % First, define the processing that is wanted for arguments of @defvar. % This is actually simple: just print them in roman. % This must expand the args and terminate the paragraph they make up \def\defvarargs #1{\normalparens #1% \interlinepenalty=10000 \endgraf\penalty 10000\vskip -\parskip} % @defvr Counter foo-count \def\defvr{\defmethparsebody\Edefvr\defvrx\defvrheader} \def\defvrheader #1#2#3{\doind {vr}{\code{#2}}% \begingroup\defname {#2}{#1}\defvarargs{#3}\endgroup} % @defvar == @defvr Variable \def\defvar{\defparsebody\Edefvar\defvarx\defvarheader} \def\defvarheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index \begingroup\defname {#1}{Variable}% \defvarargs {#2}\endgroup % } % @defopt == @defvr {User Option} \def\defopt{\defparsebody\Edefopt\defoptx\defoptheader} \def\defoptheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index \begingroup\defname {#1}{User Option}% \defvarargs {#2}\endgroup % } % This definition is run if you use @defvarx % anywhere other than immediately after a @defvar or @defvarx. \def\defvrx #1 {\errmessage{@defvrx in invalid context}} \def\defvarx #1 {\errmessage{@defvarx in invalid context}} \def\defoptx #1 {\errmessage{@defoptx in invalid context}} % Now define @deftp % Args are printed in bold, a slight difference from @defvar. \def\deftpargs #1{\bf \defvarargs{#1}} % @deftp Class window height width ... \def\deftp{\defmethparsebody\Edeftp\deftpx\deftpheader} \def\deftpheader #1#2#3{\doind {tp}{\code{#2}}% \begingroup\defname {#2}{#1}\deftpargs{#3}\endgroup} % This definition is run if you use @deftpx, etc % anywhere other than immediately after a @deftp, etc. \def\deftpx #1 {\errmessage{@deftpx in invalid context}} \message{cross reference,} % Define cross-reference macros \newwrite \auxfile % \setref{foo} defines a cross-reference point named foo. \def\setref#1{% \dosetq{#1-pg}{Ypagenumber}% \dosetq{#1-snt}{Ysectionnumberandtype}} \def\unnumbsetref#1{% \dosetq{#1-pg}{Ypagenumber}% \dosetq{#1-snt}{Ynothing}} \def\appendixsetref#1{% \dosetq{#1-pg}{Ypagenumber}% \dosetq{#1-snt}{Yappendixletterandtype}} % \xref and \pxref generate cross references to specified points. \def\pxref #1{see \xrefX [#1,,,,,,,]} \def\xref #1{See \xrefX [#1,,,,,,,]} \def\ref #1{\xrefX [#1,,,,,,,]} \def\xrefX [#1,#2,#3,#4,#5,#6]{% \setbox1=\hbox{\i{\losespace#5{}}}% \setbox0=\hbox{\losespace#3{}}% \ifdim \wd0 =0pt \setbox0=\hbox{\losespace#1{}}\fi% \ifdim \wd1 >0pt% section `\unhbox0' in \unhbox1% \else% \refx{#1-snt}{} [\unhbox0], page\tie \refx{#1-pg}{}% \fi } % \dosetq is the interface for calls from other macros \def\dosetq #1#2{{\let\folio=0% \edef\next{\write\auxfile{\internalsetq {#1}{#2}}}% \next}} % \internalsetq {foo}{page} expands into CHARACTERS 'xrdef {foo}{...expansion of \Ypage...} % When the aux file is read, ' is the escape character \def\internalsetq #1#2{'xrdef {#1}{\csname #2\endcsname}} % Things to be expanded by \internalsetq \def\Ypagenumber{\folio} \def\Ynothing{} \def\Ysectionnumberandtype{% \ifnum\secno=0 chapter\xreftie\the\chapno % \else \ifnum \subsecno=0 section\xreftie\the\chapno.\the\secno % \else \ifnum \subsubsecno=0 % section\xreftie\the\chapno.\the\secno.\the\subsecno % \else % section\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno % \fi \fi \fi } \def\Yappendixletterandtype{% \ifnum\secno=0 appendix\xreftie'char\the\appendixno % \else \ifnum \subsecno=0 section\xreftie'char\the\appendixno.\the\secno % \else \ifnum \subsubsecno=0 % section\xreftie'char\the\appendixno.\the\secno.\the\subsecno % \else % section\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno % \fi \fi \fi } \gdef\xreftie{'tie} % Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME. % If its value is nonempty, SUFFIX is output afterward. \def\refx#1#2{% {% \expandafter\ifx\csname X#1\endcsname\relax % If not defined, say something at least. \expandafter\gdef\csname X#1\endcsname {$\langle$un\-def\-in\-ed$\rangle$}#2% \message {WARNING: Cross-reference "#1" used but not yet defined}% \message {}% \fi % \setbox0=\hbox{\csname X#1\endcsname}%It's defined, so just use it. \ifdim\wd0>0pt \unhbox0{}#2\fi }} % Read the last existing aux file, if any. No error if none exists. % This is the macro invoked by entries in the aux file. \def\xrdef #1#2{ {\catcode`\'=\other\expandafter \gdef \csname X#1\endcsname {#2}}} \def\readauxfile{% \begingroup \catcode `\^^@=\other \catcode `\=\other \catcode `\=\other \catcode `\^^C=\other \catcode `\^^D=\other \catcode `\^^E=\other \catcode `\^^F=\other \catcode `\^^G=\other \catcode `\^^H=\other \catcode `\ =\other \catcode `\^^L=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\=\other \catcode `\^^[=\other \catcode `\^^\=\other \catcode `\^^]=\other \catcode `\^^^=\other \catcode `\^^_=\other \catcode `\@=\other \catcode `\^=\other \catcode `\~=\other \catcode `\[=\other \catcode `\]=\other \catcode`\"=\other \catcode`\_=\other \catcode`\|=\other \catcode`\<=\other \catcode`\>=\other \catcode `\$=\other \catcode `\#=\other \catcode `\&=\other % the aux file uses ' as the escape. % Turn off \ as an escape so we do not lose on % entries which were dumped with control sequences in their names. % For example, 'xrdef {$\leq $-fun}{page ...} made by @defun ^^ % Reference to such entries still does not work the way one would wish, % but at least they do not bomb out when the aux file is read in. \catcode `\{=1 \catcode `\}=2 \catcode `\%=\other \catcode `\'=0 \catcode `\\=\other \openin 1 \jobname.aux \ifeof 1 \else \closein 1 \input \jobname.aux \fi % Open the new aux file. Tex will close it automatically at exit. \openout \auxfile=\jobname.aux \endgroup} % Footnotes. \newcount \footnoteno \def\supereject{\par\penalty -20000\footnoteno =0 } \let\ptexfootnote=\footnote {\catcode `\@=11 \gdef\footnote{\global\advance \footnoteno by \@ne \edef\thisfootno{$^{\the\footnoteno}$}% \let\@sf\empty \ifhmode\edef\@sf{\spacefactor\the\spacefactor}\/\fi \thisfootno\@sf\parsearg\footnotezzz} \gdef\footnotezzz #1{\insert\footins{ \interlinepenalty\interfootnotelinepenalty \splittopskip\ht\strutbox % top baseline for broken footnotes \splitmaxdepth\dp\strutbox \floatingpenalty\@MM \leftskip\z@skip \rightskip\z@skip \spaceskip\z@skip \xspaceskip\z@skip \footstrut\hang\textindent{\thisfootno}#1\strut}} }%end \catcode `\@=11 % End of control word definitions. \message{and turning on texinfo input format.} \def\openindices{% \newindex{cp}% \newcodeindex{fn}% \newcodeindex{vr}% \newcodeindex{tp}% \newcodeindex{ky}% \newcodeindex{pg}% } % Set some numeric style parameters, for 8.5 x 11 format. \hsize = 6.5in \parindent 15pt \parskip 18pt plus 1pt \baselineskip 15pt \advance\topskip by 1.2cm % Prevent underfull vbox error messages. \vbadness=10000 % Use @smallbook to reset parameters for 7x9.5 format \def\smallbook{ \global\lispnarrowing = 0.3in \global\baselineskip 12pt \global\parskip 3pt plus 1pt \global\hsize = 5in \global\doublecolumnhsize=2.4in \global\doublecolumnvsize=15.0in \global\vsize=7.5in \global\tolerance=700 \global\hfuzz=1pt \global\pagewidth=\hsize \global\pageheight=\vsize \global\font\ninett=cmtt9 \global\let\smalllisp=\smalllispx \global\let\smallexample=\smalllispx \global\def\Esmallexample{\Esmalllisp} } %% For a final copy, take out the rectangles %% that mark overfull boxes (in case you have decided %% that the text looks ok even though it passes the margin). \def\finalout{\overfullrule=0pt} % Turn off all special characters except @ % (and those which the user can use as if they were ordinary) % Define certain chars to be always in tt font. \catcode`\"=\active \def\activedoublequote{{\tt \char '042}} \let"=\activedoublequote \catcode`\~=\active \def~{{\tt \char '176}} \chardef\hat=`\^ \catcode`\^=\active \def^{{\tt \hat}} \catcode`\_=\active \def_{{\tt \char '137}} \catcode`\|=\active \def|{{\tt \char '174}} \chardef \less=`\< \catcode`\<=\active \def<{{\tt \less}} \chardef \gtr=`\> \catcode`\>=\active \def>{{\tt \gtr}} \catcode`\+=\active \def+{{\tt \char 43}} %\catcode 27=\active %\def^^[{$\diamondsuit$} \catcode`\@=0 % \rawbackslashxx output one backslash character in current font {\catcode`\\=\other @gdef@rawbackslashxx{\}} % \rawbackslash redefines \ as input to do \rawbackslashxx. {\catcode`\\=\active @gdef@rawbackslash{@let\=@rawbackslashxx }} % \normalbackslash outputs one backslash in fixed width font. \def\normalbackslash{{\tt\rawbackslashxx}} % Say @foo, not \foo, in error messages. \escapechar=`\@ @c \catcode 17=0 @c Define control-q \catcode`\\=\active % If a .fmt file is being used, we don't want the `\input texinfo' to show up. % That is what \eatinput is for; after that, the `\' should revert to printing % a backslash. % @gdef@eatinput input texinfo{@fixbackslash} @global@let\ = @eatinput % On the other hand, perhaps the file did not have a `\input texinfo'. Then % the first `\{ in the file would cause an error. This macro tries to fix % that, assuming it is called before the first `\' could plausibly occur. % @gdef@fixbackslash{@ifx\@eatinput @let\ = @normalbackslash @fi} %% These look ok in all fonts, so just make them not special. The @rm below %% makes sure that the current font starts out as the newly loaded cmr10 @catcode`@$=@other @catcode`@%=@other @catcode`@&=@other @catcode`@#=@other @textfonts @rm