diff --git a/src/build.c b/src/build.c index 9e510b8..b388a19 100644 --- a/src/build.c +++ b/src/build.c @@ -38,695 +38,623 @@ #include "build.h" -#include "global.h" /* FIXME: get rid of this! */ +#include "global.h" /* FIXME: get rid of this! */ #include "library.h" #include "scanner.h" -#include "version.h" /* for FILEVERSION */ +#include "version.h" /* for FILEVERSION */ #include "vp.h" #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) -#include +# include #else -#include +# include #endif /* Exported variables: */ -bool buildonly = false; /* only build the database */ -bool unconditional = false; /* unconditionally build database */ -bool fileschanged; /* assume some files changed */ +bool buildonly = false; /* only build the database */ +bool unconditional = false; /* unconditionally build database */ +bool fileschanged; /* assume some files changed */ /* variable copies of the master strings... */ -char invname_buf[] = INVNAME; -char invpost_buf[] = INVPOST; -char reffile_buf[] = REFFILE; -char *invname = invname_buf; /* inverted index to the database */ -char *invpost = invpost_buf; /* inverted index postings */ -char *reffile = reffile_buf; /* cross-reference file path name */ +char invname_buf[] = INVNAME; +char invpost_buf[] = INVPOST; +char reffile_buf[] = REFFILE; +char *invname = invname_buf; /* inverted index to the database */ +char *invpost = invpost_buf; /* inverted index postings */ +char *reffile = reffile_buf; /* cross-reference file path name */ -char *newreffile; /* new cross-reference file name */ -FILE *newrefs; /* new cross-reference */ -FILE *postings; /* new inverted index postings */ -int symrefs = -1; /* cross-reference file */ +char *newreffile; /* new cross-reference file name */ +FILE *newrefs; /* new cross-reference */ +FILE *postings; /* new inverted index postings */ +int symrefs = -1; /* cross-reference file */ -INVCONTROL invcontrol; /* inverted file control structure */ +INVCONTROL invcontrol; /* inverted file control structure */ /* Local variables: */ -static char *newinvname; /* new inverted index file name */ -static char *newinvpost; /* new inverted index postings file name */ -static long traileroffset; /* file trailer offset */ +static char *newinvname; /* new inverted index file name */ +static char *newinvpost; /* new inverted index postings file name */ +static long traileroffset; /* file trailer offset */ /* Internal prototypes: */ -static void cannotindex(void); -static int compare(const void *s1, const void *s2); -static void copydata(void); -static void copyinverted(void); -static char *getoldfile(void); -static void movefile(char *new, char *old); -static void putheader(char *dir); -static void fetch_include_from_dbase(char *, size_t); -static void putlist(char **names, int count); -static bool samelist(FILE *oldrefs, char **names, int count); - +static void cannotindex(void); +static int compare(const void *s1, const void *s2); +static void copydata(void); +static void copyinverted(void); +static char *getoldfile(void); +static void movefile(char *new, char *old); +static void putheader(char *dir); +static void fetch_include_from_dbase(char *, size_t); +static void putlist(char **names, int count); +static bool samelist(FILE *oldrefs, char **names, int count); /* Error handling routine if inverted index creation fails */ -static void -cannotindex(void) -{ - fprintf(stderr, PROGRAM_NAME ": cannot create inverted index; ignoring -q option\n"); - invertedindex = false; - errorsfound = true; - fprintf(stderr, PROGRAM_NAME ": removed files %s and %s\n", - newinvname, newinvpost); - unlink(newinvname); - unlink(newinvpost); +static void cannotindex(void) { + fprintf(stderr, PROGRAM_NAME ": cannot create inverted index; ignoring -q option\n"); + invertedindex = false; + errorsfound = true; + fprintf(stderr, PROGRAM_NAME ": removed files %s and %s\n", newinvname, newinvpost); + unlink(newinvname); + unlink(newinvpost); } - /* see if the name list is the same in the cross-reference file */ -static bool -samelist(FILE *oldrefs, char **names, int count) -{ - char oldname[PATHLEN + 1]; /* name in old cross-reference */ - int oldcount; - int i; - - /* see if the number of names is the same */ - if (fscanf(oldrefs, "%d", &oldcount) != 1 || - oldcount != count) { - return(false); - } - /* see if the name list is the same */ - for (i = 0; i < count; ++i) { - if ((1 != fscanf(oldrefs," %[^\n]",oldname)) || - strnotequal(oldname, names[i])) { - return(false); - } - } - return(true); +static bool samelist(FILE *oldrefs, char **names, int count) { + char oldname[PATHLEN + 1]; /* name in old cross-reference */ + int oldcount; + int i; + + /* see if the number of names is the same */ + if(fscanf(oldrefs, "%d", &oldcount) != 1 || oldcount != count) { return (false); } + /* see if the name list is the same */ + for(i = 0; i < count; ++i) { + if((1 != fscanf(oldrefs, " %[^\n]", oldname)) || strnotequal(oldname, names[i])) { + return (false); + } + } + return (true); } - /* create the file name(s) used for a new cross-referene */ -void setup_build_filenames(char *reffile) -{ - char *path; /* file pathname */ - char *s; /* pointer to basename in path */ - - path = malloc(strlen(reffile) + 10u); - strcpy(path, reffile); - s = basename(path); - *s = '\0'; - strcat(path, "n"); - ++s; - strcpy(s, basename(reffile)); - newreffile = strdup(path); - strcpy(s, basename(invname)); - newinvname = strdup(path); - strcpy(s, basename(invpost)); - newinvpost = strdup(path); - free(path); +void setup_build_filenames(char *reffile) { + char *path; /* file pathname */ + char *s; /* pointer to basename in path */ + + path = malloc(strlen(reffile) + 10u); + strcpy(path, reffile); + s = basename(path); + *s = '\0'; + strcat(path, "n"); + ++s; + strcpy(s, basename(reffile)); + newreffile = strdup(path); + strcpy(s, basename(invname)); + newinvname = strdup(path); + strcpy(s, basename(invpost)); + newinvpost = strdup(path); + free(path); } /* open the database */ -void -opendatabase(void) -{ - if ((symrefs = vpopen(reffile, O_BINARY | O_RDONLY)) == -1) { - cannotopen(reffile); - myexit(1); - } - blocknumber = -1; /* force next seek to read the first block */ - - /* open any inverted index */ - if (invertedindex == true && - invopen(&invcontrol, invname, invpost, INVAVAIL) == -1) { - askforreturn(); /* so user sees message */ - invertedindex = false; - } +void opendatabase(void) { + if((symrefs = vpopen(reffile, O_BINARY | O_RDONLY)) == -1) { + cannotopen(reffile); + myexit(1); + } + blocknumber = -1; /* force next seek to read the first block */ + + /* open any inverted index */ + if(invertedindex == true && invopen(&invcontrol, invname, invpost, INVAVAIL) == -1) { + askforreturn(); /* so user sees message */ + invertedindex = false; + } } - /* rebuild the database */ -void -rebuild(void) -{ - close(symrefs); - if (invertedindex == true) { - invclose(&invcontrol); - nsrcoffset = 0; - npostings = 0; - } - build(); - opendatabase(); - - /* revert to the initial display */ - if (refsfound != NULL) { - fclose(refsfound); - refsfound = NULL; - } +void rebuild(void) { + close(symrefs); + if(invertedindex == true) { + invclose(&invcontrol); + nsrcoffset = 0; + npostings = 0; + } + build(); + opendatabase(); + + /* revert to the initial display */ + if(refsfound != NULL) { + fclose(refsfound); + refsfound = NULL; + } } - /* build the cross-reference */ -void -build(void) -{ - unsigned long i; - FILE *oldrefs; /* old cross-reference file */ - time_t reftime; /* old crossref modification time */ - char *file; /* current file */ - char *oldfile; /* file in old cross-reference */ - char newdir[PATHLEN + 1]; /* directory in new cross-reference */ - char olddir[PATHLEN + 1]; /* directory in old cross-reference */ - char oldname[PATHLEN + 1]; /* name in old cross-reference */ - unsigned long oldnum; /* number in old cross-ref */ - struct stat statstruct; /* file status */ - unsigned long firstfile; /* first source file in pass */ - unsigned long lastfile; /* last source file in pass */ - int built = 0; /* built crossref for these files */ - int copied = 0; /* copied crossref for these files */ - unsigned long fileindex; /* source file name index */ - bool interactive = true; /* output progress messages */ - - /* normalize the current directory relative to the home directory so - the cross-reference is not rebuilt when the user's login is moved */ - strcpy(newdir, currentdir); - if (strcmp(currentdir, home) == 0) { - strcpy(newdir, "$HOME"); - } else if (strncmp(currentdir, home, strlen(home)) == 0) { - snprintf(newdir, sizeof(newdir), "$HOME%s", currentdir + strlen(home)); - } - /* sort the source file names (needed for rebuilding) */ - qsort(srcfiles, nsrcfiles, sizeof(*srcfiles), compare); - - /* if there is an old cross-reference and its current directory matches */ - /* or this is an unconditional build */ - if ((oldrefs = vpfopen(reffile, "rb")) != NULL - && unconditional == false - && fscanf(oldrefs, PROGRAM_NAME " %d %" PATHLEN_STR "s", &fileversion, olddir) == 2 - && (strcmp(olddir, currentdir) == 0 /* remain compatible */ - || strcmp(olddir, newdir) == 0)) { - /* get the cross-reference file's modification time */ - fstat(fileno(oldrefs), &statstruct); - reftime = statstruct.st_mtime; - if (fileversion >= 8) { - bool oldcompress = true; - bool oldinvertedindex = false; - bool oldtruncate = false; - int c; - - /* see if there are options in the database */ - for (;;) { - while((c = getc(oldrefs)) == ' ') - ; /* do nothing */ - if (c != '-') { - ungetc(c, oldrefs); - break; - } - switch (getc(oldrefs)) { - case 'c': /* ASCII characters only */ - oldcompress = false; - break; - case 'q': /* quick search */ - oldinvertedindex = true; - fscanf(oldrefs, "%ld", &totalterms); - break; - case 'T': /* truncate symbols to 8 characters */ - oldtruncate = true; - break; - } - } - /* check the old and new option settings */ - if (oldcompress != compress || oldtruncate != trun_syms) { - posterr(PROGRAM_NAME ": -c or -T option mismatch between command line and old symbol database\n"); - goto force; - } - if (oldinvertedindex != invertedindex) { - posterr(PROGRAM_NAME ": -q option mismatch between command line and old symbol database\n"); - if (invertedindex == false) { - posterr(PROGRAM_NAME ": removed files %s and %s\n", - invname, invpost); - unlink(invname); - unlink(invpost); - } - goto outofdate; - } - /* seek to the trailer */ - if (fscanf(oldrefs, "%ld", &traileroffset) != 1 || - fseek(oldrefs, traileroffset, SEEK_SET) == -1) { - posterr(PROGRAM_NAME ": incorrect symbol database file format\n"); - goto force; - } - } - /* if assuming that some files have changed */ - if (fileschanged == true) { - goto outofdate; - } - /* see if the directory lists are the same */ - if (samelist(oldrefs, srcdirs, nsrcdirs) == false - || samelist(oldrefs, incdirs, nincdirs) == false - /* get the old number of files */ - || fscanf(oldrefs, "%lu", &oldnum) != 1 - /* skip the string space size */ - || (fileversion >= 9 && fscanf(oldrefs, "%*s") != 0)) { - goto outofdate; - } - /* see if the list of source files is the same and - none have been changed up to the included files */ - for (i = 0; i < nsrcfiles; ++i) { - if ((1 != fscanf(oldrefs," %[^\n]",oldname)) - || strnotequal(oldname, srcfiles[i]) - || (lstat(srcfiles[i], &statstruct) != 0) - || (statstruct.st_mtime > reftime) - ) { - goto outofdate; - } - } - /* the old cross-reference is up-to-date */ - /* so get the list of included files */ - while (i++ < oldnum && fgets(oldname, sizeof(oldname), oldrefs)) { - addsrcfile(oldname); - } - fclose(oldrefs); - return; - - outofdate: - /* if the database format has changed, rebuild it all */ - if (fileversion != FILEVERSION) { - fprintf(stderr, PROGRAM_NAME ": converting to new symbol database file format\n"); - goto force; - } - /* reopen the old cross-reference file for fast scanning */ - if ((symrefs = vpopen(reffile, O_BINARY | O_RDONLY)) == -1) { - postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile); - /* NOTREACHED */ - } - /* get the first file name in the old cross-reference */ - blocknumber = -1; - read_block(); /* read the first cross-ref block */ - scanpast('\t'); /* skip the header */ - oldfile = getoldfile(); - } else { /* force cross-referencing of all the source files */ - force: - reftime = 0; - oldfile = NULL; - } - /* open the new cross-reference file */ - if ((newrefs = myfopen(newreffile, "wb")) == NULL) { - postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile); - /* NOTREACHED */ - } - if (invertedindex == true && (postings = myfopen(temp1, "wb")) == NULL) { - cannotwrite(temp1); - cannotindex(); - } - putheader(newdir); - fileversion = FILEVERSION; - if (buildonly == true && verbosemode != true && !isatty(0)) { - interactive = false; - } else { - searchcount = 0; - } - /* output the leading tab expected by crossref() */ - dbputc('\t'); - - /* make passes through the source file list until the last level of - included files is processed */ - firstfile = 0; - lastfile = nsrcfiles; - if (invertedindex == true) { - srcoffset = malloc((nsrcfiles + 1u) * sizeof(*srcoffset)); - } - for (;;) { - progress("Building symbol database", (long)built, - (long)lastfile); - if (linemode == false) - refresh(); - - /* get the next source file name */ - for (fileindex = firstfile; fileindex < lastfile; ++fileindex) { - - /* display the progress about every three seconds */ - if (interactive == true && fileindex % 10 == 0) { - progress("Building symbol database", fileindex, lastfile); - } - /* if the old file has been deleted get the next one */ - file = srcfiles[fileindex]; - while (oldfile != NULL && strcmp(file, oldfile) > 0) { - oldfile = getoldfile(); - } - /* if there isn't an old database or this is a new file */ - if (oldfile == NULL || strcmp(file, oldfile) < 0) { - crossref(file); - ++built; - } else if (lstat(file, &statstruct) == 0 - && statstruct.st_mtime > reftime) { - /* if this file was modified */ - crossref(file); - ++built; - - /* skip its old crossref so modifying the last source - * file does not cause all included files to be built. - * Unfortunately a new file that is alphabetically - * last will cause all included files to be build, but - * this is less likely */ - oldfile = getoldfile(); - } else { - /* copy its cross-reference */ - putfilename(file); - if (invertedindex == true) { - copyinverted(); - } else { - copydata(); - } - ++copied; - oldfile = getoldfile(); - } - } - /* see if any included files were found */ - if (lastfile == nsrcfiles) { - break; - } - firstfile = lastfile; - lastfile = nsrcfiles; - if (invertedindex == true) { - srcoffset = realloc(srcoffset, (nsrcfiles + 1) * sizeof(*srcoffset)); - } - /* sort the included file names */ - qsort(srcfiles + firstfile, lastfile - firstfile, sizeof(*srcfiles), compare); - } - /* add a null file name to the trailing tab */ - putfilename(""); - dbputc('\n'); - - /* get the file trailer offset */ - traileroffset = dboffset; - - /* output the source and include directory and file lists */ - putlist(srcdirs, nsrcdirs); - putlist(incdirs, nincdirs); - putlist(srcfiles, nsrcfiles); - if (fflush(newrefs) == EOF) { - /* rewind doesn't check for write failure */ - cannotwrite(newreffile); - /* NOTREACHED */ - } - - /* create the inverted index if requested */ - if (invertedindex == true) { - char sortcommand[PATHLEN + 1]; - - if (fflush(postings) == EOF) { - cannotwrite(temp1); - /* NOTREACHED */ - } - fstat(fileno(postings), &statstruct); - fclose(postings); - snprintf(sortcommand, sizeof(sortcommand), "env LC_ALL=C sort -T %s %s", tmpdir, temp1); - if ((postings = mypopen(sortcommand, "r")) == NULL) { - fprintf(stderr, PROGRAM_NAME ": cannot open pipe to sort command\n"); - cannotindex(); - } else { - if ((totalterms = invmake(newinvname, newinvpost, postings)) > 0) { - movefile(newinvname, invname); - movefile(newinvpost, invpost); - } else { - cannotindex(); - } - mypclose(postings); - } - unlink(temp1); - free(srcoffset); - } - /* rewrite the header with the trailer offset and final option list */ - rewind(newrefs); - putheader(newdir); - fclose(newrefs); - - /* close the old database file */ - if (symrefs >= 0) { - close(symrefs); - } - if (oldrefs != NULL) { - fclose(oldrefs); - } - /* replace it with the new database file */ - movefile(newreffile, reffile); +void build(void) { + unsigned long i; + FILE *oldrefs; /* old cross-reference file */ + time_t reftime; /* old crossref modification time */ + char *file; /* current file */ + char *oldfile; /* file in old cross-reference */ + char newdir[PATHLEN + 1]; /* directory in new cross-reference */ + char olddir[PATHLEN + 1]; /* directory in old cross-reference */ + char oldname[PATHLEN + 1]; /* name in old cross-reference */ + unsigned long oldnum; /* number in old cross-ref */ + struct stat statstruct; /* file status */ + unsigned long firstfile; /* first source file in pass */ + unsigned long lastfile; /* last source file in pass */ + int built = 0; /* built crossref for these files */ + int copied = 0; /* copied crossref for these files */ + unsigned long fileindex; /* source file name index */ + bool interactive = true; /* output progress messages */ + + /* normalize the current directory relative to the home directory so + the cross-reference is not rebuilt when the user's login is moved */ + strcpy(newdir, currentdir); + if(strcmp(currentdir, home) == 0) { + strcpy(newdir, "$HOME"); + } else if(strncmp(currentdir, home, strlen(home)) == 0) { + snprintf(newdir, sizeof(newdir), "$HOME%s", currentdir + strlen(home)); + } + /* sort the source file names (needed for rebuilding) */ + qsort(srcfiles, nsrcfiles, sizeof(*srcfiles), compare); + + /* if there is an old cross-reference and its current directory matches */ + /* or this is an unconditional build */ + if((oldrefs = vpfopen(reffile, "rb")) != NULL && unconditional == false && + fscanf(oldrefs, PROGRAM_NAME " %d %" PATHLEN_STR "s", &fileversion, olddir) == + 2 && + (strcmp(olddir, currentdir) == 0 /* remain compatible */ + || strcmp(olddir, newdir) == 0)) { + /* get the cross-reference file's modification time */ + fstat(fileno(oldrefs), &statstruct); + reftime = statstruct.st_mtime; + if(fileversion >= 8) { + bool oldcompress = true; + bool oldinvertedindex = false; + bool oldtruncate = false; + int c; + + /* see if there are options in the database */ + for(;;) { + while((c = getc(oldrefs)) == ' ') + ; /* do nothing */ + if(c != '-') { + ungetc(c, oldrefs); + break; + } + switch(getc(oldrefs)) { + case 'c': /* ASCII characters only */ + oldcompress = false; + break; + case 'q': /* quick search */ + oldinvertedindex = true; + fscanf(oldrefs, "%ld", &totalterms); + break; + case 'T': /* truncate symbols to 8 characters */ + oldtruncate = true; + break; + } + } + /* check the old and new option settings */ + if(oldcompress != compress || oldtruncate != trun_syms) { + posterr(PROGRAM_NAME + ": -c or -T option mismatch between command line and old symbol database\n"); + goto force; + } + if(oldinvertedindex != invertedindex) { + posterr(PROGRAM_NAME + ": -q option mismatch between command line and old symbol database\n"); + if(invertedindex == false) { + posterr(PROGRAM_NAME ": removed files %s and %s\n", invname, invpost); + unlink(invname); + unlink(invpost); + } + goto outofdate; + } + /* seek to the trailer */ + if(fscanf(oldrefs, "%ld", &traileroffset) != 1 || + fseek(oldrefs, traileroffset, SEEK_SET) == -1) { + posterr(PROGRAM_NAME ": incorrect symbol database file format\n"); + goto force; + } + } + /* if assuming that some files have changed */ + if(fileschanged == true) { goto outofdate; } + /* see if the directory lists are the same */ + if(samelist(oldrefs, srcdirs, nsrcdirs) == false || + samelist(oldrefs, incdirs, nincdirs) == false + /* get the old number of files */ + || fscanf(oldrefs, "%lu", &oldnum) != 1 + /* skip the string space size */ + || (fileversion >= 9 && fscanf(oldrefs, "%*s") != 0)) { + goto outofdate; + } + /* see if the list of source files is the same and + none have been changed up to the included files */ + for(i = 0; i < nsrcfiles; ++i) { + if((1 != fscanf(oldrefs, " %[^\n]", oldname)) || + strnotequal(oldname, srcfiles[i]) || + (lstat(srcfiles[i], &statstruct) != 0) || + (statstruct.st_mtime > reftime)) { + goto outofdate; + } + } + /* the old cross-reference is up-to-date */ + /* so get the list of included files */ + while(i++ < oldnum && fgets(oldname, sizeof(oldname), oldrefs)) { + addsrcfile(oldname); + } + fclose(oldrefs); + return; + + outofdate: + /* if the database format has changed, rebuild it all */ + if(fileversion != FILEVERSION) { + fprintf(stderr, + PROGRAM_NAME ": converting to new symbol database file format\n"); + goto force; + } + /* reopen the old cross-reference file for fast scanning */ + if((symrefs = vpopen(reffile, O_BINARY | O_RDONLY)) == -1) { + postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile); + /* NOTREACHED */ + } + /* get the first file name in the old cross-reference */ + blocknumber = -1; + read_block(); /* read the first cross-ref block */ + scanpast('\t'); /* skip the header */ + oldfile = getoldfile(); + } else { /* force cross-referencing of all the source files */ + force: + reftime = 0; + oldfile = NULL; + } + /* open the new cross-reference file */ + if((newrefs = myfopen(newreffile, "wb")) == NULL) { + postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile); + /* NOTREACHED */ + } + if(invertedindex == true && (postings = myfopen(temp1, "wb")) == NULL) { + cannotwrite(temp1); + cannotindex(); + } + putheader(newdir); + fileversion = FILEVERSION; + if(buildonly == true && verbosemode != true && !isatty(0)) { + interactive = false; + } else { + searchcount = 0; + } + /* output the leading tab expected by crossref() */ + dbputc('\t'); + + /* make passes through the source file list until the last level of + included files is processed */ + firstfile = 0; + lastfile = nsrcfiles; + if(invertedindex == true) { + srcoffset = malloc((nsrcfiles + 1u) * sizeof(*srcoffset)); + } + for(;;) { + progress("Building symbol database", (long)built, (long)lastfile); + if(linemode == false) refresh(); + + /* get the next source file name */ + for(fileindex = firstfile; fileindex < lastfile; ++fileindex) { + + /* display the progress about every three seconds */ + if(interactive == true && fileindex % 10 == 0) { + progress("Building symbol database", fileindex, lastfile); + } + /* if the old file has been deleted get the next one */ + file = srcfiles[fileindex]; + while(oldfile != NULL && strcmp(file, oldfile) > 0) { + oldfile = getoldfile(); + } + /* if there isn't an old database or this is a new file */ + if(oldfile == NULL || strcmp(file, oldfile) < 0) { + crossref(file); + ++built; + } else if(lstat(file, &statstruct) == 0 && statstruct.st_mtime > reftime) { + /* if this file was modified */ + crossref(file); + ++built; + + /* skip its old crossref so modifying the last source + * file does not cause all included files to be built. + * Unfortunately a new file that is alphabetically + * last will cause all included files to be build, but + * this is less likely */ + oldfile = getoldfile(); + } else { + /* copy its cross-reference */ + putfilename(file); + if(invertedindex == true) { + copyinverted(); + } else { + copydata(); + } + ++copied; + oldfile = getoldfile(); + } + } + /* see if any included files were found */ + if(lastfile == nsrcfiles) { break; } + firstfile = lastfile; + lastfile = nsrcfiles; + if(invertedindex == true) { + srcoffset = realloc(srcoffset, (nsrcfiles + 1) * sizeof(*srcoffset)); + } + /* sort the included file names */ + qsort(srcfiles + firstfile, lastfile - firstfile, sizeof(*srcfiles), compare); + } + /* add a null file name to the trailing tab */ + putfilename(""); + dbputc('\n'); + + /* get the file trailer offset */ + traileroffset = dboffset; + + /* output the source and include directory and file lists */ + putlist(srcdirs, nsrcdirs); + putlist(incdirs, nincdirs); + putlist(srcfiles, nsrcfiles); + if(fflush(newrefs) == EOF) { + /* rewind doesn't check for write failure */ + cannotwrite(newreffile); + /* NOTREACHED */ + } + + /* create the inverted index if requested */ + if(invertedindex == true) { + char sortcommand[PATHLEN + 1]; + + if(fflush(postings) == EOF) { + cannotwrite(temp1); + /* NOTREACHED */ + } + fstat(fileno(postings), &statstruct); + fclose(postings); + snprintf(sortcommand, + sizeof(sortcommand), + "env LC_ALL=C sort -T %s %s", + tmpdir, + temp1); + if((postings = mypopen(sortcommand, "r")) == NULL) { + fprintf(stderr, PROGRAM_NAME ": cannot open pipe to sort command\n"); + cannotindex(); + } else { + if((totalterms = invmake(newinvname, newinvpost, postings)) > 0) { + movefile(newinvname, invname); + movefile(newinvpost, invpost); + } else { + cannotindex(); + } + mypclose(postings); + } + unlink(temp1); + free(srcoffset); + } + /* rewrite the header with the trailer offset and final option list */ + rewind(newrefs); + putheader(newdir); + fclose(newrefs); + + /* close the old database file */ + if(symrefs >= 0) { close(symrefs); } + if(oldrefs != NULL) { fclose(oldrefs); } + /* replace it with the new database file */ + movefile(newreffile, reffile); } - /* string comparison function for qsort */ -static int -compare(const void *arg_s1, const void *arg_s2) -{ - const char **s1 = (const char **) arg_s1; - const char **s2 = (const char **) arg_s2; +static int compare(const void *arg_s1, const void *arg_s2) { + const char **s1 = (const char **)arg_s1; + const char **s2 = (const char **)arg_s2; - return(strcmp(*s1, *s2)); + return (strcmp(*s1, *s2)); } - /* seek to the trailer, in a given file */ -void -seek_to_trailer(FILE *f) -{ - if (fscanf(f, "%ld", &traileroffset) != 1) { - postfatal(PROGRAM_NAME ": cannot read trailer offset from file %s\n", reffile); - /* NOTREACHED */ - } - if (fseek(f, traileroffset, SEEK_SET) == -1) { - postfatal(PROGRAM_NAME ": cannot seek to trailer in file %s\n", reffile); - /* NOTREACHED */ - } +void seek_to_trailer(FILE *f) { + if(fscanf(f, "%ld", &traileroffset) != 1) { + postfatal(PROGRAM_NAME ": cannot read trailer offset from file %s\n", reffile); + /* NOTREACHED */ + } + if(fseek(f, traileroffset, SEEK_SET) == -1) { + postfatal(PROGRAM_NAME ": cannot seek to trailer in file %s\n", reffile); + /* NOTREACHED */ + } } - /* get the next file name in the old cross-reference */ -static char * -getoldfile(void) -{ - static char file[PATHLEN + 1]; /* file name in old crossref */ - - if (blockp != NULL) { - do { - if (*blockp == NEWFILE) { - skiprefchar(); - fetch_string_from_dbase(file, sizeof(file)); - if (file[0] != '\0') { /* if not end-of-crossref */ - return(file); - } - return(NULL); - } - } while (scanpast('\t') != NULL); - } - return(NULL); +static char *getoldfile(void) { + static char file[PATHLEN + 1]; /* file name in old crossref */ + + if(blockp != NULL) { + do { + if(*blockp == NEWFILE) { + skiprefchar(); + fetch_string_from_dbase(file, sizeof(file)); + if(file[0] != '\0') { /* if not end-of-crossref */ + return (file); + } + return (NULL); + } + } while(scanpast('\t') != NULL); + } + return (NULL); } - /* Free all storage allocated for filenames: */ -void free_newbuildfiles(void) -{ - free(newinvname); - free(newinvpost); - free(newreffile); +void free_newbuildfiles(void) { + free(newinvname); + free(newinvpost); + free(newreffile); } - /* output the cscope version, current directory, database format options, and the database trailer offset */ -static void -putheader(char *dir) -{ - dboffset = fprintf(newrefs, PROGRAM_NAME " %d %s", FILEVERSION, dir); - if (compress == false) { - dboffset += fprintf(newrefs, " -c"); - } - if (invertedindex == true) { - dboffset += fprintf(newrefs, " -q %.10ld", totalterms); - } else { - /* leave space so if the header is overwritten without -q - * because writing the inverted index failed, the header - * is the same length */ - dboffset += fprintf(newrefs, " "); - } - if (trun_syms == true) { - dboffset += fprintf(newrefs, " -T"); - } - - dboffset += fprintf(newrefs, " %.10ld\n", traileroffset); +static void putheader(char *dir) { + dboffset = fprintf(newrefs, PROGRAM_NAME " %d %s", FILEVERSION, dir); + if(compress == false) { dboffset += fprintf(newrefs, " -c"); } + if(invertedindex == true) { + dboffset += fprintf(newrefs, " -q %.10ld", totalterms); + } else { + /* leave space so if the header is overwritten without -q + * because writing the inverted index failed, the header + * is the same length */ + dboffset += fprintf(newrefs, " "); + } + if(trun_syms == true) { dboffset += fprintf(newrefs, " -T"); } + + dboffset += fprintf(newrefs, " %.10ld\n", traileroffset); #ifdef PRINTF_RETVAL_BROKEN - dboffset = ftell(newrefs); + dboffset = ftell(newrefs); #endif } - /* put the name list into the cross-reference file */ -static void -putlist(char **names, int count) -{ - int i, size = 0; - - fprintf(newrefs, "%d\n", count); - if (names == srcfiles) { - - /* calculate the string space needed */ - for (i = 0; i < count; ++i) { - size += strlen(names[i]) + 1; - } - fprintf(newrefs, "%d\n", size); - } - for (i = 0; i < count; ++i) { - if (fputs(names[i], newrefs) == EOF || - putc('\n', newrefs) == EOF) { - cannotwrite(newreffile); - /* NOTREACHED */ - } - } +static void putlist(char **names, int count) { + int i, size = 0; + + fprintf(newrefs, "%d\n", count); + if(names == srcfiles) { + + /* calculate the string space needed */ + for(i = 0; i < count; ++i) { + size += strlen(names[i]) + 1; + } + fprintf(newrefs, "%d\n", size); + } + for(i = 0; i < count; ++i) { + if(fputs(names[i], newrefs) == EOF || putc('\n', newrefs) == EOF) { + cannotwrite(newreffile); + /* NOTREACHED */ + } + } } - /* copy this file's symbol data */ -static void -copydata(void) -{ - char *cp; - - setmark('\t'); - cp = blockp; - for (;;) { - /* copy up to the next \t */ - do { /* innermost loop optimized to only one test */ - while (*cp != '\t') { - dbputc(*cp++); - } - } while (*++cp == '\0' && (cp = read_block()) != NULL); - dbputc('\t'); /* copy the tab */ - - /* get the next character */ - /* HBB 2010-08-21: potential problem if above loop was left - * with cp==NULL */ - if (cp && (*(cp + 1) == '\0')) { - cp = read_block(); - } - /* exit if at the end of this file's data */ - if (cp == NULL || *cp == NEWFILE) { - break; - } - /* look for an #included file */ - if (*cp == INCLUDE) { - char symbol[PATLEN + 1]; - blockp = cp; - fetch_include_from_dbase(symbol, sizeof(symbol)); - writestring(symbol); - setmark('\t'); - cp = blockp; - } - } - blockp = cp; +static void copydata(void) { + char *cp; + + setmark('\t'); + cp = blockp; + for(;;) { + /* copy up to the next \t */ + do { /* innermost loop optimized to only one test */ + while(*cp != '\t') { + dbputc(*cp++); + } + } while(*++cp == '\0' && (cp = read_block()) != NULL); + dbputc('\t'); /* copy the tab */ + + /* get the next character */ + /* HBB 2010-08-21: potential problem if above loop was left + * with cp==NULL */ + if(cp && (*(cp + 1) == '\0')) { cp = read_block(); } + /* exit if at the end of this file's data */ + if(cp == NULL || *cp == NEWFILE) { break; } + /* look for an #included file */ + if(*cp == INCLUDE) { + char symbol[PATLEN + 1]; + blockp = cp; + fetch_include_from_dbase(symbol, sizeof(symbol)); + writestring(symbol); + setmark('\t'); + cp = blockp; + } + } + blockp = cp; } /* copy this file's symbol data and output the inverted index postings */ -static void -copyinverted(void) -{ - char *cp; - char c; - int type; /* reference type (mark character) */ - char symbol[PATLEN + 1]; - - /* note: this code was expanded in-line for speed */ - /* while (scanpast('\n') != NULL) { */ - /* other macros were replaced by code using cp instead of blockp */ - cp = blockp; - for (;;) { - setmark('\n'); - do { /* innermost loop optimized to only one test */ - while (*cp != '\n') { - dbputc(*cp++); - } - } while (*++cp == '\0' && (cp = read_block()) != NULL); - dbputc('\n'); /* copy the newline */ - - /* get the next character */ - /* HBB 2010-08-21: potential problem if above loop was left - * with cp==NULL */ - if (cp && (*(cp + 1) == '\0')) { - cp = read_block(); - } - /* exit if at the end of this file's data */ - if (cp == NULL) { - break; - } - switch (*cp) { - case '\n': - lineoffset = dboffset + 1; - continue; - case '\t': - dbputc('\t'); - blockp = cp; - type = getrefchar(); - switch (type) { - case NEWFILE: /* file name */ - return; - case INCLUDE: /* #included file */ - fetch_include_from_dbase(symbol, sizeof(symbol)); - goto output; - } - dbputc(type); - skiprefchar(); - fetch_string_from_dbase(symbol, sizeof(symbol)); - goto output; - } - c = *cp; - if (c & 0200) { /* digraph char? */ - c = dichar1[(c & 0177) / 8]; - } - /* if this is a symbol */ - if (isalpha((unsigned char)c) || c == '_') { - blockp = cp; - fetch_string_from_dbase(symbol, sizeof(symbol)); - type = ' '; - output: - putposting(symbol, type); - writestring(symbol); - if (blockp == NULL) { - return; - } - cp = blockp; - } - } - blockp = cp; +static void copyinverted(void) { + char *cp; + char c; + int type; /* reference type (mark character) */ + char symbol[PATLEN + 1]; + + /* note: this code was expanded in-line for speed */ + /* while (scanpast('\n') != NULL) { */ + /* other macros were replaced by code using cp instead of blockp */ + cp = blockp; + for(;;) { + setmark('\n'); + do { /* innermost loop optimized to only one test */ + while(*cp != '\n') { + dbputc(*cp++); + } + } while(*++cp == '\0' && (cp = read_block()) != NULL); + dbputc('\n'); /* copy the newline */ + + /* get the next character */ + /* HBB 2010-08-21: potential problem if above loop was left + * with cp==NULL */ + if(cp && (*(cp + 1) == '\0')) { cp = read_block(); } + /* exit if at the end of this file's data */ + if(cp == NULL) { break; } + switch(*cp) { + case '\n': + lineoffset = dboffset + 1; + continue; + case '\t': + dbputc('\t'); + blockp = cp; + type = getrefchar(); + switch(type) { + case NEWFILE: /* file name */ + return; + case INCLUDE: /* #included file */ + fetch_include_from_dbase(symbol, sizeof(symbol)); + goto output; + } + dbputc(type); + skiprefchar(); + fetch_string_from_dbase(symbol, sizeof(symbol)); + goto output; + } + c = *cp; + if(c & 0200) { /* digraph char? */ + c = dichar1[(c & 0177) / 8]; + } + /* if this is a symbol */ + if(isalpha((unsigned char)c) || c == '_') { + blockp = cp; + fetch_string_from_dbase(symbol, sizeof(symbol)); + type = ' '; + output: + putposting(symbol, type); + writestring(symbol); + if(blockp == NULL) { return; } + cp = blockp; + } + } + blockp = cp; } - /* replace the old file with the new file */ -static void -movefile(char *new, char *old) -{ - unlink(old); - if (rename(new, old) == -1) { - myperror(PROGRAM_NAME); - postfatal(PROGRAM_NAME ": cannot rename file %s to file %s\n", - new, old); - /* NOTREACHED */ - } +static void movefile(char *new, char *old) { + unlink(old); + if(rename(new, old) == -1) { + myperror(PROGRAM_NAME); + postfatal(PROGRAM_NAME ": cannot rename file %s to file %s\n", new, old); + /* NOTREACHED */ + } } - /* process the #included file in the old database */ -static void -fetch_include_from_dbase(char *s, size_t length) -{ - dbputc(INCLUDE); - skiprefchar(); - fetch_string_from_dbase(s, length); - incfile(s + 1, s); +static void fetch_include_from_dbase(char *s, size_t length) { + dbputc(INCLUDE); + skiprefchar(); + fetch_string_from_dbase(s, length); + incfile(s + 1, s); } diff --git a/src/build.h b/src/build.h index 68f5c4e..ae1645b 100644 --- a/src/build.h +++ b/src/build.h @@ -33,38 +33,38 @@ #ifndef CSCOPE_BUILD_H #define CSCOPE_BUILD_H -#include "global.h" /* FIXME: temp. only */ +#include "global.h" /* FIXME: temp. only */ #include "invlib.h" /* types and macros of build.c to be used by other modules */ /* database output macros that update its offset */ -#define dbputc(c) (++dboffset, (void) putc(c, newrefs)) -#define dbfputs(s) (dboffset += strlen(s), fputs(s, newrefs)) +#define dbputc(c) (++dboffset, (void)putc(c, newrefs)) +#define dbfputs(s) (dboffset += strlen(s), fputs(s, newrefs)) /* declarations for globals defined in build.c */ -extern bool buildonly; /* only build the database */ -extern bool unconditional; /* unconditionally build database */ -extern bool fileschanged; /* assume some files changed */ +extern bool buildonly; /* only build the database */ +extern bool unconditional; /* unconditionally build database */ +extern bool fileschanged; /* assume some files changed */ -extern char *reffile; /* cross-reference file path name */ -extern char *invname; /* inverted index to the database */ -extern char *invpost; /* inverted index postings */ -extern char *newreffile; /* new cross-reference file name */ -extern FILE *newrefs; /* new cross-reference */ -extern FILE *postings; /* new inverted index postings */ -extern int symrefs; /* cross-reference file */ +extern char *reffile; /* cross-reference file path name */ +extern char *invname; /* inverted index to the database */ +extern char *invpost; /* inverted index postings */ +extern char *newreffile; /* new cross-reference file name */ +extern FILE *newrefs; /* new cross-reference */ +extern FILE *postings; /* new inverted index postings */ +extern int symrefs; /* cross-reference file */ -extern INVCONTROL invcontrol; /* inverted file control structure */ +extern INVCONTROL invcontrol; /* inverted file control structure */ /* Prototypes of external functions defined by build.c */ -void build(void); -void free_newbuildfiles(void); -void opendatabase(void); -void rebuild(void); -void setup_build_filenames(char *reffile); -void seek_to_trailer(FILE *f); +void build(void); +void free_newbuildfiles(void); +void opendatabase(void); +void rebuild(void); +void setup_build_filenames(char *reffile); +void seek_to_trailer(FILE *f); #endif /* CSCOPE_BUILD_H */ diff --git a/src/command.c b/src/command.c index 3921a11..be09d73 100644 --- a/src/command.c +++ b/src/command.c @@ -36,14 +36,14 @@ */ #include "global.h" -#include "build.h" /* for rebuild() */ +#include "build.h" /* for rebuild() */ #include #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) -#include +# include #else -#include +# include #endif #include @@ -54,164 +54,135 @@ * In the original version this was handled by * "int selecting // whether the (upper) symbol list is being browsed". */ -extern const void *const winput; -extern const void *const wmode; -extern const void *const wresult; +extern const void *const winput; +extern const void *const wmode; +extern const void *const wresult; extern const void *const *const current_window; -bool caseless; /* ignore letter case when searching */ -bool *change; /* change this line */ -char newpat[PATLEN + 1]; /* new pattern */ +bool caseless; /* ignore letter case when searching */ +bool *change; /* change this line */ +char newpat[PATLEN + 1]; /* new pattern */ /* Internal prototypes: */ -static void scrollbar(MOUSE *p); +static void scrollbar(MOUSE *p); /* read references from a file */ -bool -readrefs(char *filename) -{ - FILE *file; - int c; - - if ((file = myfopen(filename, "rb")) == NULL) { - cannotopen(filename); - return(false); - } - if ((c = getc(file)) == EOF) { /* if file is empty */ - fclose(file); - return(false); - } - totallines = 0; - disprefs = 0; - nextline = 1; - if (writerefsfound() == true) { - putc(c, refsfound); - while ((c = getc(file)) != EOF) { - putc(c, refsfound); - } - fclose(file); - fclose(refsfound); - if ( (refsfound = myfopen(temp1, "rb")) == NULL) { - cannotopen(temp1); - return(false); - } - countrefs(); - } else - fclose(file); - return(true); +bool readrefs(char *filename) { + FILE *file; + int c; + + if((file = myfopen(filename, "rb")) == NULL) { + cannotopen(filename); + return (false); + } + if((c = getc(file)) == EOF) { /* if file is empty */ + fclose(file); + return (false); + } + totallines = 0; + disprefs = 0; + nextline = 1; + if(writerefsfound() == true) { + putc(c, refsfound); + while((c = getc(file)) != EOF) { + putc(c, refsfound); + } + fclose(file); + fclose(refsfound); + if((refsfound = myfopen(temp1, "rb")) == NULL) { + cannotopen(temp1); + return (false); + } + countrefs(); + } else + fclose(file); + return (true); } /* scrollbar actions */ -static void -scrollbar(MOUSE *p) -{ - ///* reposition list if it makes sense */ - //if (totallines == 0) { - //return; - //} - //switch (p->percent) { - - //case 101: /* scroll down one page */ - //if (nextline + mdisprefs > totallines) { - // nextline = totallines - mdisprefs + 1; - //} - //break; - - //case 102: /* scroll up one page */ - //nextline = topline - mdisprefs; - //if (nextline < 1) { - // nextline = 1; - //} - //break; - - //case 103: /* scroll down one line */ - //nextline = topline + 1; - //break; - - //case 104: /* scroll up one line */ - //if (topline > 1) { - // nextline = topline - 1; - //} - //break; - //default: - //nextline = p->percent * totallines / 100; - //} - ////seekline(nextline); +static void scrollbar(MOUSE *p) { + ///* reposition list if it makes sense */ + // if (totallines == 0) { + // return; + // } + // switch (p->percent) { + + // case 101: /* scroll down one page */ + // if (nextline + mdisprefs > totallines) { + // nextline = totallines - mdisprefs + 1; + // } + // break; + + // case 102: /* scroll up one page */ + // nextline = topline - mdisprefs; + // if (nextline < 1) { + // nextline = 1; + // } + // break; + + // case 103: /* scroll down one line */ + // nextline = topline + 1; + // break; + + // case 104: /* scroll up one line */ + // if (topline > 1) { + // nextline = topline - 1; + // } + // break; + // default: + // nextline = p->percent * totallines / 100; + // } + ////seekline(nextline); } - /* count the references found */ -void -countrefs(void) -{ - char *subsystem; /* OGS subsystem name */ - char *book; /* OGS book name */ - char file[PATHLEN + 1]; /* file name */ - char function[PATLEN + 1]; /* function name */ - char linenum[NUMLEN + 1]; /* line number */ - int i; - - /* count the references found and find the length of the file, - function, and line number display fields */ - - /* HBB falseTE 2012-04-07: it may look like we shouldn't assing tempstring here, - * since it's not used. But it has to be assigned just so the return value - * of fscanf will actually reach 4. */ - while (EOF != (i = fscanf(refsfound, - "%" PATHLEN_STR "s%" PATLEN_STR "s%" NUMLEN_STR "s %" TEMPSTRING_LEN_STR "[^\n]", - file, function, linenum, tempstring - ) - ) - ) { - if ( (i != 4) - || !isgraph((unsigned char) *file) - || !isgraph((unsigned char) *function) - || !isdigit((unsigned char) *linenum) - ) { - postmsg("File does not have expected format"); - totallines = 0; - disprefs = 0; - return; - } - if ((i = strlen(pathcomponents(file, dispcomponents))) > filelen) { - filelen = i; - } - if (ogs == true) { - ogsnames(file, &subsystem, &book); - if ((i = strlen(subsystem)) > subsystemlen) { - subsystemlen = i; - } - if ((i = strlen(book)) > booklen) { - booklen = i; - } - } - if ((i = strlen(function)) > fcnlen) { - fcnlen = i; - } - if ((i = strlen(linenum)) > numlen) { - numlen = i; - } - ++totallines; - } - rewind(refsfound); - - /* restrict the width of displayed columns */ - /* HBB FIXME 20060419: magic number alert! */ - i = (COLS - 5) / 3; - if (ogs == true) { - i = (COLS - 7) / 5; - } - if (filelen > i && i > 4) { - filelen = i; - } - if (subsystemlen > i && i > 9) { - subsystemlen = i; - } - if (booklen > i && i > 4) { - booklen = i; - } - if (fcnlen > i && i > 8) { - fcnlen = i; - } +void countrefs(void) { + char *subsystem; /* OGS subsystem name */ + char *book; /* OGS book name */ + char file[PATHLEN + 1]; /* file name */ + char function[PATLEN + 1]; /* function name */ + char linenum[NUMLEN + 1]; /* line number */ + int i; + + /* count the references found and find the length of the file, + function, and line number display fields */ + + /* HBB falseTE 2012-04-07: it may look like we shouldn't assing tempstring here, + * since it's not used. But it has to be assigned just so the return value + * of fscanf will actually reach 4. */ + while(EOF != (i = fscanf(refsfound, + "%" PATHLEN_STR "s%" PATLEN_STR "s%" NUMLEN_STR + "s %" TEMPSTRING_LEN_STR "[^\n]", + file, + function, + linenum, + tempstring))) { + if((i != 4) || !isgraph((unsigned char)*file) || + !isgraph((unsigned char)*function) || !isdigit((unsigned char)*linenum)) { + postmsg("File does not have expected format"); + totallines = 0; + disprefs = 0; + return; + } + if((i = strlen(pathcomponents(file, dispcomponents))) > filelen) { filelen = i; } + if(ogs == true) { + ogsnames(file, &subsystem, &book); + if((i = strlen(subsystem)) > subsystemlen) { subsystemlen = i; } + if((i = strlen(book)) > booklen) { booklen = i; } + } + if((i = strlen(function)) > fcnlen) { fcnlen = i; } + if((i = strlen(linenum)) > numlen) { numlen = i; } + ++totallines; + } + rewind(refsfound); + + /* restrict the width of displayed columns */ + /* HBB FIXME 20060419: magic number alert! */ + i = (COLS - 5) / 3; + if(ogs == true) { i = (COLS - 7) / 5; } + if(filelen > i && i > 4) { filelen = i; } + if(subsystemlen > i && i > 9) { subsystemlen = i; } + if(booklen > i && i > 4) { booklen = i; } + if(fcnlen > i && i > 8) { fcnlen = i; } } diff --git a/src/constants.h b/src/constants.h index 012cadd..3e24d2f 100644 --- a/src/constants.h +++ b/src/constants.h @@ -38,77 +38,79 @@ #ifndef CSCOPE_CONSTANTS_H #define CSCOPE_CONSTANTS_H -#define ctrl(x) (x & 037) /* control character macro */ +#define ctrl(x) (x & 037) /* control character macro */ /* fast string equality tests (avoids most strcmp() calls) */ -#define strequal(s1, s2) (*(s1) == *(s2) && strcmp(s1, s2) == 0) -#define strnotequal(s1, s2) (*(s1) != *(s2) || strcmp(s1, s2) != 0) +#define strequal(s1, s2) (*(s1) == *(s2) && strcmp(s1, s2) == 0) +#define strnotequal(s1, s2) (*(s1) != *(s2) || strcmp(s1, s2) != 0) /* set the mark character for searching the cross-reference file */ -#define setmark(c) (blockmark = c, block[blocklen] = blockmark) +#define setmark(c) (blockmark = c, block[blocklen] = blockmark) /* get the next character in the cross-reference */ /* note that blockp is assumed not to be null */ -#define getrefchar() (*(++blockp + 1) != '\0' ? *blockp : \ - (read_block() != NULL ? *blockp : '\0')) +#define getrefchar() \ + (*(++blockp + 1) != '\0' ? *blockp : (read_block() != NULL ? *blockp : '\0')) /* skip the next character in the cross-reference */ /* note that blockp is assumed not to be null and that this macro will always be in a statement by itself */ -#define skiprefchar() if (*(++blockp + 1) == '\0') (void) read_block() - -#define DUMMYCHAR ' ' /* use space as a dummy character */ -#define MSGLEN ((PATLEN) + 80) /* displayed message length */ -#define NUMLEN 10 /* line number length */ -#define PATHLEN 250 /* file pathname length */ -#define PATLEN 250 /* symbol pattern length */ -#define TEMPSTRING_LEN 8191 /* max strlen() of the global temp string */ -#define REFFILE "cscope.out" /* cross-reference output file */ -#define NAMEFILE "cscope.files" /* default list-of-files file */ -#define INVNAME "cscope.in.out" /* inverted index to the database */ -#define INVPOST "cscope.po.out" /* inverted index postings */ -#define INVNAME2 "cscope.out.in"/* follows correct naming convention */ -#define INVPOST2 "cscope.out.po"/* follows correct naming convention */ - -#define STMTMAX 10000 /* maximum source statement length */ - -#define STR2(x) #x -#define STRINGIZE(x) STR2(x) -#define PATLEN_STR STRINGIZE(PATLEN) -#define PATHLEN_STR STRINGIZE(PATHLEN) -#define NUMLEN_STR STRINGIZE(NUMLEN) +#define skiprefchar() \ + if(*(++blockp + 1) == '\0') (void)read_block() + +#define DUMMYCHAR ' ' /* use space as a dummy character */ +#define MSGLEN ((PATLEN) + 80) /* displayed message length */ +#define NUMLEN 10 /* line number length */ +#define PATHLEN 250 /* file pathname length */ +#define PATLEN 250 /* symbol pattern length */ +#define TEMPSTRING_LEN 8191 /* max strlen() of the global temp string */ +#define REFFILE "cscope.out" /* cross-reference output file */ +#define NAMEFILE "cscope.files" /* default list-of-files file */ +#define INVNAME "cscope.in.out" /* inverted index to the database */ +#define INVPOST "cscope.po.out" /* inverted index postings */ +#define INVNAME2 "cscope.out.in" /* follows correct naming convention */ +#define INVPOST2 "cscope.out.po" /* follows correct naming convention */ + +#define STMTMAX 10000 /* maximum source statement length */ + +#define STR2(x) #x +#define STRINGIZE(x) STR2(x) +#define PATLEN_STR STRINGIZE(PATLEN) +#define PATHLEN_STR STRINGIZE(PATHLEN) +#define NUMLEN_STR STRINGIZE(NUMLEN) #define TEMPSTRING_LEN_STR STRINGIZE(TEMPSTRING_LEN) /* input fields (value matches field order on screen) */ enum { - SYMBOL = 0, - DEFINITION = 1, - CALLEDBY = 2, - CALLING = 3, - STRING = 4, - CHANGE = 5, - REGEXP = 6, - FILENAME = 7, - INCLUDES = 8 + SYMBOL = 0, + DEFINITION = 1, + CALLEDBY = 2, + CALLING = 3, + STRING = 4, + CHANGE = 5, + REGEXP = 6, + FILENAME = 7, + INCLUDES = 8 }; -#define FIELDS 10 + +#define FIELDS 10 // XXX #define bazdki 1 /* file open modes */ #ifndef R_OK -# define READ R_OK +# define READ R_OK #else -# define READ 4 +# define READ 4 #endif #ifdef W_OK -# define WRITE W_OK +# define WRITE W_OK #else -# define WRITE 2 +# define WRITE 2 #endif -#define O_TEXT 0x00 +#define O_TEXT 0x00 #define O_BINARY 0x00 diff --git a/src/crossref.c b/src/crossref.c index 40ef770..c08dc5b 100644 --- a/src/crossref.c +++ b/src/crossref.c @@ -46,447 +46,408 @@ #include /* convert long to a string in base BASE notation */ -#define ltobase(value) \ -do { \ - n = (value); \ - s = buf + (sizeof(buf) - 1); \ - *s = '\0'; \ - digits = 1; \ - while (n >= BASE) { \ - ++digits; \ - i = n; \ - n /= BASE; \ - *--s = i - n * BASE + '!'; \ - } \ - *--s = n + '!'; \ -} while (0) - -#define SYMBOLINC 20 /* symbol list size increment */ - -long dboffset; /* new database offset */ -bool errorsfound; /* prompt before clearing messages */ -long lineoffset; /* source line database offset */ -long npostings; /* number of postings */ -int nsrcoffset; /* number of file name database offsets */ -long *srcoffset; /* source file name database offsets */ -unsigned long symbols; /* number of symbols */ - -static char *filename; /* file name for warning messages */ -static long fcnoffset; /* function name database offset */ -static long macrooffset; /* macro name database offset */ -static unsigned long msymbols = SYMBOLINC; /* maximum number of symbols */ - -struct symbol { /* symbol data */ - int type; /* type */ - unsigned int first; /* index of first character in text */ - unsigned int last; /* index of last+1 character in text */ - unsigned int length; /* symbol length */ - unsigned int fcn_level; /* function level of the symbol */ +#define ltobase(value) \ + do { \ + n = (value); \ + s = buf + (sizeof(buf) - 1); \ + *s = '\0'; \ + digits = 1; \ + while(n >= BASE) { \ + ++digits; \ + i = n; \ + n /= BASE; \ + *--s = i - n * BASE + '!'; \ + } \ + *--s = n + '!'; \ + } while(0) + +#define SYMBOLINC 20 /* symbol list size increment */ + +long dboffset; /* new database offset */ +bool errorsfound; /* prompt before clearing messages */ +long lineoffset; /* source line database offset */ +long npostings; /* number of postings */ +int nsrcoffset; /* number of file name database offsets */ +long *srcoffset; /* source file name database offsets */ +unsigned long symbols; /* number of symbols */ + +static char *filename; /* file name for warning messages */ +static long fcnoffset; /* function name database offset */ +static long macrooffset; /* macro name database offset */ +static unsigned long msymbols = SYMBOLINC; /* maximum number of symbols */ + +struct symbol { /* symbol data */ + int type; /* type */ + unsigned int first; /* index of first character in text */ + unsigned int last; /* index of last+1 character in text */ + unsigned int length; /* symbol length */ + unsigned int fcn_level; /* function level of the symbol */ }; static struct symbol *symbol; -static void putcrossref(void); -static void savesymbol(int token, int num); - -void -crossref(char *srcfile) -{ - unsigned int i; - unsigned int length; /* symbol length */ - unsigned int entry_no; /* function level of the symbol */ - int token; /* current token */ - struct stat st; - - if (! ((stat(srcfile, &st) == 0) - && S_ISREG(st.st_mode))) { - cannotopen(srcfile); - errorsfound = true; - return; - } - - entry_no = 0; - /* open the source file */ - if ((yyin = myfopen(srcfile, "r")) == NULL) { - cannotopen(srcfile); - errorsfound = true; - return; - } - filename = srcfile; /* save the file name for warning messages */ - putfilename(srcfile); /* output the file name */ - dbputc('\n'); - dbputc('\n'); - - /* read the source file */ - initscanner(srcfile); - fcnoffset = macrooffset = 0; - symbols = 0; - if (symbol == NULL) { - symbol = malloc(msymbols * sizeof(*symbol)); - } - for (;;) { - - /* get the next token */ - switch (token = yylex()) { - default: - /* if requested, truncate C symbols */ - length = last - first; - if (trun_syms == true && length > 8 && - token != INCLUDE && token != NEWFILE) { - length = 8; - last = first + 8; - } - /* see if the token has a symbol */ - if (length == 0) { - savesymbol(token, entry_no); - break; - } - /* update entry_no if see function entry */ - if (token == FCNDEF) { - entry_no++; - } - /* see if the symbol is already in the list */ - for (i = 0; i < symbols; ++i) { - if (length == symbol[i].length - && strncmp(my_yytext + first, - my_yytext + symbol[i].first, - length) == 0 - && entry_no == symbol[i].fcn_level - && token == symbol[i].type - ) { /* could be a::a() */ - break; - } - } - if (i == symbols) { /* if not already in list */ - savesymbol(token, entry_no); - } - break; - - case NEWLINE: /* end of line containing symbols */ - entry_no = 0; /* reset entry_no for each line */ +static void putcrossref(void); +static void savesymbol(int token, int num); + +void crossref(char *srcfile) { + unsigned int i; + unsigned int length; /* symbol length */ + unsigned int entry_no; /* function level of the symbol */ + int token; /* current token */ + struct stat st; + + if(!((stat(srcfile, &st) == 0) && S_ISREG(st.st_mode))) { + cannotopen(srcfile); + errorsfound = true; + return; + } + + entry_no = 0; + /* open the source file */ + if((yyin = myfopen(srcfile, "r")) == NULL) { + cannotopen(srcfile); + errorsfound = true; + return; + } + filename = srcfile; /* save the file name for warning messages */ + putfilename(srcfile); /* output the file name */ + dbputc('\n'); + dbputc('\n'); + + /* read the source file */ + initscanner(srcfile); + fcnoffset = macrooffset = 0; + symbols = 0; + if(symbol == NULL) { symbol = malloc(msymbols * sizeof(*symbol)); } + for(;;) { + + /* get the next token */ + switch(token = yylex()) { + default: + /* if requested, truncate C symbols */ + length = last - first; + if(trun_syms == true && length > 8 && token != INCLUDE && + token != NEWFILE) { + length = 8; + last = first + 8; + } + /* see if the token has a symbol */ + if(length == 0) { + savesymbol(token, entry_no); + break; + } + /* update entry_no if see function entry */ + if(token == FCNDEF) { entry_no++; } + /* see if the symbol is already in the list */ + for(i = 0; i < symbols; ++i) { + if(length == symbol[i].length && + strncmp(my_yytext + first, my_yytext + symbol[i].first, length) == + 0 && + entry_no == symbol[i].fcn_level && + token == symbol[i].type) { /* could be a::a() */ + break; + } + } + if(i == symbols) { /* if not already in list */ + savesymbol(token, entry_no); + } + break; + + case NEWLINE: /* end of line containing symbols */ + entry_no = 0; /* reset entry_no for each line */ #ifdef USING_LEX - --yyleng; /* remove the newline */ + --yyleng; /* remove the newline */ #endif - putcrossref(); /* output the symbols and source line */ - lineno = myylineno; /* save the symbol line number */ + putcrossref(); /* output the symbols and source line */ + lineno = myylineno; /* save the symbol line number */ #ifndef USING_LEX - /* HBB 20010425: replaced yyleng-- by this chunk: */ - if (my_yytext) - *my_yytext = '\0'; - my_yyleng = 0; + /* HBB 20010425: replaced yyleng-- by this chunk: */ + if(my_yytext) *my_yytext = '\0'; + my_yyleng = 0; #endif - break; - - case LEXERR: /* Lexer error, abort further parsing of this file */ - case LEXEOF: /* end of file; last line may not have \n */ - - /* if there were symbols, output them and the source line */ - if (symbols > 0) { - putcrossref(); - } - (void) fclose(yyin); /* close the source file */ - - /* output the leading tab expected by the next call */ - dbputc('\t'); - return; - } - } + break; + + case LEXERR: /* Lexer error, abort further parsing of this file */ + case LEXEOF: /* end of file; last line may not have \n */ + + /* if there were symbols, output them and the source line */ + if(symbols > 0) { putcrossref(); } + (void)fclose(yyin); /* close the source file */ + + /* output the leading tab expected by the next call */ + dbputc('\t'); + return; + } + } } /* save the symbol in the list */ -static void -savesymbol(int token, int num) -{ - /* make sure there is room for the symbol */ - if (symbols == msymbols) { - msymbols += SYMBOLINC; - symbol = realloc(symbol, msymbols * sizeof(*symbol)); - } - /* save the symbol */ - symbol[symbols].type = token; - symbol[symbols].first = first; - symbol[symbols].last = last; - symbol[symbols].length = last - first; - symbol[symbols].fcn_level = num; - ++symbols; +static void savesymbol(int token, int num) { + /* make sure there is room for the symbol */ + if(symbols == msymbols) { + msymbols += SYMBOLINC; + symbol = realloc(symbol, msymbols * sizeof(*symbol)); + } + /* save the symbol */ + symbol[symbols].type = token; + symbol[symbols].first = first; + symbol[symbols].last = last; + symbol[symbols].length = last - first; + symbol[symbols].fcn_level = num; + ++symbols; } /* output the file name */ -void -putfilename(char *srcfile) -{ - /* check for file system out of space */ - /* note: dbputc is not used to avoid lint complaint */ - if (putc(NEWFILE, newrefs) == EOF) { - cannotwrite(newreffile); - /* NOTREACHED */ - } - ++dboffset; - if (invertedindex == true) { - srcoffset[nsrcoffset++] = dboffset; - } - dbfputs(srcfile); - fcnoffset = macrooffset = 0; +void putfilename(char *srcfile) { + /* check for file system out of space */ + /* note: dbputc is not used to avoid lint complaint */ + if(putc(NEWFILE, newrefs) == EOF) { + cannotwrite(newreffile); + /* NOTREACHED */ + } + ++dboffset; + if(invertedindex == true) { srcoffset[nsrcoffset++] = dboffset; } + dbfputs(srcfile); + fcnoffset = macrooffset = 0; } /* output the symbols and source line */ -static void -putcrossref(void) -{ - unsigned int i, j; - unsigned char c; - bool blank; /* blank indicator */ - unsigned int symput = 0; /* symbols output */ - int type; - - /* output the source line */ - lineoffset = dboffset; - dboffset += fprintf(newrefs, "%d ", lineno); +static void putcrossref(void) { + unsigned int i, j; + unsigned char c; + bool blank; /* blank indicator */ + unsigned int symput = 0; /* symbols output */ + int type; + + /* output the source line */ + lineoffset = dboffset; + dboffset += fprintf(newrefs, "%d ", lineno); #ifdef PRINTF_RETVAL_BROKEN - dboffset = ftell(newrefs); /* fprintf doesn't return chars written */ + dboffset = ftell(newrefs); /* fprintf doesn't return chars written */ #endif - /* HBB 20010425: added this line: */ - my_yytext[my_yyleng] = '\0'; - - blank = false; - for (i = 0; i < my_yyleng; ++i) { - - /* change a tab to a blank and compress blanks */ - if ((c = my_yytext[i]) == ' ' || c == '\t') { - blank = true; - } else if (symput < symbols && i == symbol[symput].first) { - /* look for the start of a symbol */ - - /* check for compressed blanks */ - if (blank == true) { - blank = false; - dbputc(' '); - } - dbputc('\n'); /* symbols start on a new line */ - - /* output any symbol type */ - if ((type = symbol[symput].type) != IDENT) { - dbputc('\t'); - dbputc(type); - } else { - type = ' '; - } - /* output the symbol */ - j = symbol[symput].last; - c = my_yytext[j]; - my_yytext[j] = '\0'; - if (invertedindex == true) { - putposting(my_yytext + i, type); - } - writestring(my_yytext + i); - dbputc('\n'); - my_yytext[j] = c; - i = j - 1; - ++symput; - } else { - /* HBB: try to save some time by early-out handling of - * non-compressed mode */ - if (compress == false) { - if (blank == true) { - dbputc(' '); - blank = false; - } - j = i + strcspn(my_yytext+i, "\t "); - if (symput < symbols - && j >= symbol[symput].first) - j = symbol[symput].first; - c = my_yytext[j]; - my_yytext[j] = '\0'; - writestring(my_yytext + i); - my_yytext[j] = c; - i = j - 1; - /* finished this 'i', continue with the blank */ - continue; - } - - /* check for compressed blanks */ - if (blank == true) { - if (dicode2[c]) { - c = DICODE_COMPRESS(' ', c); - } else { - dbputc(' '); - } - } else if (IS_A_DICODE(c, my_yytext[i + 1]) - && symput < symbols - && i + 1 != symbol[symput].first) { - /* compress digraphs */ - c = DICODE_COMPRESS(c, my_yytext[i + 1]); - ++i; - } - dbputc((int) c); - blank = false; - - /* skip compressed characters */ - if (c < ' ') { - ++i; - - /* skip blanks before a preprocesor keyword */ - /* note: don't use isspace() because \f and \v - are used for keywords */ - while ((j = my_yytext[i]) == ' ' || j == '\t') { - ++i; - } - /* skip the rest of the keyword */ - while (isalpha((unsigned char)my_yytext[i])) { - ++i; - } - /* skip space after certain keywords */ - if (keyword[c].delim != '\0') { - while ((j = my_yytext[i]) == ' ' || j == '\t') { - ++i; - } - } - /* skip a '(' after certain keywords */ - if (keyword[c].delim == '(' - && my_yytext[i] == '(') { - ++i; - } - --i; /* compensate for ++i in for() */ - } /* if compressed char */ - } /* else: not a symbol */ - } /* for(i) */ - - /* ignore trailing blanks */ - dbputc('\n'); - dbputc('\n'); - - /* output any #define end marker */ - /* note: must not be part of #define so putsource() doesn't discard it - so findcalledbysub() can find it and return */ - if (symput < symbols && symbol[symput].type == DEFINEEND) { - dbputc('\t'); - dbputc(DEFINEEND); - dbputc('\n'); - dbputc('\n'); /* mark beginning of next source line */ - macrooffset = 0; - } - symbols = 0; + /* HBB 20010425: added this line: */ + my_yytext[my_yyleng] = '\0'; + + blank = false; + for(i = 0; i < my_yyleng; ++i) { + + /* change a tab to a blank and compress blanks */ + if((c = my_yytext[i]) == ' ' || c == '\t') { + blank = true; + } else if(symput < symbols && i == symbol[symput].first) { + /* look for the start of a symbol */ + + /* check for compressed blanks */ + if(blank == true) { + blank = false; + dbputc(' '); + } + dbputc('\n'); /* symbols start on a new line */ + + /* output any symbol type */ + if((type = symbol[symput].type) != IDENT) { + dbputc('\t'); + dbputc(type); + } else { + type = ' '; + } + /* output the symbol */ + j = symbol[symput].last; + c = my_yytext[j]; + my_yytext[j] = '\0'; + if(invertedindex == true) { putposting(my_yytext + i, type); } + writestring(my_yytext + i); + dbputc('\n'); + my_yytext[j] = c; + i = j - 1; + ++symput; + } else { + /* HBB: try to save some time by early-out handling of + * non-compressed mode */ + if(compress == false) { + if(blank == true) { + dbputc(' '); + blank = false; + } + j = i + strcspn(my_yytext + i, "\t "); + if(symput < symbols && j >= symbol[symput].first) + j = symbol[symput].first; + c = my_yytext[j]; + my_yytext[j] = '\0'; + writestring(my_yytext + i); + my_yytext[j] = c; + i = j - 1; + /* finished this 'i', continue with the blank */ + continue; + } + + /* check for compressed blanks */ + if(blank == true) { + if(dicode2[c]) { + c = DICODE_COMPRESS(' ', c); + } else { + dbputc(' '); + } + } else if(IS_A_DICODE(c, my_yytext[i + 1]) && symput < symbols && + i + 1 != symbol[symput].first) { + /* compress digraphs */ + c = DICODE_COMPRESS(c, my_yytext[i + 1]); + ++i; + } + dbputc((int)c); + blank = false; + + /* skip compressed characters */ + if(c < ' ') { + ++i; + + /* skip blanks before a preprocesor keyword */ + /* note: don't use isspace() because \f and \v + are used for keywords */ + while((j = my_yytext[i]) == ' ' || j == '\t') { + ++i; + } + /* skip the rest of the keyword */ + while(isalpha((unsigned char)my_yytext[i])) { + ++i; + } + /* skip space after certain keywords */ + if(keyword[c].delim != '\0') { + while((j = my_yytext[i]) == ' ' || j == '\t') { + ++i; + } + } + /* skip a '(' after certain keywords */ + if(keyword[c].delim == '(' && my_yytext[i] == '(') { ++i; } + --i; /* compensate for ++i in for() */ + } /* if compressed char */ + } /* else: not a symbol */ + } /* for(i) */ + + /* ignore trailing blanks */ + dbputc('\n'); + dbputc('\n'); + + /* output any #define end marker */ + /* note: must not be part of #define so putsource() doesn't discard it + so findcalledbysub() can find it and return */ + if(symput < symbols && symbol[symput].type == DEFINEEND) { + dbputc('\t'); + dbputc(DEFINEEND); + dbputc('\n'); + dbputc('\n'); /* mark beginning of next source line */ + macrooffset = 0; + } + symbols = 0; } /* HBB 20000421: new function, for avoiding memory leaks */ /* free the cross reference symbol table */ -void -freecrossref() -{ - if (symbol) - free(symbol); - symbol = NULL; - symbols = 0; +void freecrossref() { + if(symbol) free(symbol); + symbol = NULL; + symbols = 0; } /* output the inverted index posting */ -void -putposting(char *term, int type) -{ - long i, n; - char *s; - int digits; /* digits output */ - long offset; /* function/macro database offset */ - char buf[11]; /* number buffer */ - - /* get the function or macro name offset */ - offset = fcnoffset; - if (macrooffset != 0) { - offset = macrooffset; - } - /* then update them to avoid negative relative name offset */ - switch (type) { - case DEFINE: - macrooffset = dboffset; - break; - case DEFINEEND: - macrooffset = 0; - return; /* null term */ - case FCNDEF: - fcnoffset = dboffset; - break; - case FCNEND: - fcnoffset = 0; - return; /* null term */ - } - /* ignore a null term caused by a enum/struct/union without a tag */ - if (*term == '\0') { - return; - } - /* skip any #include secondary type char (< or ") */ - if (type == INCLUDE) { - ++term; - } - /* output the posting, which should be as small as possible to reduce - the temp file size and sort time */ - (void) fputs(term, postings); - (void) putc(' ', postings); - - /* the line offset is padded so postings for the same term will sort - in ascending line offset order to order the references as they - appear withing a source file */ - ltobase(lineoffset); - for (i = PRECISION - digits; i > 0; --i) { - (void) putc('!', postings); - } - do { - (void) putc(*s, postings); - } while (*++s != '\0'); - - /* postings are also sorted by type */ - (void) putc(type, postings); - - /* function or macro name offset */ - if (offset > 0) { - (void) putc(' ', postings); - ltobase(offset); - do { - (void) putc(*s, postings); - } while (*++s != '\0'); - } - if (putc('\n', postings) == EOF) { - cannotwrite(temp1); - /* NOTREACHED */ - } - ++npostings; +void putposting(char *term, int type) { + long i, n; + char *s; + int digits; /* digits output */ + long offset; /* function/macro database offset */ + char buf[11]; /* number buffer */ + + /* get the function or macro name offset */ + offset = fcnoffset; + if(macrooffset != 0) { offset = macrooffset; } + /* then update them to avoid negative relative name offset */ + switch(type) { + case DEFINE: + macrooffset = dboffset; + break; + case DEFINEEND: + macrooffset = 0; + return; /* null term */ + case FCNDEF: + fcnoffset = dboffset; + break; + case FCNEND: + fcnoffset = 0; + return; /* null term */ + } + /* ignore a null term caused by a enum/struct/union without a tag */ + if(*term == '\0') { return; } + /* skip any #include secondary type char (< or ") */ + if(type == INCLUDE) { ++term; } + /* output the posting, which should be as small as possible to reduce + the temp file size and sort time */ + (void)fputs(term, postings); + (void)putc(' ', postings); + + /* the line offset is padded so postings for the same term will sort + in ascending line offset order to order the references as they + appear withing a source file */ + ltobase(lineoffset); + for(i = PRECISION - digits; i > 0; --i) { + (void)putc('!', postings); + } + do { + (void)putc(*s, postings); + } while(*++s != '\0'); + + /* postings are also sorted by type */ + (void)putc(type, postings); + + /* function or macro name offset */ + if(offset > 0) { + (void)putc(' ', postings); + ltobase(offset); + do { + (void)putc(*s, postings); + } while(*++s != '\0'); + } + if(putc('\n', postings) == EOF) { + cannotwrite(temp1); + /* NOTREACHED */ + } + ++npostings; } /* put the string into the new database */ -void -writestring(char *s) -{ - unsigned char c; - int i; - - if (compress == false) { - /* Save some I/O overhead by using puts() instead of putc(): */ - dbfputs(s); - return; - } - /* compress digraphs */ - for (i = 0; (c = s[i]) != '\0'; ++i) { - if (/* dicode1[c] && dicode2[(unsigned char) s[i + 1]] */ - IS_A_DICODE(c, s[i + 1])) { - /* c = (0200 - 2) + dicode1[c] + dicode2[(unsigned char) s[i + 1]]; */ - c = DICODE_COMPRESS(c, s[i + 1]); - ++i; - } - dbputc(c); - } +void writestring(char *s) { + unsigned char c; + int i; + + if(compress == false) { + /* Save some I/O overhead by using puts() instead of putc(): */ + dbfputs(s); + return; + } + /* compress digraphs */ + for(i = 0; (c = s[i]) != '\0'; ++i) { + if(/* dicode1[c] && dicode2[(unsigned char) s[i + 1]] */ + IS_A_DICODE(c, s[i + 1])) { + /* c = (0200 - 2) + dicode1[c] + dicode2[(unsigned char) s[i + 1]]; */ + c = DICODE_COMPRESS(c, s[i + 1]); + ++i; + } + dbputc(c); + } } /* print a warning message with the file name and line number */ -void -warning(char *text) -{ +void warning(char *text) { - (void) fprintf(stderr, PROGRAM_NAME ": \"%s\", line %d: warning: %s\n", filename, - myylineno, text); - errorsfound = true; + (void)fprintf(stderr, + PROGRAM_NAME ": \"%s\", line %d: warning: %s\n", + filename, + myylineno, + text); + errorsfound = true; } diff --git a/src/dir.c b/src/dir.c index 1c0e981..820c087 100644 --- a/src/dir.c +++ b/src/dir.c @@ -38,708 +38,654 @@ #include "global.h" -#include "vp.h" /* vpdirs and vpndirs */ +#include "vp.h" /* vpdirs and vpndirs */ #include -#include /* needed by stat.h and dirent.h */ +#include /* needed by stat.h and dirent.h */ #include -#include /* stat */ +#include /* stat */ #include -#define DIRSEPS " ,:" /* directory list separators */ -#define DIRINC 10 /* directory list size increment */ -#define HASHMOD 2003 /* must be a prime number */ -#define SRCINC HASHMOD /* source file list size increment */ - /* largest known database had 22049 files */ - -char currentdir[PATHLEN + 1];/* current directory */ -char **incdirs; /* #include directories */ -char **srcdirs; /* source directories */ -char **srcfiles; /* source files */ -unsigned long nincdirs; /* number of #include directories */ -unsigned long nsrcdirs; /* number of source directories */ -unsigned long nsrcfiles; /* number of source files */ -unsigned long msrcfiles = SRCINC; /* maximum number of source files */ - -static char **incnames; /* #include directory names without view pathing */ -static unsigned long mincdirs = DIRINC; /* maximum number of #include directories */ -static unsigned long msrcdirs; /* maximum number of source directories */ -static unsigned long nvpsrcdirs; /* number of view path source directories */ - -static struct listitem { /* source file names without view pathing */ - char *text; - struct listitem *next; +#define DIRSEPS " ,:" /* directory list separators */ +#define DIRINC 10 /* directory list size increment */ +#define HASHMOD 2003 /* must be a prime number */ +#define SRCINC HASHMOD /* source file list size increment */ + /* largest known database had 22049 files */ + +char currentdir[PATHLEN + 1]; /* current directory */ +char **incdirs; /* #include directories */ +char **srcdirs; /* source directories */ +char **srcfiles; /* source files */ +unsigned long nincdirs; /* number of #include directories */ +unsigned long nsrcdirs; /* number of source directories */ +unsigned long nsrcfiles; /* number of source files */ +unsigned long msrcfiles = SRCINC; /* maximum number of source files */ + +static char **incnames; /* #include directory names without view pathing */ +static unsigned long mincdirs = DIRINC; /* maximum number of #include directories */ +static unsigned long msrcdirs; /* maximum number of source directories */ +static unsigned long nvpsrcdirs; /* number of view path source directories */ + +static struct listitem { /* source file names without view pathing */ + char *text; + struct listitem *next; } *srcnames[HASHMOD]; /* Internal prototypes: */ -static bool accessible_file(char *file); -static bool issrcfile(char *file); -static void addsrcdir(char *dir); -static void addincdir(char *name, char *path); -static void scan_dir(const char *dirfile, bool recurse); -static void makevpsrcdirs(void); - +static bool accessible_file(char *file); +static bool issrcfile(char *file); +static void addsrcdir(char *dir); +static void addincdir(char *name, char *path); +static void scan_dir(const char *dirfile, bool recurse); +static void makevpsrcdirs(void); /* make the view source directory list */ -static void -makevpsrcdirs(void) -{ - int i; - - /* return if this function has already been called */ - if (nsrcdirs > 0) { - return; - } - /* get the current directory name */ - if (getcwd(currentdir, PATHLEN) == NULL) { - fprintf(stderr, PROGRAM_NAME ": warning: cannot get current directory name\n"); - strcpy(currentdir, ""); - } - /* see if there is a view path and this directory is in it */ - vpinit(currentdir); - if (vpndirs > 1) { - nsrcdirs = vpndirs; - } else { - nsrcdirs = 1; - } - /* create the source directory list */ - msrcdirs = nsrcdirs + DIRINC; - srcdirs = malloc(msrcdirs * sizeof(*srcdirs)); - *srcdirs = "."; /* first source dir is always current dir */ - for (i = 1; i < vpndirs; ++i) { - srcdirs[i] = vpdirs[i]; - } - /* save the number of original source directories in the view path */ - nvpsrcdirs = nsrcdirs; +static void makevpsrcdirs(void) { + int i; + + /* return if this function has already been called */ + if(nsrcdirs > 0) { return; } + /* get the current directory name */ + if(getcwd(currentdir, PATHLEN) == NULL) { + fprintf(stderr, PROGRAM_NAME ": warning: cannot get current directory name\n"); + strcpy(currentdir, ""); + } + /* see if there is a view path and this directory is in it */ + vpinit(currentdir); + if(vpndirs > 1) { + nsrcdirs = vpndirs; + } else { + nsrcdirs = 1; + } + /* create the source directory list */ + msrcdirs = nsrcdirs + DIRINC; + srcdirs = malloc(msrcdirs * sizeof(*srcdirs)); + *srcdirs = "."; /* first source dir is always current dir */ + for(i = 1; i < vpndirs; ++i) { + srcdirs[i] = vpdirs[i]; + } + /* save the number of original source directories in the view path */ + nvpsrcdirs = nsrcdirs; } /* add a source directory to the list for each view path source directory */ -void -sourcedir(char *dirlist) -{ - char path[PATHLEN + 1]; - char *dir; - unsigned int i; - - makevpsrcdirs(); /* make the view source directory list */ - dirlist = strdup(dirlist); /* don't change environment variable text */ - - /* parse the directory list */ - dir = strtok(dirlist, DIRSEPS); - while (dir != NULL) { - int dir_len = strlen(dir); - - addsrcdir(dir); - - /* if it isn't a full path name and there is a - multi-directory view path */ - if (*dirlist != '/' && vpndirs > 1) { - - /* compute its path from higher view path source dirs */ - for (i = 1; i < nvpsrcdirs; ++i) { - snprintf(path, sizeof(path), "%.*s/%s", - PATHLEN - 2 - dir_len, - srcdirs[i], dir); - addsrcdir(path); - } - } - dir = strtok(NULL, DIRSEPS); - } - free(dirlist); /* HBB 20000421: avoid memory leaks */ +void sourcedir(char *dirlist) { + char path[PATHLEN + 1]; + char *dir; + unsigned int i; + + makevpsrcdirs(); /* make the view source directory list */ + dirlist = strdup(dirlist); /* don't change environment variable text */ + + /* parse the directory list */ + dir = strtok(dirlist, DIRSEPS); + while(dir != NULL) { + int dir_len = strlen(dir); + + addsrcdir(dir); + + /* if it isn't a full path name and there is a + multi-directory view path */ + if(*dirlist != '/' && vpndirs > 1) { + + /* compute its path from higher view path source dirs */ + for(i = 1; i < nvpsrcdirs; ++i) { + snprintf(path, + sizeof(path), + "%.*s/%s", + PATHLEN - 2 - dir_len, + srcdirs[i], + dir); + addsrcdir(path); + } + } + dir = strtok(NULL, DIRSEPS); + } + free(dirlist); /* HBB 20000421: avoid memory leaks */ } /* add a source directory to the list */ -static void -addsrcdir(char *dir) -{ - struct stat statstruct; - - /* make sure it is a directory */ - if (lstat(compath(dir), &statstruct) == 0 && - S_ISDIR(statstruct.st_mode)) { - - /* note: there already is a source directory list */ - if (nsrcdirs == msrcdirs) { - msrcdirs += DIRINC; - srcdirs = realloc(srcdirs, msrcdirs * sizeof(*srcdirs)); - } - srcdirs[nsrcdirs++] = strdup(dir); - } +static void addsrcdir(char *dir) { + struct stat statstruct; + + /* make sure it is a directory */ + if(lstat(compath(dir), &statstruct) == 0 && S_ISDIR(statstruct.st_mode)) { + + /* note: there already is a source directory list */ + if(nsrcdirs == msrcdirs) { + msrcdirs += DIRINC; + srcdirs = realloc(srcdirs, msrcdirs * sizeof(*srcdirs)); + } + srcdirs[nsrcdirs++] = strdup(dir); + } } /* HBB 20000421: new function, for avoiding leaks */ /* free list of src directories */ -void -freesrclist() -{ - if (!srcdirs) - return; - while(nsrcdirs>1) - free(srcdirs[--nsrcdirs]); - free(srcdirs); +void freesrclist() { + if(!srcdirs) return; + while(nsrcdirs > 1) + free(srcdirs[--nsrcdirs]); + free(srcdirs); } /* add a #include directory to the list for each view path source directory */ -void -includedir(char *dirlist) -{ - char path[PATHLEN + 1]; - char *dir; - unsigned int i; - - makevpsrcdirs(); /* make the view source directory list */ - dirlist = strdup(dirlist); /* don't change environment variable text */ - - /* parse the directory list */ - dir = strtok(dirlist, DIRSEPS); - while (dir != NULL) { - size_t dir_len = strlen(dir); - - addincdir(dir, dir); - - /* if it isn't a full path name and there is a - multi-directory view path */ - if (*dirlist != '/' && vpndirs > 1) { - - /* compute its path from higher view path source dirs */ - for (i = 1; i < nvpsrcdirs; ++i) { - snprintf(path, sizeof(path), "%.*s/%s", - (int)(PATHLEN - 2 - dir_len), - srcdirs[i], dir); - addincdir(dir, path); - } - } - dir = strtok(NULL, DIRSEPS); - } - free(dirlist); /* HBB 20000421: avoid leaks */ +void includedir(char *dirlist) { + char path[PATHLEN + 1]; + char *dir; + unsigned int i; + + makevpsrcdirs(); /* make the view source directory list */ + dirlist = strdup(dirlist); /* don't change environment variable text */ + + /* parse the directory list */ + dir = strtok(dirlist, DIRSEPS); + while(dir != NULL) { + size_t dir_len = strlen(dir); + + addincdir(dir, dir); + + /* if it isn't a full path name and there is a + multi-directory view path */ + if(*dirlist != '/' && vpndirs > 1) { + + /* compute its path from higher view path source dirs */ + for(i = 1; i < nvpsrcdirs; ++i) { + snprintf(path, + sizeof(path), + "%.*s/%s", + (int)(PATHLEN - 2 - dir_len), + srcdirs[i], + dir); + addincdir(dir, path); + } + } + dir = strtok(NULL, DIRSEPS); + } + free(dirlist); /* HBB 20000421: avoid leaks */ } /* add a #include directory to the list */ -static void -addincdir(char *name, char *path) -{ - struct stat statstruct; - - /* make sure it is a directory */ - if (lstat(compath(path), &statstruct) == 0 && - S_ISDIR(statstruct.st_mode)) { - if (incdirs == NULL) { - incdirs = malloc(mincdirs * sizeof(*incdirs)); - incnames = malloc(mincdirs * sizeof(*incnames)); - } else if (nincdirs == mincdirs) { - mincdirs += DIRINC; - incdirs = realloc(incdirs, mincdirs * sizeof(*incdirs)); - incnames = realloc(incnames, mincdirs * sizeof(*incnames)); - } - incdirs[nincdirs] = strdup(path); - incnames[nincdirs++] = strdup(name); - } +static void addincdir(char *name, char *path) { + struct stat statstruct; + + /* make sure it is a directory */ + if(lstat(compath(path), &statstruct) == 0 && S_ISDIR(statstruct.st_mode)) { + if(incdirs == NULL) { + incdirs = malloc(mincdirs * sizeof(*incdirs)); + incnames = malloc(mincdirs * sizeof(*incnames)); + } else if(nincdirs == mincdirs) { + mincdirs += DIRINC; + incdirs = realloc(incdirs, mincdirs * sizeof(*incdirs)); + incnames = realloc(incnames, mincdirs * sizeof(*incnames)); + } + incdirs[nincdirs] = strdup(path); + incnames[nincdirs++] = strdup(name); + } } /* HBB 2000421: new function, for avoiding memory leaks */ /* free the list of include files, if wanted */ -void -freeinclist() -{ - if (!incdirs) - return; - while(nincdirs>0) { - free(incdirs[--nincdirs]); - free(incnames[nincdirs]); - } - free(incdirs); - free(incnames); +void freeinclist() { + if(!incdirs) return; + while(nincdirs > 0) { + free(incdirs[--nincdirs]); + free(incnames[nincdirs]); + } + free(incdirs); + free(incnames); } /* make the source file list */ -void -makefilelist(void) -{ - static bool firstbuild = true; /* first time through */ - FILE *names; /* name file pointer */ - char dir[PATHLEN + 1]; - char path[PATHLEN + 1]; - char line[PATHLEN * 10]; - char *file; - char *s; - unsigned int i; - - makevpsrcdirs(); /* make the view source directory list */ - - /* if -i was falseT given and there are source file arguments */ - if (namefile == NULL && fileargc > 0) { - - /* put them in a list that can be expanded */ - for (i = 0; i < fileargc; ++i) { - file = fileargv[i]; - if (infilelist(file) == false) { - if ((s = inviewpath(file)) != NULL) { - addsrcfile(s); - } else { - fprintf(stderr, PROGRAM_NAME ": cannot find file %s\n", - file); - errorsfound = true; - } - } - } - return; - } - - /* see if a file name file exists */ - if (namefile == NULL && vpaccess(NAMEFILE, READ) == 0) { - namefile = NAMEFILE; - } - - if (namefile == NULL) { - /* No namefile --> make a list of all the source files - * in the directories */ - for (i = 0; i < nsrcdirs; ++i) { - scan_dir(srcdirs[i], recurse_dir); - } - return; - } - - /* Came here --> there is a file of source file names */ - - if (strcmp(namefile, "-") == 0) - names = stdin; - else if ((names = vpfopen(namefile, "r")) == NULL) { - cannotopen(namefile); - myexit(1); - } - - /* get the names in the file */ - while (fgets(line, 10*PATHLEN, names) != NULL) { - char *point_in_line = line + (strlen(line) - 1); - size_t length_of_name = 0; - int unfinished_option = 0; - bool done = false; - - /* Kill away \n left at end of fgets()'d string: */ - if (*point_in_line == '\n') - *point_in_line = '\0'; - - /* Parse whitespace-terminated strings in line: */ - point_in_line = line; - while (sscanf(point_in_line, "%" PATHLEN_STR "s", path) == 1) { - /* Have to store this length --- inviewpath() will - * modify path, later! */ - length_of_name = strlen(path); - - if (*path == '-') { /* if an option */ - if (unfinished_option) { - /* Can't have another option directly after an - * -I or -p option with no name after it! */ - fprintf(stderr, PROGRAM_NAME ": Syntax error in namelist file %s: unfinished -I or -p option\n", - namefile); - unfinished_option = 0; - } - - i = path[1]; - switch (i) { - case 'c': /* ASCII characters only in crossref */ - compress = false; - break; - case 'k': /* ignore DFLT_INCDIR */ - kernelmode = true; - break; - case 'q': /* quick search */ - invertedindex = true; - break; - case 'T': /* truncate symbols to 8 characters */ - trun_syms = true; - break; - case 'I': /* #include file directory */ - case 'p': /* file path components to display */ - /* coverity[overwrite_var] */ - s = path + 2; /* for "-Ipath" */ - if (*s == '\0') { /* if "-I path" */ - unfinished_option = i; - break; - } - - /* this code block used several times in here - * --> make it a macro to avoid unnecessary - * duplication */ -#define HANDLE_OPTION_ARGUMENT(i, s) \ - switch (i) { \ - case 'I': /* #include file directory */ \ - if (firstbuild == true) { \ - /* expand $ and ~ */ \ - shellpath(dir, sizeof(dir), (s)); \ - includedir(dir); \ - } \ - unfinished_option = 0; \ - done = true; \ - break; \ - case 'p': /* file path components to display */ \ - if (*(s) < '0' || *(s) > '9') { \ - fprintf(stderr, "csope: -p option in file %s: missing or invalid numeric value\n", \ - namefile); \ - } \ - dispcomponents = atoi(s); \ - unfinished_option = 0; \ - done = true; \ - break; \ - default: \ - done = false; \ - } /* switch(i) */ - - /* ... and now call it for the first time */ - HANDLE_OPTION_ARGUMENT(i, s) - break; - default: - fprintf(stderr, PROGRAM_NAME ": only -I, -c, -k, -p, and -T options can be in file %s\n", - namefile); - } /* switch(i) */ - } /* if('-') */ - else if (*path == '"') { - /* handle quoted filenames... */ - size_t in = 1, out = 0; - char *newpath = malloc(PATHLEN + 1); - - while (in < PATHLEN && point_in_line[in] != '\0') { - if (point_in_line[in] == '"') { - newpath[out] = '\0'; - /* Tell outer loop to skip over this entire - * quoted string */ - length_of_name = in + 1; - break; /* found end of quoted string */ - } else if (point_in_line[in] == '\\' - && in < PATHLEN - 1 - && (point_in_line[in + 1]== '"' - || point_in_line[in + 1] == '\\')) { - /* un-escape \" or \\ sequence */ - newpath[out++] = point_in_line[in + 1]; - in += 2; - } else { - newpath[out++] = point_in_line[in++]; - } - } /* while(in) */ - if (in >= PATHLEN) { /* safeguard against almost-overflow */ - newpath[out]='\0'; - } - - /* If an -I or -p arguments was missing before, - * treat this name as the argument: */ - HANDLE_OPTION_ARGUMENT(unfinished_option, newpath); - if (! done) { - /* coverity[overwrite_var] */ - if ((s = inviewpath(newpath)) != NULL) { - addsrcfile(s); - } else { - fprintf(stderr, PROGRAM_NAME, ": cannot find file %s\n", - newpath); - errorsfound = true; - } - } - free(newpath); - } /* if(quoted name) */ - else { - /* ... so this is an ordinary file name, unquoted */ - - /* If an -I or -p arguments was missing before, - * treat this name as the argument: */ - HANDLE_OPTION_ARGUMENT(unfinished_option, path); - if (!done) { - if ((s = inviewpath(path)) != NULL) { - addsrcfile(s); - } else { - fprintf(stderr, PROGRAM_NAME ": cannot find file %s\n", - path); - errorsfound = true; - } - } - } /* else(ordinary name) */ - - point_in_line += length_of_name; - while (isspace((unsigned char) *point_in_line)) - point_in_line ++; - } /* while(sscanf(line)) */ - } /* while(fgets(line)) */ - - if (names == stdin) - clearerr(stdin); - else - fclose(names); - firstbuild = false; - return; - +void makefilelist(void) { + static bool firstbuild = true; /* first time through */ + FILE *names; /* name file pointer */ + char dir[PATHLEN + 1]; + char path[PATHLEN + 1]; + char line[PATHLEN * 10]; + char *file; + char *s; + unsigned int i; + + makevpsrcdirs(); /* make the view source directory list */ + + /* if -i was falseT given and there are source file arguments */ + if(namefile == NULL && fileargc > 0) { + + /* put them in a list that can be expanded */ + for(i = 0; i < fileargc; ++i) { + file = fileargv[i]; + if(infilelist(file) == false) { + if((s = inviewpath(file)) != NULL) { + addsrcfile(s); + } else { + fprintf(stderr, PROGRAM_NAME ": cannot find file %s\n", file); + errorsfound = true; + } + } + } + return; + } + + /* see if a file name file exists */ + if(namefile == NULL && vpaccess(NAMEFILE, READ) == 0) { namefile = NAMEFILE; } + + if(namefile == NULL) { + /* No namefile --> make a list of all the source files + * in the directories */ + for(i = 0; i < nsrcdirs; ++i) { + scan_dir(srcdirs[i], recurse_dir); + } + return; + } + + /* Came here --> there is a file of source file names */ + + if(strcmp(namefile, "-") == 0) + names = stdin; + else if((names = vpfopen(namefile, "r")) == NULL) { + cannotopen(namefile); + myexit(1); + } + + /* get the names in the file */ + while(fgets(line, 10 * PATHLEN, names) != NULL) { + char *point_in_line = line + (strlen(line) - 1); + size_t length_of_name = 0; + int unfinished_option = 0; + bool done = false; + + /* Kill away \n left at end of fgets()'d string: */ + if(*point_in_line == '\n') *point_in_line = '\0'; + + /* Parse whitespace-terminated strings in line: */ + point_in_line = line; + while(sscanf(point_in_line, "%" PATHLEN_STR "s", path) == 1) { + /* Have to store this length --- inviewpath() will + * modify path, later! */ + length_of_name = strlen(path); + + if(*path == '-') { /* if an option */ + if(unfinished_option) { + /* Can't have another option directly after an + * -I or -p option with no name after it! */ + fprintf(stderr, + PROGRAM_NAME + ": Syntax error in namelist file %s: unfinished -I or -p option\n", + namefile); + unfinished_option = 0; + } + + i = path[1]; + switch(i) { + case 'c': /* ASCII characters only in crossref */ + compress = false; + break; + case 'k': /* ignore DFLT_INCDIR */ + kernelmode = true; + break; + case 'q': /* quick search */ + invertedindex = true; + break; + case 'T': /* truncate symbols to 8 characters */ + trun_syms = true; + break; + case 'I': /* #include file directory */ + case 'p': /* file path components to display */ + /* coverity[overwrite_var] */ + s = path + 2; /* for "-Ipath" */ + if(*s == '\0') { /* if "-I path" */ + unfinished_option = i; + break; + } + + /* this code block used several times in here + * --> make it a macro to avoid unnecessary + * duplication */ +#define HANDLE_OPTION_ARGUMENT(i, s) \ + switch(i) { \ + case 'I': /* #include file directory */ \ + if(firstbuild == true) { \ + /* expand $ and ~ */ \ + shellpath(dir, sizeof(dir), (s)); \ + includedir(dir); \ + } \ + unfinished_option = 0; \ + done = true; \ + break; \ + case 'p': /* file path components to display */ \ + if(*(s) < '0' || *(s) > '9') { \ + fprintf(stderr, \ + "csope: -p option in file %s: missing or invalid numeric value\n", \ + namefile); \ + } \ + dispcomponents = atoi(s); \ + unfinished_option = 0; \ + done = true; \ + break; \ + default: \ + done = false; \ + } /* switch(i) */ + + /* ... and now call it for the first time */ + HANDLE_OPTION_ARGUMENT(i, s) + break; + default: + fprintf(stderr, + PROGRAM_NAME + ": only -I, -c, -k, -p, and -T options can be in file %s\n", + namefile); + } /* switch(i) */ + } /* if('-') */ + else if(*path == '"') { + /* handle quoted filenames... */ + size_t in = 1, out = 0; + char *newpath = malloc(PATHLEN + 1); + + while(in < PATHLEN && point_in_line[in] != '\0') { + if(point_in_line[in] == '"') { + newpath[out] = '\0'; + /* Tell outer loop to skip over this entire + * quoted string */ + length_of_name = in + 1; + break; /* found end of quoted string */ + } else if(point_in_line[in] == '\\' && in < PATHLEN - 1 && + (point_in_line[in + 1] == '"' || + point_in_line[in + 1] == '\\')) { + /* un-escape \" or \\ sequence */ + newpath[out++] = point_in_line[in + 1]; + in += 2; + } else { + newpath[out++] = point_in_line[in++]; + } + } /* while(in) */ + if(in >= PATHLEN) { /* safeguard against almost-overflow */ + newpath[out] = '\0'; + } + + /* If an -I or -p arguments was missing before, + * treat this name as the argument: */ + HANDLE_OPTION_ARGUMENT(unfinished_option, newpath); + if(!done) { + /* coverity[overwrite_var] */ + if((s = inviewpath(newpath)) != NULL) { + addsrcfile(s); + } else { + fprintf(stderr, PROGRAM_NAME, ": cannot find file %s\n", newpath); + errorsfound = true; + } + } + free(newpath); + } /* if(quoted name) */ + else { + /* ... so this is an ordinary file name, unquoted */ + + /* If an -I or -p arguments was missing before, + * treat this name as the argument: */ + HANDLE_OPTION_ARGUMENT(unfinished_option, path); + if(!done) { + if((s = inviewpath(path)) != NULL) { + addsrcfile(s); + } else { + fprintf(stderr, PROGRAM_NAME ": cannot find file %s\n", path); + errorsfound = true; + } + } + } /* else(ordinary name) */ + + point_in_line += length_of_name; + while(isspace((unsigned char)*point_in_line)) + point_in_line++; + } /* while(sscanf(line)) */ + } /* while(fgets(line)) */ + + if(names == stdin) + clearerr(stdin); + else + fclose(names); + firstbuild = false; + return; } /* scan a directory (recursively?) for source files */ -static void -scan_dir(const char *adir, bool recurse_dir) -{ - DIR *dirfile; - int adir_len = strlen(adir); - - /* FIXME: no guards against adir_len > PATHLEN, yet */ - - if ((dirfile = opendir(adir)) != NULL) { - struct dirent *entry; - char path[PATHLEN + 1]; - - while ((entry = readdir(dirfile)) != NULL) { - if ((strcmp(".",entry->d_name) != 0) - && (strcmp("..",entry->d_name) != 0)) { - struct stat buf; - - snprintf(path, sizeof(path), "%s/%.*s", adir, - PATHLEN - 2 - adir_len, - entry->d_name); - - if (lstat(path,&buf) == 0) { - if (recurse_dir - && S_ISDIR(buf.st_mode) ) { - scan_dir(path, recurse_dir); - } else if (issrcfile(path) - && infilelist(path) == false - && access(path, R_OK) == 0) { - addsrcfile(path); - } - } - } - } - closedir(dirfile); - } - return; +static void scan_dir(const char *adir, bool recurse_dir) { + DIR *dirfile; + int adir_len = strlen(adir); + + /* FIXME: no guards against adir_len > PATHLEN, yet */ + + if((dirfile = opendir(adir)) != NULL) { + struct dirent *entry; + char path[PATHLEN + 1]; + + while((entry = readdir(dirfile)) != NULL) { + if((strcmp(".", entry->d_name) != 0) && (strcmp("..", entry->d_name) != 0)) { + struct stat buf; + + snprintf(path, + sizeof(path), + "%s/%.*s", + adir, + PATHLEN - 2 - adir_len, + entry->d_name); + + if(lstat(path, &buf) == 0) { + if(recurse_dir && S_ISDIR(buf.st_mode)) { + scan_dir(path, recurse_dir); + } else if(issrcfile(path) && infilelist(path) == false && + access(path, R_OK) == 0) { + addsrcfile(path); + } + } + } + } + closedir(dirfile); + } + return; } - /* see if this is a source file */ -static bool -issrcfile(char *path) -{ - struct stat statstruct; - char *file = basename(path); - char *s = strrchr(file, '.'); - bool looks_like_source = false; - - /* ensure there is some file suffix */ - if (s == NULL || *++s == '\0') - return false; - - /* if an SCCS or versioned file */ - if (file[1] == '.' && file + 2 != s) { /* 1 character prefix */ - switch (*file) { - case 's': - case 'S': - return(false); - } - } - - if (s[1] == '\0') { /* 1 character suffix */ - switch (*s) { - case 'c': - case 'h': - case 'l': - case 'y': - case 'C': - case 'G': - case 'H': - case 'L': - looks_like_source = true; - } - } else if ((s[2] == '\0') /* 2 char suffix */ - && ((s[0] == 'b' && s[1] == 'p') /* breakpoint listing */ - || (s[0] == 'q' - && (s[1] == 'c' || s[1] == 'h')) /* Ingres */ - || (s[0] == 's' && s[1] == 'd') /* SDL */ - || (s[0] == 'c' && s[1] == 'c') /* C++ source */ - || (s[0] == 'h' && s[1] == 'h'))) { /* C++ header */ - looks_like_source = true; - - } else if((s[3] == '\0') /* 3 char suffix */ - /* C++ template source */ - && ((s[0] == 't' && s[1] == 'c' && s[2] == 'c' ) - /* C++ source: */ - || (s[0] == 'c' && s[1] == 'p' && s[2] == 'p' ) - || (s[0] == 'c' && s[1] == 'x' && s[2] == 'x' ) - || (s[0] == 'h' && s[1] == 'p' && s[2] == 'p' ) - || (s[0] == 'h' && s[1] == 'x' && s[2] == 'x' )) - ) { - looks_like_source = true; - } - - if (looks_like_source != true) - return false; - - /* make sure it is a file */ - if (lstat(path, &statstruct) == 0 && - S_ISREG(statstruct.st_mode)) { - return(true); - } - return false; +static bool issrcfile(char *path) { + struct stat statstruct; + char *file = basename(path); + char *s = strrchr(file, '.'); + bool looks_like_source = false; + + /* ensure there is some file suffix */ + if(s == NULL || *++s == '\0') return false; + + /* if an SCCS or versioned file */ + if(file[1] == '.' && file + 2 != s) { /* 1 character prefix */ + switch(*file) { + case 's': + case 'S': + return (false); + } + } + + if(s[1] == '\0') { /* 1 character suffix */ + switch(*s) { + case 'c': + case 'h': + case 'l': + case 'y': + case 'C': + case 'G': + case 'H': + case 'L': + looks_like_source = true; + } + } else if((s[2] == '\0') /* 2 char suffix */ + && ((s[0] == 'b' && s[1] == 'p') /* breakpoint listing */ + || (s[0] == 'q' && (s[1] == 'c' || s[1] == 'h')) /* Ingres */ + || (s[0] == 's' && s[1] == 'd') /* SDL */ + || (s[0] == 'c' && s[1] == 'c') /* C++ source */ + || (s[0] == 'h' && s[1] == 'h'))) { /* C++ header */ + looks_like_source = true; + + } else if((s[3] == '\0') /* 3 char suffix */ + /* C++ template source */ + && ((s[0] == 't' && s[1] == 'c' && s[2] == 'c') + /* C++ source: */ + || (s[0] == 'c' && s[1] == 'p' && s[2] == 'p') || + (s[0] == 'c' && s[1] == 'x' && s[2] == 'x') || + (s[0] == 'h' && s[1] == 'p' && s[2] == 'p') || + (s[0] == 'h' && s[1] == 'x' && s[2] == 'x'))) { + looks_like_source = true; + } + + if(looks_like_source != true) return false; + + /* make sure it is a file */ + if(lstat(path, &statstruct) == 0 && S_ISREG(statstruct.st_mode)) { return (true); } + return false; } - /* add an include file to the source file list */ -void -incfile(char *file, char *type) -{ - char name[PATHLEN + 1]; - char path[PATHLEN + 1]; - char *s; - unsigned int i; - - assert(file != NULL); /* should never happen, but let's make sure anyway */ - /* see if the file is already in the source file list */ - if (infilelist(file) == true) { - return; - } - /* look in current directory if it was #include "file" */ - if (type[0] == '"' && (s = inviewpath(file)) != NULL) { - addsrcfile(s); - } else { - size_t file_len = strlen(file); - - /* search for the file in the #include directory list */ - for (i = 0; i < nincdirs; ++i) { - /* don't include the file from two directories */ - snprintf(name, sizeof(name), "%.*s/%s", - (int)(PATHLEN - 2 - file_len), incnames[i], - file); - if (infilelist(name) == true) { - break; - } - /* make sure it exists and is readable */ - snprintf(path, sizeof(path), "%.*s/%s", - (int)(PATHLEN - 2 - file_len), incdirs[i], - file); - if (access(compath(path), READ) == 0) { - addsrcfile(path); - break; - } - } - } +void incfile(char *file, char *type) { + char name[PATHLEN + 1]; + char path[PATHLEN + 1]; + char *s; + unsigned int i; + + assert(file != NULL); /* should never happen, but let's make sure anyway */ + /* see if the file is already in the source file list */ + if(infilelist(file) == true) { return; } + /* look in current directory if it was #include "file" */ + if(type[0] == '"' && (s = inviewpath(file)) != NULL) { + addsrcfile(s); + } else { + size_t file_len = strlen(file); + + /* search for the file in the #include directory list */ + for(i = 0; i < nincdirs; ++i) { + /* don't include the file from two directories */ + snprintf(name, + sizeof(name), + "%.*s/%s", + (int)(PATHLEN - 2 - file_len), + incnames[i], + file); + if(infilelist(name) == true) { break; } + /* make sure it exists and is readable */ + snprintf(path, + sizeof(path), + "%.*s/%s", + (int)(PATHLEN - 2 - file_len), + incdirs[i], + file); + if(access(compath(path), READ) == 0) { + addsrcfile(path); + break; + } + } + } } - /* see if the file is already in the list */ -bool -infilelist(char *path) -{ - struct listitem *p; - - for (p = srcnames[hash(compath(path)) % HASHMOD]; - p != NULL; - p = p->next) { - if (strequal(path, p->text)) { - return(true); - } - } - return(false); -} +bool infilelist(char *path) { + struct listitem *p; + for(p = srcnames[hash(compath(path)) % HASHMOD]; p != NULL; p = p->next) { + if(strequal(path, p->text)) { return (true); } + } + return (false); +} /* check if a file is readable enough to be allowed in the * database */ -static bool -accessible_file(char *file) -{ - if (access(compath(file), READ) == 0) { - struct stat stats; - - if (lstat(file, &stats) == 0 - && S_ISREG(stats.st_mode)) { - return true; - } - } - return false; +static bool accessible_file(char *file) { + if(access(compath(file), READ) == 0) { + struct stat stats; + + if(lstat(file, &stats) == 0 && S_ISREG(stats.st_mode)) { return true; } + } + return false; } /* search for the file in the view path */ -char * -inviewpath(char *file) -{ - static char path[PATHLEN + 1]; - unsigned int i; - - /* look for the file */ - if (accessible_file(file)) { - return(file); - } - - /* if it isn't a full path name and there is a multi-directory - * view path */ - if (*file != '/' && vpndirs > 1) { - int file_len = strlen(file); - - /* compute its path from higher view path source dirs */ - for (i = 1; i < nvpsrcdirs; ++i) { - snprintf(path, sizeof(path), "%.*s/%s", - PATHLEN - 2 - file_len, srcdirs[i], - file); - if (accessible_file(path)) { - return(path); - } - } - } - return(NULL); +char *inviewpath(char *file) { + static char path[PATHLEN + 1]; + unsigned int i; + + /* look for the file */ + if(accessible_file(file)) { return (file); } + + /* if it isn't a full path name and there is a multi-directory + * view path */ + if(*file != '/' && vpndirs > 1) { + int file_len = strlen(file); + + /* compute its path from higher view path source dirs */ + for(i = 1; i < nvpsrcdirs; ++i) { + snprintf(path, + sizeof(path), + "%.*s/%s", + PATHLEN - 2 - file_len, + srcdirs[i], + file); + if(accessible_file(path)) { return (path); } + } + } + return (NULL); } /* add a source file to the list */ -void -addsrcfile(char *path) -{ - struct listitem *p; - int i; - - /* make sure there is room for the file */ - if (nsrcfiles == msrcfiles) { - msrcfiles += SRCINC; - srcfiles = realloc(srcfiles, msrcfiles * sizeof(*srcfiles)); - } - /* add the file to the list */ - srcfiles[nsrcfiles++] = strdup(compath(path)); - p = malloc(sizeof(*p)); - p->text = strdup(compath(path)); - i = hash(p->text) % HASHMOD; - p->next = srcnames[i]; - srcnames[i] = p; +void addsrcfile(char *path) { + struct listitem *p; + int i; + + /* make sure there is room for the file */ + if(nsrcfiles == msrcfiles) { + msrcfiles += SRCINC; + srcfiles = realloc(srcfiles, msrcfiles * sizeof(*srcfiles)); + } + /* add the file to the list */ + srcfiles[nsrcfiles++] = strdup(compath(path)); + p = malloc(sizeof(*p)); + p->text = strdup(compath(path)); + i = hash(p->text) % HASHMOD; + p->next = srcnames[i]; + srcnames[i] = p; } /* free the memory allocated for the source file list */ -void -freefilelist(void) -{ - struct listitem *p, *nextp; - int i; - - /* if '-d' option is used a string space block is allocated */ - if (isuptodate == false) { - while (nsrcfiles > 0) { - free (srcfiles[--nsrcfiles]); - } - } else { - /* for '-d' option free the string space block */ - /* protect against empty list */ - if (nsrcfiles > 0) - free (srcfiles[0]); - nsrcfiles = 0; - } - - free (srcfiles); /* HBB 20000421: avoid leak */ - msrcfiles = 0; - srcfiles=0; - - for (i = 0; i < HASHMOD; ++i) { - for (p = srcnames[i]; p != NULL; p = nextp) { - /* HBB 20000421: avoid memory leak */ - free(p->text); - nextp = p->next; - free(p); - } - srcnames[i] = NULL; - } +void freefilelist(void) { + struct listitem *p, *nextp; + int i; + + /* if '-d' option is used a string space block is allocated */ + if(isuptodate == false) { + while(nsrcfiles > 0) { + free(srcfiles[--nsrcfiles]); + } + } else { + /* for '-d' option free the string space block */ + /* protect against empty list */ + if(nsrcfiles > 0) free(srcfiles[0]); + nsrcfiles = 0; + } + + free(srcfiles); /* HBB 20000421: avoid leak */ + msrcfiles = 0; + srcfiles = 0; + + for(i = 0; i < HASHMOD; ++i) { + for(p = srcnames[i]; p != NULL; p = nextp) { + /* HBB 20000421: avoid memory leak */ + free(p->text); + nextp = p->next; + free(p); + } + srcnames[i] = NULL; + } } diff --git a/src/display.c b/src/display.c index 78c2654..8f11e1f 100644 --- a/src/display.c +++ b/src/display.c @@ -40,48 +40,46 @@ #include "colors.h" #ifdef CCS -#include "sgs.h" /* ESG_PKG and ESG_REL */ +# include "sgs.h" /* ESG_PKG and ESG_REL */ #else -#include "version.h" /* FILEVERSION and FIXVERSION */ +# include "version.h" /* FILEVERSION and FIXVERSION */ #endif #include -#include /* va_list stuff */ +#include /* va_list stuff */ #include #include #include /* XXX */ -#define MSGLINE 0 /* message line */ -#define MSGCOL 0 /* message column */ - -int subsystemlen = sizeof("Subsystem")-1; /* OGS subsystem name display field length */ -int booklen = sizeof("Book")-1; /* OGS book name display field length */ -int filelen = sizeof("File")-1; /* file name display field length */ -int fcnlen = sizeof("Function")-1; /* function name display field length */ -int numlen = 0; /* line number display field length */ - -int *displine; /* screen line of displayed reference */ -unsigned int disprefs; /* displayed references */ -int field; /* input field */ -unsigned int mdisprefs; /* maximum displayed references */ -unsigned int nextline; /* next line to be shown */ -static int bottomline; /* bottom line of page */ -long searchcount; /* count of files searched */ -unsigned int totallines; /* total reference lines */ -unsigned int curdispline = 0; -int current_page = 0; -int input_mode = INPUT_NORMAL; -const char* prompts[] = { - [INPUT_NORMAL] = "$ ", - [INPUT_APPEND] = "Append to file: ", - [INPUT_PIPE] = "Pipe to shell command: ", - [INPUT_READ] = "Read from file: ", - [INPUT_CHANGE_TO] = "To: ", - [INPUT_CHANGE] = "To: " -}; - -unsigned int topline = 1; /* top line of page */ +#define MSGLINE 0 /* message line */ +#define MSGCOL 0 /* message column */ + +int subsystemlen = sizeof("Subsystem") - 1; /* OGS subsystem name display field length */ +int booklen = sizeof("Book") - 1; /* OGS book name display field length */ +int filelen = sizeof("File") - 1; /* file name display field length */ +int fcnlen = sizeof("Function") - 1; /* function name display field length */ +int numlen = 0; /* line number display field length */ + +int *displine; /* screen line of displayed reference */ +unsigned int disprefs; /* displayed references */ +int field; /* input field */ +unsigned int mdisprefs; /* maximum displayed references */ +unsigned int nextline; /* next line to be shown */ +static int bottomline; /* bottom line of page */ +long searchcount; /* count of files searched */ +unsigned int totallines; /* total reference lines */ +unsigned int curdispline = 0; +int current_page = 0; +int input_mode = INPUT_NORMAL; +const char *prompts[] = {[INPUT_NORMAL] = "$ ", + [INPUT_APPEND] = "Append to file: ", + [INPUT_PIPE] = "Pipe to shell command: ", + [INPUT_READ] = "Read from file: ", + [INPUT_CHANGE_TO] = "To: ", + [INPUT_CHANGE] = "To: "}; + +unsigned int topline = 1; /* top line of page */ extern const char tooltip_winput[]; extern const char tooltip_wmode[]; @@ -90,15 +88,15 @@ extern const char tooltip_wresult[]; #define MAX(a, b) ((a) > (b) ? (a) : (b)) /* Selectable windows */ -WINDOW* winput; -WINDOW* wmode; -WINDOW* wresult; -WINDOW* whelp; +WINDOW *winput; +WINDOW *wmode; +WINDOW *wresult; +WINDOW *whelp; /* Non-Selectable windows */ -WINDOW* wtooltip; +WINDOW *wtooltip; /* Selected window pointer */ -WINDOW** current_window; -static WINDOW** last_window; +WINDOW **current_window; +static WINDOW **last_window; static int result_window_height; static int second_col_width; @@ -120,45 +118,102 @@ static inline void display_results(void); static inline void display_tooltip(void); /* NOTE: It's declared like this because we dont need a terminating '\00'. */ -static const char dispchars[] = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' -}; -int dispchar2int(const char c){ +static const char dispchars[] = {'0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z'}; + +int dispchar2int(const char c) { const char fst = dispchars[0]; - const char lst = dispchars[sizeof(dispchars)-1]; - int r = c - fst; - if(r < 0 || lst < r){ return -1; } + const char lst = dispchars[sizeof(dispchars) - 1]; + int r = c - fst; + if(r < 0 || lst < r) { return -1; } return r; } -char lastmsg[MSGLEN + 1]; /* last message displayed */ +char lastmsg[MSGLEN + 1]; /* last message displayed */ -struct { /* text of input fields */ - char *text1; - char *text2; +struct { /* text of input fields */ + char *text1; + char *text2; } /* Paralel array to "field_searchers", indexed by "field" */ -fields[FIELDS + 1] = { /* samuel has a search that is not part of the cscope display */ - {"Find this", "C symbol"}, - {"Find this", "global definition"}, - {"Find", "functions called by this function"}, - {"Find", "functions calling this function"}, - {"Find this", "text string"}, - {"Change this", "text string"}, - {"Find this", "egrep pattern"}, - {"Find this", "file"}, - {"Find", "files #including this file"}, - {"Find", "assignments to this symbol"}, - {"Find all", "function definitions"}, /* samuel only */ +fields[FIELDS + 1] = { + /* samuel has a search that is not part of the cscope display */ + {"Find this", "C symbol" }, + {"Find this", "global definition" }, + {"Find", "functions called by this function"}, + {"Find", "functions calling this function" }, + {"Find this", "text string" }, + {"Change this", "text string" }, + {"Find this", "egrep pattern" }, + {"Find this", "file" }, + {"Find", "files #including this file" }, + {"Find", "assignments to this symbol" }, + {"Find all", "function definitions" }, /* samuel only */ }; /* initialize display parameters */ -void -dispinit(void) -{ - /* initialize the curses display package */ - initscr(); /* initialize the screen */ +void dispinit(void) { + /* initialize the curses display package */ + initscr(); /* initialize the screen */ start_color(); use_default_colors(); easy_init_pair(FRAME); @@ -184,81 +239,77 @@ dispinit(void) easy_init_pair(TABLE_COL_SELECTED_FUNCTION); easy_init_pair(TABLE_COL_SELECTED_TEXT); easy_init_pair(PAGER_MSG); - entercurses(); - - /* Calculate section sizes */ - result_window_height = LINES - 2; - input_window_height = 1; - mode_window_height = LINES - input_window_height - 2 - 1; - first_col_width = 48; // (((COLS - 2)%2 == 0) ? ((COLS-2)/2) : (((COLS-2)/2)+1)); - second_col_width = COLS - 2 - 1 - first_col_width; //((COLS - 2) / 2) - 1; - mdisprefs = result_window_height - (WRESULT_TABLE_BODY_START + 1); - tooltip_width = MAX(MAX(strlen(tooltip_winput), strlen(tooltip_wmode)), strlen(tooltip_wresult)); - - if (mdisprefs <= 0) { - postfatal(PROGRAM_NAME ": screen too small\n"); - /* NOTREACHED */ - } - if(mdisprefs > sizeof(dispchars)){ - mdisprefs = sizeof(dispchars); - } - - /* allocate the displayed line array */ - displine = malloc(mdisprefs * sizeof(*displine)); - - /* readline */ - rlinit(); - - /* initialize windows */ - winput = newwin(input_window_height, first_col_width, 1, 1); - wmode = newwin(mode_window_height, first_col_width, input_window_height+1 + 1, 1); - wresult = newwin(result_window_height, second_col_width, 1, first_col_width + 1 + 1); - whelp = newwin(LINES-2, COLS-2, 1, 1); - wtooltip = newwin(1, tooltip_width, LINES-1, COLS - (tooltip_width+4)); - refresh(); - - current_window = &winput; + entercurses(); + + /* Calculate section sizes */ + result_window_height = LINES - 2; + input_window_height = 1; + mode_window_height = LINES - input_window_height - 2 - 1; + first_col_width = 48; // (((COLS - 2)%2 == 0) ? ((COLS-2)/2) : (((COLS-2)/2)+1)); + second_col_width = COLS - 2 - 1 - first_col_width; //((COLS - 2) / 2) - 1; + mdisprefs = result_window_height - (WRESULT_TABLE_BODY_START + 1); + tooltip_width = + MAX(MAX(strlen(tooltip_winput), strlen(tooltip_wmode)), strlen(tooltip_wresult)); + + if(mdisprefs <= 0) { + postfatal(PROGRAM_NAME ": screen too small\n"); + /* NOTREACHED */ + } + if(mdisprefs > sizeof(dispchars)) { mdisprefs = sizeof(dispchars); } + + /* allocate the displayed line array */ + displine = malloc(mdisprefs * sizeof(*displine)); + + /* readline */ + rlinit(); + + /* initialize windows */ + winput = newwin(input_window_height, first_col_width, 1, 1); + wmode = newwin(mode_window_height, first_col_width, input_window_height + 1 + 1, 1); + wresult = newwin(result_window_height, second_col_width, 1, first_col_width + 1 + 1); + whelp = newwin(LINES - 2, COLS - 2, 1, 1); + wtooltip = newwin(1, tooltip_width, LINES - 1, COLS - (tooltip_width + 4)); + refresh(); + + current_window = &winput; } /* enter curses mode */ -void -entercurses(void) -{ - incurses = true; +void entercurses(void) { + incurses = true; window_change = CH_ALL; - nonl(); /* don't translate an output \n to \n\r */ - cbreak(); /* single character input */ - noecho(); /* don't echo input characters */ - curs_set(0); - clear(); /* clear the screen */ - mouseinit(); /* initialize any mouse interface */ - //drawscrollbar(topline, nextline); - keypad(stdscr, TRUE); /* enable the keypad */ - //fixkeypad(); /* fix for getch() intermittently returning garbage */ - standend(); /* turn off reverse video */ + nonl(); /* don't translate an output \n to \n\r */ + cbreak(); /* single character input */ + noecho(); /* don't echo input characters */ + curs_set(0); + clear(); /* clear the screen */ + mouseinit(); /* initialize any mouse interface */ + // drawscrollbar(topline, nextline); + keypad(stdscr, TRUE); /* enable the keypad */ + // fixkeypad(); /* fix for getch() intermittently returning garbage */ + standend(); /* turn off reverse video */ } /* exit curses mode */ -void -exitcurses(void) -{ - /* clear the bottom line */ - move(LINES - 1, 0); - clrtoeol(); - refresh(); - - /* exit curses and restore the terminal modes */ - endwin(); - incurses = false; - - /* restore the mouse */ - mousecleanup(); - fflush(stdout); +void exitcurses(void) { + /* clear the bottom line */ + move(LINES - 1, 0); + clrtoeol(); + refresh(); + + /* exit curses and restore the terminal modes */ + endwin(); + incurses = false; + + /* restore the mouse */ + mousecleanup(); + fflush(stdout); } -static inline void display_help(){ - // XXX: this could be optimized by only overriding the buffer if theres an actual change +static inline void display_help() { + // XXX: this could be optimized by only overriding the buffer if theres an actual + // change werase(whelp); wmove(whelp, 0, 0); wattron(whelp, COLOR_PAIR(COLOR_PAIR_HELP)); @@ -271,36 +322,36 @@ static inline void display_help(){ do_press_any_key = true; } -static inline void display_frame(const bool border_only){ +static inline void display_frame(const bool border_only) { wattron(stdscr, COLOR_PAIR(COLOR_PAIR_FRAME)); - box(stdscr, 0, 0); - /* Title*/ - const int LEFT_PADDING = 5; - wmove(stdscr, 0, LEFT_PADDING); + box(stdscr, 0, 0); + /* Title*/ + const int LEFT_PADDING = 5; + wmove(stdscr, 0, LEFT_PADDING); #if CCS - wprintw(stdscr, PROGRAM_NAME " %s", ESG_REL); + wprintw(stdscr, PROGRAM_NAME " %s", ESG_REL); #else - wprintw(stdscr, PROGRAM_NAME " version %d%s", FILEVERSION, FIXVERSION); + wprintw(stdscr, PROGRAM_NAME " version %d%s", FILEVERSION, FIXVERSION); #endif - wmove(stdscr, 0, COLS - (int)sizeof("Case: XXX") - 4); - if(caseless){ - waddstr(stdscr, "Case: ON"); - }else{ - waddstr(stdscr, "Case: OFF"); + wmove(stdscr, 0, COLS - (int)sizeof("Case: XXX") - 4); + if(caseless) { + waddstr(stdscr, "Case: ON"); + } else { + waddstr(stdscr, "Case: OFF"); } /* --- */ - if(!border_only){ + if(!border_only) { /* Vertical line */ mvaddch(0, first_col_width + 1, ACS_TTEE); - for(int i = 0; i < LINES-2; i++){ - mvaddch(i+1, first_col_width + 1, ACS_VLINE); + for(int i = 0; i < LINES - 2; i++) { + mvaddch(i + 1, first_col_width + 1, ACS_VLINE); } - mvaddch(LINES-1, first_col_width + 1, ACS_BTEE); + mvaddch(LINES - 1, first_col_width + 1, ACS_BTEE); /* Horizontal line */ wmove(stdscr, input_window_height + 1, 0); addch(ACS_LTEE); - for(int i = 0; i < first_col_width; i++){ + for(int i = 0; i < first_col_width; i++) { addch(ACS_HLINE); } addch(ACS_RTEE); @@ -309,244 +360,246 @@ static inline void display_frame(const bool border_only){ wattroff(stdscr, COLOR_PAIR(COLOR_PAIR_FRAME)); } -static inline void display_mode(){ +static inline void display_mode() { werase(wmode); - for(int i = 0; i < FIELDS; ++i){ - if(i == field){ - wattron(wmode, COLOR_PAIR(COLOR_PAIR_FIELD_SELECTED) | ATTRIBUTE_FIELD_SELECTED); + for(int i = 0; i < FIELDS; ++i) { + if(i == field) { + wattron(wmode, + COLOR_PAIR(COLOR_PAIR_FIELD_SELECTED) | ATTRIBUTE_FIELD_SELECTED); mvwprintw(wmode, i, 0, "%s %s", fields[i].text1, fields[i].text2); - wattroff(wmode, COLOR_PAIR(COLOR_PAIR_FIELD_SELECTED) | ATTRIBUTE_FIELD_SELECTED); - }else{ + wattroff(wmode, + COLOR_PAIR(COLOR_PAIR_FIELD_SELECTED) | ATTRIBUTE_FIELD_SELECTED); + } else { wattron(wmode, COLOR_PAIR(COLOR_PAIR_FIELD)); mvwprintw(wmode, i, 0, "%s %s", fields[i].text1, fields[i].text2); wattroff(wmode, COLOR_PAIR(COLOR_PAIR_FIELD)); } - } + } } -static inline void display_command_field(){ - werase(winput); +static inline void display_command_field() { + werase(winput); wattron(winput, COLOR_PAIR(COLOR_PAIR_PROMPT)); - mvwaddstr(winput, 0, 0, prompts[input_mode]); + mvwaddstr(winput, 0, 0, prompts[input_mode]); wattroff(winput, COLOR_PAIR(COLOR_PAIR_PROMPT)); - waddstr(winput, rl_line_buffer); + waddstr(winput, rl_line_buffer); display_cursor(); } -static inline void display_results(){ - int i; - char *s; - int screenline; /* screen line number */ - int srctxtw; /* source line display width */ - int color_swp; /* holds the rigth ncurses color value, - * so we dont have to branch twice - * (at attron & attroff) - * because of selections - */ - int attr_swp; /* holds the rigth ncurses attribute value, - * so we dont have to branch twice - * (at attron & attroff) - * because of selections - */ - /* column headings */ - char *subsystem; /* OGS subsystem name */ - char *book; /* OGS book name */ - char file[PATHLEN + 1]; /* file name */ - char function[PATLEN + 1]; /* function name */ - char linenum[NUMLEN + 1]; /* line number */ + +static inline void display_results() { + int i; + char *s; + int screenline; /* screen line number */ + int srctxtw; /* source line display width */ + int color_swp; /* holds the rigth ncurses color value, + * so we dont have to branch twice + * (at attron & attroff) + * because of selections + */ + int attr_swp; /* holds the rigth ncurses attribute value, + * so we dont have to branch twice + * (at attron & attroff) + * because of selections + */ + /* column headings */ + char *subsystem; /* OGS subsystem name */ + char *book; /* OGS book name */ + char file[PATHLEN + 1]; /* file name */ + char function[PATLEN + 1]; /* function name */ + char linenum[NUMLEN + 1]; /* line number */ werase(wresult); /* --- Display the message --- */ - if (totallines == 0) { // Its a real message - wmove(wresult, MSGLINE, 0); - wclrtoeol(wresult); + if(totallines == 0) { // Its a real message + wmove(wresult, MSGLINE, 0); + wclrtoeol(wresult); wattron(wresult, COLOR_PAIR(COLOR_PAIR_MESSAGE)); - waddstr(wresult, lastmsg); + waddstr(wresult, lastmsg); wattroff(wresult, COLOR_PAIR(COLOR_PAIR_MESSAGE)); - return; - } - if (input_mode == INPUT_CHANGE) { // Its a pattern + return; + } + if(input_mode == INPUT_CHANGE) { // Its a pattern snprintf(lastmsg, MSGLEN, "Change \"%s\" to \"%s\"", input_line, newpat); - } else { - snprintf(lastmsg, MSGLEN, "%c%s: %s", toupper((unsigned char)fields[field].text2[0]), - fields[field].text2 + 1, input_line); - } + } else { + snprintf(lastmsg, + MSGLEN, + "%c%s: %s", + toupper((unsigned char)fields[field].text2[0]), + fields[field].text2 + 1, + input_line); + } wattron(wresult, COLOR_PAIR(COLOR_PAIR_PATTERN)); - waddstr(wresult, lastmsg); + waddstr(wresult, lastmsg); wattroff(wresult, COLOR_PAIR(COLOR_PAIR_PATTERN)); - /* --- Display the column headings --- */ + /* --- Display the column headings --- */ wattron(wresult, COLOR_PAIR(COLOR_PAIR_TABLE_HEADER)); - wmove(wresult, 2, 2); - if (ogs == true && field != FILENAME) { - wprintw(wresult, "%-*s ", subsystemlen, "Subsystem"); - wprintw(wresult, "%-*s ", booklen, "Book"); - } - if (dispcomponents > 0) - wprintw(wresult, "%-*s ", filelen, "File"); - - if (field == SYMBOL || field == CALLEDBY || field == CALLING) { - wprintw(wresult, "%-*s ", fcnlen, "Function"); - } - if (field != FILENAME) { - waddstr(wresult, "Line"); - } + wmove(wresult, 2, 2); + if(ogs == true && field != FILENAME) { + wprintw(wresult, "%-*s ", subsystemlen, "Subsystem"); + wprintw(wresult, "%-*s ", booklen, "Book"); + } + if(dispcomponents > 0) wprintw(wresult, "%-*s ", filelen, "File"); + + if(field == SYMBOL || field == CALLEDBY || field == CALLING) { + wprintw(wresult, "%-*s ", fcnlen, "Function"); + } + if(field != FILENAME) { waddstr(wresult, "Line"); } wattroff(wresult, COLOR_PAIR(COLOR_PAIR_TABLE_HEADER)); /* --- Display table entries --- */ - wmove(wresult, WRESULT_TABLE_BODY_START, 0); - - /* calculate the source text column */ - /* NOTE: the +1s are column gaps */ - srctxtw = second_col_width; - srctxtw -= 1+1; // dispchars - if (ogs == true) { - srctxtw -= subsystemlen+1 + booklen+1; - } - if (dispcomponents > 0) { - srctxtw -= filelen+1; - } - if (field == SYMBOL || field == CALLEDBY || field == CALLING) { - srctxtw -= fcnlen+1; - } - srctxtw -= numlen+1; + wmove(wresult, WRESULT_TABLE_BODY_START, 0); + + /* calculate the source text column */ + /* NOTE: the +1s are column gaps */ + srctxtw = second_col_width; + srctxtw -= 1 + 1; // dispchars + if(ogs == true) { srctxtw -= subsystemlen + 1 + booklen + 1; } + if(dispcomponents > 0) { srctxtw -= filelen + 1; } + if(field == SYMBOL || field == CALLEDBY || field == CALLING) { + srctxtw -= fcnlen + 1; + } + srctxtw -= numlen + 1; /* decide where to list from */ { int seekerr; - do{ + do { seekerr = seekpage(current_page); - }while(seekerr == -1 && current_page--); + } while(seekerr == -1 && current_page--); } - /* until the max references have been displayed or - there is no more room */ - for (disprefs = 0, screenline = WRESULT_TABLE_BODY_START; - disprefs < mdisprefs && screenline < (result_window_height-1); - ++disprefs, ++screenline) - { + /* until the max references have been displayed or + there is no more room */ + for(disprefs = 0, screenline = WRESULT_TABLE_BODY_START; + disprefs < mdisprefs && screenline < (result_window_height - 1); + ++disprefs, ++screenline) { attr_swp = (disprefs != curdispline) ? A_NORMAL : ATTRIBUTE_RESULT_SELECTED; wattron(wresult, attr_swp); - /* read the reference line */ - if ( - fscanf(refsfound, "%" PATHLEN_STR "s%" PATHLEN_STR "s%" NUMLEN_STR "s %" TEMPSTRING_LEN_STR "[^\n]", - file, - function, - linenum, - tempstring - ) - < - 4 - ){ break; } - - ++nextline; - displine[disprefs] = screenline; - - color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_ID : COLOR_PAIR_TABLE_SELECTED_ID; + /* read the reference line */ + if(fscanf(refsfound, + "%" PATHLEN_STR "s%" PATHLEN_STR "s%" NUMLEN_STR "s %" TEMPSTRING_LEN_STR + "[^\n]", + file, + function, + linenum, + tempstring) < 4) { + break; + } + + ++nextline; + displine[disprefs] = screenline; + + color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_ID : + COLOR_PAIR_TABLE_SELECTED_ID; wattron(wresult, COLOR_PAIR(color_swp)); - wprintw(wresult, "%c", dispchars[disprefs]); + wprintw(wresult, "%c", dispchars[disprefs]); wattroff(wresult, COLOR_PAIR(color_swp)); - /* display any change mark */ - color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_MARK : COLOR_PAIR_TABLE_SELECTED_MARK; + /* display any change mark */ + color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_MARK : + COLOR_PAIR_TABLE_SELECTED_MARK; wattron(wresult, COLOR_PAIR(color_swp)); - if (input_mode == INPUT_CHANGE && change[topref + disprefs]) { - waddch(wresult, '>'); - } else { - waddch(wresult, ' '); - } + if(input_mode == INPUT_CHANGE && change[topref + disprefs]) { + waddch(wresult, '>'); + } else { + waddch(wresult, ' '); + } wattroff(wresult, COLOR_PAIR(color_swp)); - /* display the file name */ - color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_FILE : COLOR_PAIR_TABLE_COL_SELECTED_FILE; + /* display the file name */ + color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_FILE : + COLOR_PAIR_TABLE_COL_SELECTED_FILE; wattron(wresult, COLOR_PAIR(color_swp)); - if (field == FILENAME) { + if(field == FILENAME) { wprintw(wresult, "%-*s ", filelen, file); - } else { + } else { /* if OGS, display the subsystem and book names */ - if (ogs == true) { + if(ogs == true) { ogsnames(file, &subsystem, &book); wprintw(wresult, "%-*.*s ", subsystemlen, subsystemlen, subsystem); wprintw(wresult, "%-*.*s ", booklen, booklen, book); } /* display the requested path components */ - if (dispcomponents > 0) { - wprintw(wresult, "%-*.*s ", filelen, filelen, - pathcomponents(file, dispcomponents)); + if(dispcomponents > 0) { + wprintw(wresult, + "%-*.*s ", + filelen, + filelen, + pathcomponents(file, dispcomponents)); } - } /* else(field == FILENAME) */ + } /* else(field == FILENAME) */ wattroff(wresult, COLOR_PAIR(color_swp)); - /* display the function name */ - if(field == SYMBOL || field == CALLEDBY || field == CALLING){ - color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_FUNCTION : COLOR_PAIR_TABLE_COL_SELECTED_FUNCTION; + /* display the function name */ + if(field == SYMBOL || field == CALLEDBY || field == CALLING) { + color_swp = (disprefs != curdispline) ? + COLOR_PAIR_TABLE_COL_FUNCTION : + COLOR_PAIR_TABLE_COL_SELECTED_FUNCTION; wattron(wresult, COLOR_PAIR(color_swp)); - wprintw(wresult, "%-*.*s ", fcnlen, fcnlen, function); + wprintw(wresult, "%-*.*s ", fcnlen, fcnlen, function); wattroff(wresult, COLOR_PAIR(color_swp)); - } - if(field == FILENAME){ - waddch(wresult, '\n'); /* go to next line */ + } + if(field == FILENAME) { + waddch(wresult, '\n'); /* go to next line */ continue; - } + } - /* display the line number */ - color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_LINE : COLOR_PAIR_TABLE_COL_SELECTED_LINE; + /* display the line number */ + color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_LINE : + COLOR_PAIR_TABLE_COL_SELECTED_LINE; wattron(wresult, COLOR_PAIR(color_swp)); - wprintw(wresult, "%*s ", numlen, linenum); + wprintw(wresult, "%*s ", numlen, linenum); wattroff(wresult, COLOR_PAIR(color_swp)); - /* there may be tabs in egrep output */ - while((s = strchr(tempstring, '\t')) != NULL){ + /* there may be tabs in egrep output */ + while((s = strchr(tempstring, '\t')) != NULL) { *s = ' '; - } + } - /* display the source line */ - color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_TEXT : COLOR_PAIR_TABLE_COL_SELECTED_TEXT; + /* display the source line */ + color_swp = (disprefs != curdispline) ? COLOR_PAIR_TABLE_COL_TEXT : + COLOR_PAIR_TABLE_COL_SELECTED_TEXT; wattron(wresult, COLOR_PAIR(color_swp)); - s = tempstring; - for (;;) { + s = tempstring; + for(;;) { /* if the source line does not fit */ - if ((i = strlen(s)) > srctxtw) { + if((i = strlen(s)) > srctxtw) { /* find the nearest blank */ - for (i = srctxtw; s[i] != ' ' && i > 0; --i) { + for(i = srctxtw; s[i] != ' ' && i > 0; --i) { ; } - if (i == 0) { - i = srctxtw; /* no blank */ - } + if(i == 0) { i = srctxtw; /* no blank */ } } /* print up to this point */ wprintw(wresult, "%.*s", i, s); s += i; /* if line didn't wrap around */ - if (i < srctxtw) { - waddch(wresult, '\n'); /* go to next line */ - } + if(i < srctxtw) { waddch(wresult, '\n'); /* go to next line */ } /* skip blanks */ - while (*s == ' ') { + while(*s == ' ') { ++s; } /* see if there is more text */ - if (*s == '\0') { - break; - } + if(*s == '\0') { break; } /* if the source line is too long */ - if (++screenline > result_window_height) { + if(++screenline > result_window_height) { /* if this is the first displayed line, display what will fit on the screen */ - if (topref == nextline-1) { + if(topref == nextline - 1) { disprefs++; /* break out of two loops */ goto endrefs; } /* erase the reference */ - while (--screenline >= displine[disprefs]) { + while(--screenline >= displine[disprefs]) { wmove(wresult, screenline, 0); wclrtoeol(wresult); } @@ -559,274 +612,241 @@ static inline void display_results(){ } /* indent the continued source line */ wmove(wresult, screenline, second_col_width - srctxtw); - } /* for(ever) */ + } /* for(ever) */ wattroff(wresult, COLOR_PAIR(color_swp)); wattroff(wresult, attr_swp); - } /* for(reference output lines) */ + } /* for(reference output lines) */ endrefs: wattroff(wresult, attr_swp); /* --- display pager message --- */ /* position cursor */ - i = result_window_height - 1; - if (screenline < i) { - waddch(wresult, '\n'); - } - else { - wmove(wresult, i, 0); - } + i = result_window_height - 1; + if(screenline < i) { + waddch(wresult, '\n'); + } else { + wmove(wresult, i, 0); + } /**/ wattron(wresult, COLOR_PAIR(COLOR_PAIR_PAGER_MSG)); - /* check for more references */ - i = totallines - nextline + 1; - bottomline = nextline; - if (i > 0) { - wprintw(wresult, "* Lines %d-%d of %d, %d more. *", topref, bottomline, totallines, i); - } - /* if this is the last page of references */ - else if (current_page > 0 && nextline > totallines) { - waddstr(wresult, "* End of results. *"); - } + /* check for more references */ + i = totallines - nextline + 1; + bottomline = nextline; + if(i > 0) { + wprintw(wresult, + "* Lines %d-%d of %d, %d more. *", + topref, + bottomline, + totallines, + i); + } + /* if this is the last page of references */ + else if(current_page > 0 && nextline > totallines) { + waddstr(wresult, "* End of results. *"); + } wattroff(wresult, COLOR_PAIR(COLOR_PAIR_PAGER_MSG)); } -static inline void display_cursor(void){ - chtype i; - int yoffset = 0, xoffset = 0; +static inline void display_cursor(void) { + chtype i; + int yoffset = 0, xoffset = 0; - xoffset = strlen(prompts[input_mode]) + rl_point; + xoffset = strlen(prompts[input_mode]) + rl_point; - wmove(*current_window, yoffset, xoffset); + wmove(*current_window, yoffset, xoffset); - i = winch(*current_window); - i |= A_REVERSE; - waddch(*current_window, i); + i = winch(*current_window); + i |= A_REVERSE; + waddch(*current_window, i); } -void -horswp_field(void){ - if(current_window != &wresult){ - if(totallines == 0){ return; } - if(current_window == &winput){ - window_change |= CH_INPUT; - }else{ - window_change |= CH_MODE; - } - last_window = current_window; - current_window = &wresult; - }else{ - current_window = last_window; - if(current_window == &winput){ - window_change |= CH_INPUT; - } - } - window_change |= CH_RESULT; + +void horswp_field(void) { + if(current_window != &wresult) { + if(totallines == 0) { return; } + if(current_window == &winput) { + window_change |= CH_INPUT; + } else { + window_change |= CH_MODE; + } + last_window = current_window; + current_window = &wresult; + } else { + current_window = last_window; + if(current_window == &winput) { window_change |= CH_INPUT; } + } + window_change |= CH_RESULT; } -void -verswp_field(void){ - if(current_window == &wresult){ return; } - current_window = (current_window == &winput) ? &wmode : &winput; - window_change |= CH_INPUT | CH_MODE; +void verswp_field(void) { + if(current_window == &wresult) { return; } + current_window = (current_window == &winput) ? &wmode : &winput; + window_change |= CH_INPUT | CH_MODE; } /* display search progress with default custom format */ -void -progress(char *what, long current, long max) -{ - static long start; - long now; - int i; - - /* save the start time */ - if (searchcount == 0) { - start = time(NULL); - } - if ((now = time(NULL)) - start >= 1) - { - if (linemode == false) - { - wmove(wresult, MSGLINE, MSGCOL); - wclrtoeol(wresult); - waddstr(wresult, what); - snprintf(lastmsg, sizeof(lastmsg), "%ld", current); - wmove(wresult, MSGLINE, (COLS / 2) - (strlen(lastmsg) / 2)); - waddstr(wresult, lastmsg); - snprintf(lastmsg, sizeof(lastmsg), "%ld", max); - wmove(wresult, MSGLINE, COLS - strlen(lastmsg)); - waddstr(wresult, lastmsg); - refresh(); - } - else if (verbosemode == true) - { - snprintf(lastmsg, sizeof(lastmsg), "> %s %ld of %ld", what, current, max); - } - - start = now; - if ((linemode == false) && (incurses == true)) - { - wmove(wresult, MSGLINE, MSGCOL); - i = (float)COLS * (float)current / (float)max; - - standout(); - for (; i > 0; i--) - waddch(wresult, inch()); - standend(); - refresh(); - } - else - if(linemode == false || verbosemode == true){ - postmsg(lastmsg); - } - } - ++searchcount; +void progress(char *what, long current, long max) { + static long start; + long now; + int i; + + /* save the start time */ + if(searchcount == 0) { start = time(NULL); } + if((now = time(NULL)) - start >= 1) { + if(linemode == false) { + wmove(wresult, MSGLINE, MSGCOL); + wclrtoeol(wresult); + waddstr(wresult, what); + snprintf(lastmsg, sizeof(lastmsg), "%ld", current); + wmove(wresult, MSGLINE, (COLS / 2) - (strlen(lastmsg) / 2)); + waddstr(wresult, lastmsg); + snprintf(lastmsg, sizeof(lastmsg), "%ld", max); + wmove(wresult, MSGLINE, COLS - strlen(lastmsg)); + waddstr(wresult, lastmsg); + refresh(); + } else if(verbosemode == true) { + snprintf(lastmsg, sizeof(lastmsg), "> %s %ld of %ld", what, current, max); + } + + start = now; + if((linemode == false) && (incurses == true)) { + wmove(wresult, MSGLINE, MSGCOL); + i = (float)COLS * (float)current / (float)max; + + standout(); + for(; i > 0; i--) + waddch(wresult, inch()); + standend(); + refresh(); + } else if(linemode == false || verbosemode == true) { + postmsg(lastmsg); + } + } + ++searchcount; } /* print error message on system call failure */ -void -myperror(char *text) -{ - char *s; +void myperror(char *text) { + char *s; - s = strerror(errno); + s = strerror(errno); - (void) snprintf(lastmsg, sizeof(lastmsg), "%s: %s", text, s); - postmsg(lastmsg); + (void)snprintf(lastmsg, sizeof(lastmsg), "%s: %s", text, s); + postmsg(lastmsg); } /* postmsg clears the message line and prints the message */ -void -postmsg(char *msg) -{ - if (linemode == true || incurses == false) { - printf("%s\n", msg); - fflush(stdout); - } - else { +void postmsg(char *msg) { + if(linemode == true || incurses == false) { + printf("%s\n", msg); + fflush(stdout); + } else { window_change |= CH_RESULT; - } - UNUSED(strncpy(lastmsg, msg, sizeof(lastmsg) - 1)); + } + UNUSED(strncpy(lastmsg, msg, sizeof(lastmsg) - 1)); } /* clearmsg2 clears the second message line */ -void -clearmsg2(void) -{ - if (linemode == false) { - wmove(wresult, MSGLINE + 1, 0); - wclrtoeol(wresult); - } +void clearmsg2(void) { + if(linemode == false) { + wmove(wresult, MSGLINE + 1, 0); + wclrtoeol(wresult); + } } /* postmsg2 clears the second message line and prints the message */ -void -postmsg2(char *msg) -{ - if (linemode == true) { - (void) printf("%s\n", msg); - } - else { - clearmsg2(); - waddstr(wresult, msg); - wrefresh(wresult); - } +void postmsg2(char *msg) { + if(linemode == true) { + (void)printf("%s\n", msg); + } else { + clearmsg2(); + waddstr(wresult, msg); + wrefresh(wresult); + } } /* display an error mesg - stdout or on second msg line */ -void -posterr(char *msg, ...) -{ - va_list ap; - char errbuf[MSGLEN]; - - va_start(ap, msg); - if (linemode == true || incurses == false) - { - (void) vfprintf(stderr, msg, ap); - (void) fputc('\n', stderr); - } else { - vsnprintf(errbuf, sizeof(errbuf), msg, ap); - postmsg2(errbuf); - } - va_end(ap); +void posterr(char *msg, ...) { + va_list ap; + char errbuf[MSGLEN]; + + va_start(ap, msg); + if(linemode == true || incurses == false) { + (void)vfprintf(stderr, msg, ap); + (void)fputc('\n', stderr); + } else { + vsnprintf(errbuf, sizeof(errbuf), msg, ap); + postmsg2(errbuf); + } + va_end(ap); } /* display a fatal error mesg -- stderr *after* shutting down curses */ -void -postfatal(const char *msg, ...) -{ - va_list ap; - char errbuf[MSGLEN]; - - va_start(ap, msg); - vsnprintf(errbuf, sizeof(errbuf), msg, ap); - /* restore the terminal to its original mode */ - if (incurses == true) { - exitcurses(); - } - - /* display fatal error messages */ - fprintf(stderr,"%s",errbuf); - - /* shut down */ - myexit(1); +void postfatal(const char *msg, ...) { + va_list ap; + char errbuf[MSGLEN]; + + va_start(ap, msg); + vsnprintf(errbuf, sizeof(errbuf), msg, ap); + /* restore the terminal to its original mode */ + if(incurses == true) { exitcurses(); } + + /* display fatal error messages */ + fprintf(stderr, "%s", errbuf); + + /* shut down */ + myexit(1); } /* get the OGS subsystem and book names */ -void -ogsnames(char *file, char **subsystem, char **book) -{ - static char buf[PATHLEN + 1]; - char *s, *slash; - - *subsystem = *book = ""; - (void) strcpy(buf,file); - s = buf; - if (*s == '/') { - ++s; - } - while ((slash = strchr(s, '/')) != NULL) { - *slash = '\0'; - if ((int)strlen(s) >= 3 && strncmp(slash - 3, ".ss", 3) == 0) { - *subsystem = s; - s = slash + 1; - if ((slash = strchr(s, '/')) != NULL) { - *book = s; - *slash = '\0'; - } - break; - } - s = slash + 1; - } +void ogsnames(char *file, char **subsystem, char **book) { + static char buf[PATHLEN + 1]; + char *s, *slash; + + *subsystem = *book = ""; + (void)strcpy(buf, file); + s = buf; + if(*s == '/') { ++s; } + while((slash = strchr(s, '/')) != NULL) { + *slash = '\0'; + if((int)strlen(s) >= 3 && strncmp(slash - 3, ".ss", 3) == 0) { + *subsystem = s; + s = slash + 1; + if((slash = strchr(s, '/')) != NULL) { + *book = s; + *slash = '\0'; + } + break; + } + s = slash + 1; + } } -static inline void display_tooltip(void){ +static inline void display_tooltip(void) { wmove(wtooltip, 0, 0); - const char* tooltip; - if(*current_window == winput){ + const char *tooltip; + if(*current_window == winput) { tooltip = tooltip_winput; - }else if(*current_window == wmode){ + } else if(*current_window == wmode) { tooltip = tooltip_wmode; - }else if(*current_window == wresult){ + } else if(*current_window == wresult) { tooltip = tooltip_wresult; } wattron(wtooltip, COLOR_PAIR(COLOR_PAIR_TOOLTIP)); waddstr(wtooltip, tooltip); // XXX: cheap hack - for(int i = 0; i < (tooltip_width-strlen(tooltip)); i++){ + for(int i = 0; i < (tooltip_width - strlen(tooltip)); i++) { waddch(wtooltip, ' '); } wattroff(wtooltip, COLOR_PAIR(COLOR_PAIR_TOOLTIP)); } -void -display(void) -{ - //drawscrollbar(topline, nextline); /* display the scrollbar */ - static void* lstwin = NULL; /* for the tooltip (see below) */ +void display(void) { + // drawscrollbar(topline, nextline); /* display the scrollbar */ + static void *lstwin = NULL; /* for the tooltip (see below) */ - if(window_change){ - if(window_change == CH_HELP){ + if(window_change) { + if(window_change == CH_HELP) { display_frame(true); display_help(); /* Do not display over the help msg and @@ -835,32 +855,24 @@ display(void) window_change = CH_ALL; return; } - if(window_change == CH_ALL){ - display_frame(false); - } + if(window_change == CH_ALL) { display_frame(false); } /* As it stands the tooltip has to be redisplayed * on every window change. */ - if(lstwin != *current_window){ + if(lstwin != *current_window) { lstwin = *current_window; display_tooltip(); } - if(window_change & CH_INPUT){ - display_command_field(); - } - if(window_change & CH_RESULT){ - display_results(); - } - if(window_change & CH_MODE){ - display_mode(); - } - - refresh(); - wrefresh(winput); - wrefresh(wmode); - wrefresh(wresult); - wrefresh(wtooltip); - } - - window_change = CH_NONE; + if(window_change & CH_INPUT) { display_command_field(); } + if(window_change & CH_RESULT) { display_results(); } + if(window_change & CH_MODE) { display_mode(); } + + refresh(); + wrefresh(winput); + wrefresh(wmode); + wrefresh(wresult); + wrefresh(wtooltip); + } + + window_change = CH_NONE; } diff --git a/src/edit.c b/src/edit.c index b7272ec..7928eff 100644 --- a/src/edit.c +++ b/src/edit.c @@ -37,111 +37,95 @@ #include "global.h" #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) -#include +# include #else -#include +# include #endif /* edit this displayed reference */ -void -editref(int i) -{ - char file[PATHLEN + 1]; /* file name */ - char linenum[NUMLEN + 1]; /* line number */ - - /* verify that there is a references found file */ - if (refsfound == NULL) { - return; - } - /* get the selected line */ - seekrelline(i); - - /* get the file name and line number */ - if (fscanf(refsfound, "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s", file, linenum) == 2) { - edit(file, linenum); - } +void editref(int i) { + char file[PATHLEN + 1]; /* file name */ + char linenum[NUMLEN + 1]; /* line number */ + + /* verify that there is a references found file */ + if(refsfound == NULL) { return; } + /* get the selected line */ + seekrelline(i); + + /* get the file name and line number */ + if(fscanf(refsfound, "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s", file, linenum) == 2) { + edit(file, linenum); + } } /* edit all references */ -void -editall(void) -{ - char file[PATHLEN + 1]; /* file name */ - char linenum[NUMLEN + 1]; /* line number */ - int c; - - /* verify that there is a references found file */ - if (refsfound == NULL) { - return; - } - /* get the first line */ +void editall(void) { + char file[PATHLEN + 1]; /* file name */ + char linenum[NUMLEN + 1]; /* line number */ + int c; + + /* verify that there is a references found file */ + if(refsfound == NULL) { return; } + /* get the first line */ fseek(refsfound, 0, SEEK_SET); - /* get each file name and line number */ - while (fscanf(refsfound, "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s%*[^\n]", file, linenum) == 2) { - edit(file, linenum); /* edit it */ - if (editallprompt == true) { - addstr("Type ^D to stop editing all lines, or any other character to continue: "); - if ((c = getch()) == EOF || c == ctrl('D') || c == ctrl('Z')) { - break; - } - } - } + /* get each file name and line number */ + while( + fscanf(refsfound, "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s%*[^\n]", file, linenum) == + 2) { + edit(file, linenum); /* edit it */ + if(editallprompt == true) { + addstr( + "Type ^D to stop editing all lines, or any other character to continue: "); + if((c = getch()) == EOF || c == ctrl('D') || c == ctrl('Z')) { break; } + } + } } /* call the editor */ -void -edit(char *file, const char *const linenum) -{ - const char *const editor_basename = basename(editor); - char msg[MSGLEN + 1]; /* message */ - char plusnum[NUMLEN + 20]; /* line number option: allow space for wordy line# flag */ - - file = filepath(file); - snprintf(msg, sizeof(msg), "%s +%s %s", basename(editor), linenum, file); - postmsg(msg); - snprintf(plusnum, sizeof(plusnum), lineflag, linenum); +void edit(char *file, const char *const linenum) { + const char *const editor_basename = basename(editor); + char msg[MSGLEN + 1]; /* message */ + char plusnum[NUMLEN + 20]; /* line number option: allow space for wordy line# flag */ + + file = filepath(file); + snprintf(msg, sizeof(msg), "%s +%s %s", basename(editor), linenum, file); + postmsg(msg); + snprintf(plusnum, sizeof(plusnum), lineflag, linenum); /* Some pagers will not start paging, unless the input * file has more lines thant the screen does. * The way to get them to pause, is to pass in /dev/null too, * imatating endless blank lines. */ - const char* const shit_pagers[] = { - "page", - "more", - NULL - }; - for(const char *const *sp = shit_pagers; *sp != NULL; sp++){ - if(!strcmp(editor_basename, *sp)){ - execute(editor, editor, plusnum, file, "/dev/null", NULL); + const char *const shit_pagers[] = {"page", "more", NULL}; + for(const char *const *sp = shit_pagers; *sp != NULL; sp++) { + if(!strcmp(editor_basename, *sp)) { + execute(editor, editor, plusnum, file, "/dev/null", NULL); goto end; } } - if (lineflagafterfile) { - execute(editor, editor, file, plusnum, NULL); - } - else { - execute(editor, editor, plusnum, file, NULL); - } + if(lineflagafterfile) { + execute(editor, editor, file, plusnum, NULL); + } else { + execute(editor, editor, plusnum, file, NULL); + } - end: - clear(); /* redisplay screen */ +end: + clear(); /* redisplay screen */ } /* if requested, prepend a path to a relative file name */ -char * -filepath(char *file) -{ - static char path[PATHLEN + 1]; +char *filepath(char *file) { + static char path[PATHLEN + 1]; - if (prependpath != NULL && *file != '/') { - (void) snprintf(path, sizeof(path), "%s/%s", prependpath, file); - file = path; - } - return(file); + if(prependpath != NULL && *file != '/') { + (void)snprintf(path, sizeof(path), "%s/%s", prependpath, file); + file = path; + } + return (file); } diff --git a/src/egrep.c b/src/egrep.c index c315949..003265a 100644 --- a/src/egrep.c +++ b/src/egrep.c @@ -110,79 +110,79 @@ #include #include -#include /* jmp_buf */ +#include /* jmp_buf */ -#define nextch() (*input++) +#define nextch() (*input++) -#define MAXLIN 350 -#define MAXPOS 4000 -#define NCHARS 256 +#define MAXLIN 350 +#define MAXPOS 4000 +#define NCHARS 256 #define NSTATES 128 -#define FINAL -1 -static char gotofn[NSTATES][NCHARS]; -static int state[NSTATES]; -static char out[NSTATES]; -static unsigned int line; -static int name[MAXLIN]; -static unsigned int left[MAXLIN]; -static unsigned int right[MAXLIN]; -static unsigned int parent[MAXLIN]; -static int foll[MAXLIN]; -static int positions[MAXPOS]; -static char chars[MAXLIN]; -static int nxtpos; -static int nxtchar; -static int tmpstat[MAXLIN]; -static int initstat[MAXLIN]; -static int xstate; -static int count; -static int icount; -static char *input; -static long lnum; -static int iflag; -static jmp_buf env; /* setjmp/longjmp buffer */ -static char *message; /* error message */ +#define FINAL -1 +static char gotofn[NSTATES][NCHARS]; +static int state[NSTATES]; +static char out[NSTATES]; +static unsigned int line; +static int name[MAXLIN]; +static unsigned int left[MAXLIN]; +static unsigned int right[MAXLIN]; +static unsigned int parent[MAXLIN]; +static int foll[MAXLIN]; +static int positions[MAXPOS]; +static char chars[MAXLIN]; +static int nxtpos; +static int nxtchar; +static int tmpstat[MAXLIN]; +static int initstat[MAXLIN]; +static int xstate; +static int count; +static int icount; +static char *input; +static long lnum; +static int iflag; +static jmp_buf env; /* setjmp/longjmp buffer */ +static char *message; /* error message */ /* Internal prototypes: */ -static void cfoll(int v); -static void cgotofn(void); -static int cstate(int v); -static int member(int symb, int set, int torf); -static int notin(int n); -static void synerror(void); -static void overflo(void); -static void add(int *array, int n); -static void follow(unsigned int v); -static int unary(int x, int d); -static int node(int x, int l, int r); -static unsigned int cclenter(int x); -static unsigned int enter(int x); +static void cfoll(int v); +static void cgotofn(void); +static int cstate(int v); +static int member(int symb, int set, int torf); +static int notin(int n); +static void synerror(void); +static void overflo(void); +static void add(int *array, int n); +static void follow(unsigned int v); +static int unary(int x, int d); +static int node(int x, int l, int r); +static unsigned int cclenter(int x); +static unsigned int enter(int x); static int yylex(void); static int yyerror(char *); #line 165 "y.tab.c" -# ifndef YY_CAST -# ifdef __cplusplus -# define YY_CAST(Type, Val) static_cast (Val) -# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast (Val) -# else -# define YY_CAST(Type, Val) ((Type) (Val)) -# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) -# endif +#ifndef YY_CAST +# ifdef __cplusplus +# define YY_CAST(Type, Val) static_cast(Val) +# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast(Val) +# else +# define YY_CAST(Type, Val) ((Type)(Val)) +# define YY_REINTERPRET_CAST(Type, Val) ((Type)(Val)) # endif -# ifndef YY_NULLPTR -# if defined __cplusplus -# if 201103L <= __cplusplus -# define YY_NULLPTR nullptr -# else -# define YY_NULLPTR 0 -# endif +#endif +#ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr # else -# define YY_NULLPTR ((void*)0) +# define YY_NULLPTR 0 # endif +# else +# define YY_NULLPTR ((void *)0) # endif +#endif /* Debug traces. */ @@ -196,43 +196,43 @@ extern int yydebug; /* Token kinds. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE - enum yytokentype - { - YYEMPTY = -2, - YYEOF = 0, /* "end of file" */ - YYerror = 256, /* error */ - YYUNDEF = 257, /* "invalid token" */ - CHAR = 258, /* CHAR */ - DOT = 259, /* DOT */ - CCL = 260, /* CCL */ - NCCL = 261, /* NCCL */ - OR = 262, /* OR */ - CAT = 263, /* CAT */ - STAR = 264, /* STAR */ - PLUS = 265, /* PLUS */ - QUEST = 266 /* QUEST */ - }; - typedef enum yytokentype yytoken_kind_t; + +enum yytokentype { + YYEMPTY = -2, + YYEOF = 0, /* "end of file" */ + YYerror = 256, /* error */ + YYUNDEF = 257, /* "invalid token" */ + CHAR = 258, /* CHAR */ + DOT = 259, /* DOT */ + CCL = 260, /* CCL */ + NCCL = 261, /* NCCL */ + OR = 262, /* OR */ + CAT = 263, /* CAT */ + STAR = 264, /* STAR */ + PLUS = 265, /* PLUS */ + QUEST = 266 /* QUEST */ +}; +typedef enum yytokentype yytoken_kind_t; #endif /* Token kinds. */ #define YYEMPTY -2 -#define YYEOF 0 +#define YYEOF 0 #define YYerror 256 #define YYUNDEF 257 -#define CHAR 258 -#define DOT 259 -#define CCL 260 -#define NCCL 261 -#define OR 262 -#define CAT 263 -#define STAR 264 -#define PLUS 265 -#define QUEST 266 +#define CHAR 258 +#define DOT 259 +#define CCL 260 +#define NCCL 261 +#define OR 262 +#define CAT 263 +#define STAR 264 +#define PLUS 265 +#define QUEST 266 /* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef int YYSTYPE; -# define YYSTYPE_IS_TRIVIAL 1 +#if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED +typedef int YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif @@ -240,33 +240,30 @@ typedef int YYSTYPE; extern YYSTYPE yylval; -int yyparse (void); - - +int yyparse(void); /* Symbol kind. */ -enum yysymbol_kind_t -{ - YYSYMBOL_YYEMPTY = -2, - YYSYMBOL_YYEOF = 0, /* "end of file" */ - YYSYMBOL_YYerror = 1, /* error */ - YYSYMBOL_YYUNDEF = 2, /* "invalid token" */ - YYSYMBOL_CHAR = 3, /* CHAR */ - YYSYMBOL_DOT = 4, /* DOT */ - YYSYMBOL_CCL = 5, /* CCL */ - YYSYMBOL_NCCL = 6, /* NCCL */ - YYSYMBOL_OR = 7, /* OR */ - YYSYMBOL_CAT = 8, /* CAT */ - YYSYMBOL_STAR = 9, /* STAR */ - YYSYMBOL_PLUS = 10, /* PLUS */ - YYSYMBOL_QUEST = 11, /* QUEST */ - YYSYMBOL_12_ = 12, /* '(' */ - YYSYMBOL_13_ = 13, /* ')' */ - YYSYMBOL_YYACCEPT = 14, /* $accept */ - YYSYMBOL_s = 15, /* s */ - YYSYMBOL_t = 16, /* t */ - YYSYMBOL_b = 17, /* b */ - YYSYMBOL_r = 18 /* r */ +enum yysymbol_kind_t { + YYSYMBOL_YYEMPTY = -2, + YYSYMBOL_YYEOF = 0, /* "end of file" */ + YYSYMBOL_YYerror = 1, /* error */ + YYSYMBOL_YYUNDEF = 2, /* "invalid token" */ + YYSYMBOL_CHAR = 3, /* CHAR */ + YYSYMBOL_DOT = 4, /* DOT */ + YYSYMBOL_CCL = 5, /* CCL */ + YYSYMBOL_NCCL = 6, /* NCCL */ + YYSYMBOL_OR = 7, /* OR */ + YYSYMBOL_CAT = 8, /* CAT */ + YYSYMBOL_STAR = 9, /* STAR */ + YYSYMBOL_PLUS = 10, /* PLUS */ + YYSYMBOL_QUEST = 11, /* QUEST */ + YYSYMBOL_12_ = 12, /* '(' */ + YYSYMBOL_13_ = 13, /* ')' */ + YYSYMBOL_YYACCEPT = 14, /* $accept */ + YYSYMBOL_s = 15, /* s */ + YYSYMBOL_t = 16, /* t */ + YYSYMBOL_b = 17, /* b */ + YYSYMBOL_r = 18 /* r */ }; typedef enum yysymbol_kind_t yysymbol_kind_t; @@ -282,7 +279,7 @@ typedef enum yysymbol_kind_t yysymbol_kind_t; so that the code can choose integer types of a good width. */ #ifndef __PTRDIFF_MAX__ -# include /* INFRINGES ON USER NAME SPACE */ +# include /* INFRINGES ON USER NAME SPACE */ # if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include /* INFRINGES ON USER NAME SPACE */ # define YY_STDINT_H @@ -296,18 +293,18 @@ typedef enum yysymbol_kind_t yysymbol_kind_t; #ifdef __INT_LEAST8_MAX__ typedef __INT_LEAST8_TYPE__ yytype_int8; -#elif defined YY_STDINT_H -typedef int_least8_t yytype_int8; +#elif defined YY_STDINT_H +typedef int_least8_t yytype_int8; #else -typedef signed char yytype_int8; +typedef signed char yytype_int8; #endif #ifdef __INT_LEAST16_MAX__ typedef __INT_LEAST16_TYPE__ yytype_int16; -#elif defined YY_STDINT_H -typedef int_least16_t yytype_int16; +#elif defined YY_STDINT_H +typedef int_least16_t yytype_int16; #else -typedef short yytype_int16; +typedef short yytype_int16; #endif /* Work around bug in HP-UX 11.23, which defines these macros @@ -318,44 +315,42 @@ typedef short yytype_int16; #ifdef __hpux # undef UINT_LEAST8_MAX # undef UINT_LEAST16_MAX -# define UINT_LEAST8_MAX 255 +# define UINT_LEAST8_MAX 255 # define UINT_LEAST16_MAX 65535 #endif -#if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ +#if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ typedef __UINT_LEAST8_TYPE__ yytype_uint8; -#elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ - && UINT_LEAST8_MAX <= INT_MAX) -typedef uint_least8_t yytype_uint8; +#elif(!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H && UINT_LEAST8_MAX <= INT_MAX) +typedef uint_least8_t yytype_uint8; #elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX -typedef unsigned char yytype_uint8; +typedef unsigned char yytype_uint8; #else typedef short yytype_uint8; #endif -#if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ +#if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ typedef __UINT_LEAST16_TYPE__ yytype_uint16; -#elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ - && UINT_LEAST16_MAX <= INT_MAX) +#elif(!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H && UINT_LEAST16_MAX <= INT_MAX) typedef uint_least16_t yytype_uint16; #elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX typedef unsigned short yytype_uint16; #else -typedef int yytype_uint16; +typedef int yytype_uint16; #endif #ifndef YYPTRDIFF_T # if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ -# define YYPTRDIFF_T __PTRDIFF_TYPE__ +# define YYPTRDIFF_T __PTRDIFF_TYPE__ # define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ # elif defined PTRDIFF_MAX # ifndef ptrdiff_t # include /* INFRINGES ON USER NAME SPACE */ # endif -# define YYPTRDIFF_T ptrdiff_t +# define YYPTRDIFF_T ptrdiff_t # define YYPTRDIFF_MAXIMUM PTRDIFF_MAX # else -# define YYPTRDIFF_T long +# define YYPTRDIFF_T long # define YYPTRDIFF_MAXIMUM LONG_MAX # endif #endif @@ -373,13 +368,12 @@ typedef int yytype_uint16; # endif #endif -#define YYSIZE_MAXIMUM \ - YY_CAST (YYPTRDIFF_T, \ - (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ - ? YYPTRDIFF_MAXIMUM \ - : YY_CAST (YYSIZE_T, -1))) +#define YYSIZE_MAXIMUM \ + YY_CAST(YYPTRDIFF_T, \ + (YYPTRDIFF_MAXIMUM < YY_CAST(YYSIZE_T, -1) ? YYPTRDIFF_MAXIMUM : \ + YY_CAST(YYSIZE_T, -1))) -#define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) +#define YYSIZEOF(X) YY_CAST(YYPTRDIFF_T, sizeof(X)) /* Stored state numbers (used for stacks). */ @@ -392,7 +386,7 @@ typedef int yy_state_fast_t; # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ -# define YY_(Msgid) dgettext ("bison-runtime", Msgid) +# define YY_(Msgid) dgettext("bison-runtime", Msgid) # endif # endif # ifndef YY_ @@ -403,7 +397,7 @@ typedef int yy_state_fast_t; #ifndef YY_ATTRIBUTE_PURE # if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) -# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) +# define YY_ATTRIBUTE_PURE __attribute__((__pure__)) # else # define YY_ATTRIBUTE_PURE # endif @@ -411,33 +405,31 @@ typedef int yy_state_fast_t; #ifndef YY_ATTRIBUTE_UNUSED # if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) -# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) +# define YY_ATTRIBUTE_UNUSED __attribute__((__unused__)) # else # define YY_ATTRIBUTE_UNUSED # endif #endif /* Suppress unused-variable warnings by "using" E. */ -#if ! defined lint || defined __GNUC__ -# define YY_USE(E) ((void) (E)) +#if !defined lint || defined __GNUC__ +# define YY_USE(E) ((void)(E)) #else # define YY_USE(E) /* empty */ #endif /* Suppress an incorrect diagnostic about yylval being uninitialized. */ -#if defined __GNUC__ && ! defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__ +#if defined __GNUC__ && !defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__ # if __GNUC__ * 100 + __GNUC_MINOR__ < 407 -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wuninitialized\"") # else -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ - _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wuninitialized\"") \ + _Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # endif -# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ - _Pragma ("GCC diagnostic pop") +# define YY_IGNORE_MAYBE_UNINITIALIZED_END _Pragma("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif @@ -449,12 +441,10 @@ typedef int yy_state_fast_t; # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif -#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ -# define YY_IGNORE_USELESS_CAST_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") -# define YY_IGNORE_USELESS_CAST_END \ - _Pragma ("GCC diagnostic pop") +#if defined __cplusplus && defined __GNUC__ && !defined __ICC && 6 <= __GNUC__ +# define YY_IGNORE_USELESS_CAST_BEGIN \ + _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wuseless-cast\"") +# define YY_IGNORE_USELESS_CAST_END _Pragma("GCC diagnostic pop") #endif #ifndef YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_BEGIN @@ -462,7 +452,7 @@ typedef int yy_state_fast_t; #endif -#define YY_ASSERT(E) ((void) (0 && (E))) +#define YY_ASSERT(E) ((void)(0 && (E))) #if !defined yyoverflow @@ -471,85 +461,84 @@ typedef int yy_state_fast_t; # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ -# define YYSTACK_ALLOC __builtin_alloca +# define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR -# include /* INFRINGES ON USER NAME SPACE */ +# include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX -# define YYSTACK_ALLOC __alloca +# define YYSTACK_ALLOC __alloca # elif defined _MSC_VER -# include /* INFRINGES ON USER NAME SPACE */ -# define alloca _alloca +# include /* INFRINGES ON USER NAME SPACE */ +# define alloca _alloca # else -# define YYSTACK_ALLOC alloca -# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS -# include /* INFRINGES ON USER NAME SPACE */ - /* Use EXIT_SUCCESS as a witness for stdlib.h. */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif +# define YYSTACK_ALLOC alloca +# if !defined _ALLOCA_H && !defined EXIT_SUCCESS +# include /* INFRINGES ON USER NAME SPACE */ +/* Use EXIT_SUCCESS as a witness for stdlib.h. */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif # endif # endif # endif # ifdef YYSTACK_ALLOC - /* Pacify GCC's 'empty if-body' warning. */ -# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) +/* Pacify GCC's 'empty if-body' warning. */ +# define YYSTACK_FREE(Ptr) \ + do { /* empty */ \ + ; \ + } while(0) # ifndef YYSTACK_ALLOC_MAXIMUM - /* The OS might guarantee only one guard page at the bottom of the stack, - and a page size can be as small as 4096 bytes. So we cannot safely - invoke alloca (N) if N exceeds 4096. Use a slightly smaller number - to allow for a few compiler-allocated temporary stack slots. */ +/* The OS might guarantee only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + invoke alloca (N) if N exceeds 4096. Use a slightly smaller number + to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC -# define YYSTACK_FREE YYFREE +# define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif -# if (defined __cplusplus && ! defined EXIT_SUCCESS \ - && ! ((defined YYMALLOC || defined malloc) \ - && (defined YYFREE || defined free))) +# if(defined __cplusplus && !defined EXIT_SUCCESS && \ + !((defined YYMALLOC || defined malloc) && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 +# define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc -# if ! defined malloc && ! defined EXIT_SUCCESS -void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ +# if !defined malloc && !defined EXIT_SUCCESS +void *malloc(YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free -# if ! defined free && ! defined EXIT_SUCCESS -void free (void *); /* INFRINGES ON USER NAME SPACE */ +# if !defined free && !defined EXIT_SUCCESS +void free(void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* !defined yyoverflow */ -#if (! defined yyoverflow \ - && (! defined __cplusplus \ - || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) +#if(!defined yyoverflow && \ + (!defined __cplusplus || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ -union yyalloc -{ - yy_state_t yyss_alloc; - YYSTYPE yyvs_alloc; +union yyalloc { + yy_state_t yyss_alloc; + YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ -# define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) +# define YYSTACK_GAP_MAXIMUM (YYSIZEOF(union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ -# define YYSTACK_BYTES(N) \ - ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ - + YYSTACK_GAP_MAXIMUM) +# define YYSTACK_BYTES(N) \ + ((N) * (YYSIZEOF(yy_state_t) + YYSIZEOF(YYSTYPE)) + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 @@ -558,16 +547,14 @@ union yyalloc elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ -# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ - do \ - { \ - YYPTRDIFF_T yynewbytes; \ - YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ - Stack = &yyptr->Stack_alloc; \ - yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ - yyptr += yynewbytes / YYSIZEOF (*yyptr); \ - } \ - while (0) +# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ + do { \ + YYPTRDIFF_T yynewbytes; \ + YYCOPY(&yyptr->Stack_alloc, Stack, yysize); \ + Stack = &yyptr->Stack_alloc; \ + yynewbytes = yystacksize * YYSIZEOF(*Stack) + YYSTACK_GAP_MAXIMUM; \ + yyptr += yynewbytes / YYSIZEOF(*yyptr); \ + } while(0) #endif @@ -576,239 +563,707 @@ union yyalloc not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ -# define YYCOPY(Dst, Src, Count) \ - __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) +# define YYCOPY(Dst, Src, Count) \ + __builtin_memcpy(Dst, Src, YY_CAST(YYSIZE_T, (Count)) * sizeof(*(Src))) # else -# define YYCOPY(Dst, Src, Count) \ - do \ - { \ - YYPTRDIFF_T yyi; \ - for (yyi = 0; yyi < (Count); yyi++) \ - (Dst)[yyi] = (Src)[yyi]; \ - } \ - while (0) +# define YYCOPY(Dst, Src, Count) \ + do { \ + YYPTRDIFF_T yyi; \ + for(yyi = 0; yyi < (Count); yyi++) \ + (Dst)[yyi] = (Src)[yyi]; \ + } while(0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ -#define YYFINAL 6 +#define YYFINAL 6 /* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 108 +#define YYLAST 108 /* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 14 +#define YYNTOKENS 14 /* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 5 +#define YYNNTS 5 /* YYNRULES -- Number of rules. */ -#define YYNRULES 18 +#define YYNRULES 18 /* YYNSTATES -- Number of states. */ -#define YYNSTATES 25 +#define YYNSTATES 25 /* YYMAXUTOK -- Last valid token kind. */ -#define YYMAXUTOK 266 +#define YYMAXUTOK 266 /* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM as returned by yylex, with out-of-bounds checking. */ -#define YYTRANSLATE(YYX) \ - (0 <= (YYX) && (YYX) <= YYMAXUTOK \ - ? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \ - : YYSYMBOL_YYUNDEF) +#define YYTRANSLATE(YYX) \ + (0 <= (YYX) && (YYX) <= YYMAXUTOK ? YY_CAST(yysymbol_kind_t, yytranslate[YYX]) : \ + YYSYMBOL_YYUNDEF) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex. */ -static const yytype_int8 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, 2, 2, 2, 2, 2, 2, 2, - 12, 13, 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, 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 -}; +static const yytype_int8 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, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 12, + 13, + 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, + 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}; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ -static const yytype_uint8 yyrline[] = -{ - 0, 103, 103, 108, 110, 112, 114, 118, 121, 123, - 125, 127, 131, 133, 135, 137, 139, 141, 143 -}; +static const yytype_uint8 yyrline[] = {0, + 103, + 103, + 108, + 110, + 112, + 114, + 118, + 121, + 123, + 125, + 127, + 131, + 133, + 135, + 137, + 139, + 141, + 143}; #endif /** Accessing symbol of state STATE. */ -#define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State]) +#define YY_ACCESSING_SYMBOL(State) YY_CAST(yysymbol_kind_t, yystos[State]) #if YYDEBUG || 0 /* The user-facing name of the symbol whose (internal) number is YYSYMBOL. No bounds checking. */ -static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED; +static const char *yysymbol_name(yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED; /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ -static const char *const yytname[] = -{ - "\"end of file\"", "error", "\"invalid token\"", "CHAR", "DOT", "CCL", - "NCCL", "OR", "CAT", "STAR", "PLUS", "QUEST", "'('", "')'", "$accept", - "s", "t", "b", "r", YY_NULLPTR -}; - -static const char * -yysymbol_name (yysymbol_kind_t yysymbol) -{ - return yytname[yysymbol]; +static const char *const yytname[] = {"\"end of file\"", + "error", + "\"invalid token\"", + "CHAR", + "DOT", + "CCL", + "NCCL", + "OR", + "CAT", + "STAR", + "PLUS", + "QUEST", + "'('", + "')'", + "$accept", + "s", + "t", + "b", + "r", + YY_NULLPTR}; + +static const char *yysymbol_name(yysymbol_kind_t yysymbol) { + return yytname[yysymbol]; } #endif #define YYPACT_NINF (-5) -#define yypact_value_is_default(Yyn) \ - ((Yyn) == YYPACT_NINF) +#define yypact_value_is_default(Yyn) ((Yyn) == YYPACT_NINF) #define YYTABLE_NINF (-14) -#define yytable_value_is_error(Yyn) \ - 0 +#define yytable_value_is_error(Yyn) 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ -static const yytype_int8 yypact[] = -{ - 2, -5, 3, -5, 1, 1, -5, -5, -5, -5, - -5, -5, 1, 47, 60, 72, 86, -5, -5, -5, - 19, 96, 1, -5, 33 -}; +static const yytype_int8 yypact[] = {2, + -5, + 3, + -5, + 1, + 1, + -5, + -5, + -5, + -5, + -5, + -5, + 1, + 47, + 60, + 72, + 86, + -5, + -5, + -5, + 19, + 96, + 1, + -5, + 33}; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_int8 yydefact[] = -{ - 7, 7, 0, 2, 0, 0, 1, 18, 8, 9, - 10, 11, 0, 0, 0, 0, 0, 14, 15, 16, - 0, 0, 0, 17, 0 -}; + {7, 7, 0, 2, 0, 0, 1, 18, 8, 9, 10, 11, 0, 0, 0, 0, 0, 14, 15, 16, 0, 0, 0, 17, 0}; /* YYPGOTO[NTERM-NUM]. */ -static const yytype_int8 yypgoto[] = -{ - -5, -5, -5, 9, -4 -}; +static const yytype_int8 yypgoto[] = {-5, -5, -5, 9, -4}; /* YYDEFGOTO[NTERM-NUM]. */ -static const yytype_int8 yydefgoto[] = -{ - 0, 2, 3, 4, 20 -}; +static const yytype_int8 yydefgoto[] = {0, 2, 3, 4, 20}; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ -static const yytype_int8 yytable[] = -{ - 13, 14, 7, 6, 8, 9, 10, 11, 15, 1, - 5, 0, 24, 12, 0, 0, 0, 24, 24, -13, - 7, 0, -13, -13, -13, -13, -13, 0, 17, 18, - 19, -13, -13, -12, 7, 0, 8, 9, 10, 11, - -12, 0, 17, 18, 19, 12, -12, -3, 7, 0, - 8, 9, 10, 11, 16, 0, 17, 18, 19, 12, - -5, 7, 0, 8, 9, 10, 11, 21, 0, 17, - 18, 19, 12, 7, 0, 8, 9, 10, 11, 22, - 0, 17, 18, 19, 12, 23, -6, 7, 0, 8, - 9, 10, 11, 0, 0, 0, -4, 7, 12, 8, - 9, 10, 11, 0, 0, 0, 0, 0, 12 -}; - -static const yytype_int8 yycheck[] = -{ - 4, 5, 1, 0, 3, 4, 5, 6, 12, 7, - 1, -1, 16, 12, -1, -1, -1, 21, 22, 0, - 1, -1, 3, 4, 5, 6, 7, -1, 9, 10, - 11, 12, 13, 0, 1, -1, 3, 4, 5, 6, - 7, -1, 9, 10, 11, 12, 13, 0, 1, -1, - 3, 4, 5, 6, 7, -1, 9, 10, 11, 12, - 0, 1, -1, 3, 4, 5, 6, 7, -1, 9, - 10, 11, 12, 1, -1, 3, 4, 5, 6, 7, - -1, 9, 10, 11, 12, 13, 0, 1, -1, 3, - 4, 5, 6, -1, -1, -1, 0, 1, 12, 3, - 4, 5, 6, -1, -1, -1, -1, -1, 12 -}; +static const yytype_int8 yytable[] = {13, + 14, + 7, + 6, + 8, + 9, + 10, + 11, + 15, + 1, + 5, + 0, + 24, + 12, + 0, + 0, + 0, + 24, + 24, + -13, + 7, + 0, + -13, + -13, + -13, + -13, + -13, + 0, + 17, + 18, + 19, + -13, + -13, + -12, + 7, + 0, + 8, + 9, + 10, + 11, + -12, + 0, + 17, + 18, + 19, + 12, + -12, + -3, + 7, + 0, + 8, + 9, + 10, + 11, + 16, + 0, + 17, + 18, + 19, + 12, + -5, + 7, + 0, + 8, + 9, + 10, + 11, + 21, + 0, + 17, + 18, + 19, + 12, + 7, + 0, + 8, + 9, + 10, + 11, + 22, + 0, + 17, + 18, + 19, + 12, + 23, + -6, + 7, + 0, + 8, + 9, + 10, + 11, + 0, + 0, + 0, + -4, + 7, + 12, + 8, + 9, + 10, + 11, + 0, + 0, + 0, + 0, + 0, + 12}; + +static const yytype_int8 yycheck[] = {4, + 5, + 1, + 0, + 3, + 4, + 5, + 6, + 12, + 7, + 1, + -1, + 16, + 12, + -1, + -1, + -1, + 21, + 22, + 0, + 1, + -1, + 3, + 4, + 5, + 6, + 7, + -1, + 9, + 10, + 11, + 12, + 13, + 0, + 1, + -1, + 3, + 4, + 5, + 6, + 7, + -1, + 9, + 10, + 11, + 12, + 13, + 0, + 1, + -1, + 3, + 4, + 5, + 6, + 7, + -1, + 9, + 10, + 11, + 12, + 0, + 1, + -1, + 3, + 4, + 5, + 6, + 7, + -1, + 9, + 10, + 11, + 12, + 1, + -1, + 3, + 4, + 5, + 6, + 7, + -1, + 9, + 10, + 11, + 12, + 13, + 0, + 1, + -1, + 3, + 4, + 5, + 6, + -1, + -1, + -1, + 0, + 1, + 12, + 3, + 4, + 5, + 6, + -1, + -1, + -1, + -1, + -1, + 12}; /* YYSTOS[STATE-NUM] -- The symbol kind of the accessing symbol of state STATE-NUM. */ -static const yytype_int8 yystos[] = -{ - 0, 7, 15, 16, 17, 17, 0, 1, 3, 4, - 5, 6, 12, 18, 18, 18, 7, 9, 10, 11, - 18, 7, 7, 13, 18 -}; +static const yytype_int8 yystos[] = {0, + 7, + 15, + 16, + 17, + 17, + 0, + 1, + 3, + 4, + 5, + 6, + 12, + 18, + 18, + 18, + 7, + 9, + 10, + 11, + 18, + 7, + 7, + 13, + 18}; /* YYR1[RULE-NUM] -- Symbol kind of the left-hand side of rule RULE-NUM. */ static const yytype_int8 yyr1[] = -{ - 0, 14, 15, 16, 16, 16, 16, 17, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18 -}; + {0, 14, 15, 16, 16, 16, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18}; /* YYR2[RULE-NUM] -- Number of symbols on the right-hand side of rule RULE-NUM. */ static const yytype_int8 yyr2[] = -{ - 0, 2, 1, 2, 4, 3, 3, 0, 1, 1, - 1, 1, 3, 2, 2, 2, 2, 3, 1 -}; - + {0, 2, 1, 2, 4, 3, 3, 0, 1, 1, 1, 1, 3, 2, 2, 2, 2, 3, 1}; -enum { YYENOMEM = -2 }; +enum { + YYENOMEM = -2 +}; -#define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) +#define yyerrok (yyerrstatus = 0) +#define yyclearin (yychar = YYEMPTY) -#define YYACCEPT goto yyacceptlab -#define YYABORT goto yyabortlab -#define YYERROR goto yyerrorlab -#define YYNOMEM goto yyexhaustedlab +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab +#define YYNOMEM goto yyexhaustedlab -#define YYRECOVERING() (!!yyerrstatus) +#define YYRECOVERING() (!!yyerrstatus) -#define YYBACKUP(Token, Value) \ - do \ - if (yychar == YYEMPTY) \ - { \ - yychar = (Token); \ - yylval = (Value); \ - YYPOPSTACK (yylen); \ - yystate = *yyssp; \ - goto yybackup; \ - } \ - else \ - { \ - yyerror (YY_("syntax error: cannot back up")); \ - YYERROR; \ - } \ - while (0) +#define YYBACKUP(Token, Value) \ + do \ + if(yychar == YYEMPTY) { \ + yychar = (Token); \ + yylval = (Value); \ + YYPOPSTACK(yylen); \ + yystate = *yyssp; \ + goto yybackup; \ + } else { \ + yyerror(YY_("syntax error: cannot back up")); \ + YYERROR; \ + } \ + while(0) /* Backward compatibility with an undocumented macro. Use YYerror or YYUNDEF. */ @@ -823,58 +1278,50 @@ enum { YYENOMEM = -2 }; # define YYFPRINTF fprintf # endif -# define YYDPRINTF(Args) \ -do { \ - if (yydebug) \ - YYFPRINTF Args; \ -} while (0) +# define YYDPRINTF(Args) \ + do { \ + if(yydebug) YYFPRINTF Args; \ + } while(0) -# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \ -do { \ - if (yydebug) \ - { \ - YYFPRINTF (stderr, "%s ", Title); \ - yy_symbol_print (stderr, \ - Kind, Value); \ - YYFPRINTF (stderr, "\n"); \ - } \ -} while (0) - +# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \ + do { \ + if(yydebug) { \ + YYFPRINTF(stderr, "%s ", Title); \ + yy_symbol_print(stderr, Kind, Value); \ + YYFPRINTF(stderr, "\n"); \ + } \ + } while(0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ -static void -yy_symbol_value_print (FILE *yyo, - yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) -{ - FILE *yyoutput = yyo; - YY_USE (yyoutput); - if (!yyvaluep) - return; - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - YY_USE (yykind); - YY_IGNORE_MAYBE_UNINITIALIZED_END +static void yy_symbol_value_print(FILE *yyo, yysymbol_kind_t yykind, + YYSTYPE const *const yyvaluep) { + FILE *yyoutput = yyo; + YY_USE(yyoutput); + if(!yyvaluep) return; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + YY_USE(yykind); + YY_IGNORE_MAYBE_UNINITIALIZED_END } - /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ -static void -yy_symbol_print (FILE *yyo, - yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) -{ - YYFPRINTF (yyo, "%s %s (", - yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind)); +static void yy_symbol_print(FILE *yyo, yysymbol_kind_t yykind, + YYSTYPE const *const yyvaluep) { + YYFPRINTF(yyo, + "%s %s (", + yykind < YYNTOKENS ? "token" : "nterm", + yysymbol_name(yykind)); - yy_symbol_value_print (yyo, yykind, yyvaluep); - YYFPRINTF (yyo, ")"); + yy_symbol_value_print(yyo, yykind, yyvaluep); + YYFPRINTF(yyo, ")"); } /*------------------------------------------------------------------. @@ -882,60 +1329,49 @@ yy_symbol_print (FILE *yyo, | TOP (included). | `------------------------------------------------------------------*/ -static void -yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) -{ - YYFPRINTF (stderr, "Stack now"); - for (; yybottom <= yytop; yybottom++) - { - int yybot = *yybottom; - YYFPRINTF (stderr, " %d", yybot); - } - YYFPRINTF (stderr, "\n"); +static void yy_stack_print(yy_state_t *yybottom, yy_state_t *yytop) { + YYFPRINTF(stderr, "Stack now"); + for(; yybottom <= yytop; yybottom++) { + int yybot = *yybottom; + YYFPRINTF(stderr, " %d", yybot); + } + YYFPRINTF(stderr, "\n"); } -# define YY_STACK_PRINT(Bottom, Top) \ -do { \ - if (yydebug) \ - yy_stack_print ((Bottom), (Top)); \ -} while (0) - +# define YY_STACK_PRINT(Bottom, Top) \ + do { \ + if(yydebug) yy_stack_print((Bottom), (Top)); \ + } while(0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ -static void -yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, - int yyrule) -{ - int yylno = yyrline[yyrule]; - int yynrhs = yyr2[yyrule]; - int yyi; - YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", - yyrule - 1, yylno); - /* The symbols being reduced. */ - for (yyi = 0; yyi < yynrhs; yyi++) - { - YYFPRINTF (stderr, " $%d = ", yyi + 1); - yy_symbol_print (stderr, - YY_ACCESSING_SYMBOL (+yyssp[yyi + 1 - yynrhs]), - &yyvsp[(yyi + 1) - (yynrhs)]); - YYFPRINTF (stderr, "\n"); - } +static void yy_reduce_print(yy_state_t *yyssp, YYSTYPE *yyvsp, int yyrule) { + int yylno = yyrline[yyrule]; + int yynrhs = yyr2[yyrule]; + int yyi; + YYFPRINTF(stderr, "Reducing stack by rule %d (line %d):\n", yyrule - 1, yylno); + /* The symbols being reduced. */ + for(yyi = 0; yyi < yynrhs; yyi++) { + YYFPRINTF(stderr, " $%d = ", yyi + 1); + yy_symbol_print(stderr, + YY_ACCESSING_SYMBOL(+yyssp[yyi + 1 - yynrhs]), + &yyvsp[(yyi + 1) - (yynrhs)]); + YYFPRINTF(stderr, "\n"); + } } -# define YY_REDUCE_PRINT(Rule) \ -do { \ - if (yydebug) \ - yy_reduce_print (yyssp, yyvsp, Rule); \ -} while (0) +# define YY_REDUCE_PRINT(Rule) \ + do { \ + if(yydebug) yy_reduce_print(yyssp, yyvsp, Rule); \ + } while(0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ -# define YYDPRINTF(Args) ((void) 0) +# define YYDPRINTF(Args) ((void)0) # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) @@ -962,25 +1398,19 @@ int yydebug; - /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ -static void -yydestruct (const char *yymsg, - yysymbol_kind_t yykind, YYSTYPE *yyvaluep) -{ - YY_USE (yyvaluep); - if (!yymsg) - yymsg = "Deleting"; - YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp); - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - YY_USE (yykind); - YY_IGNORE_MAYBE_UNINITIALIZED_END -} +static void yydestruct(const char *yymsg, yysymbol_kind_t yykind, YYSTYPE *yyvaluep) { + YY_USE(yyvaluep); + if(!yymsg) yymsg = "Deleting"; + YY_SYMBOL_PRINT(yymsg, yykind, yyvaluep, yylocationp); + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + YY_USE(yykind); + YY_IGNORE_MAYBE_UNINITIALIZED_END +} /* Lookahead token kind. */ int yychar; @@ -990,1064 +1420,965 @@ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; - - - /*----------. | yyparse. | `----------*/ -int -yyparse (void) -{ - yy_state_fast_t yystate = 0; - /* Number of tokens to shift before error messages enabled. */ - int yyerrstatus = 0; +int yyparse(void) { + yy_state_fast_t yystate = 0; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus = 0; - /* Refer to the stacks through separate pointers, to allow yyoverflow - to reallocate them elsewhere. */ + /* Refer to the stacks through separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ - /* Their size. */ - YYPTRDIFF_T yystacksize = YYINITDEPTH; + /* Their size. */ + YYPTRDIFF_T yystacksize = YYINITDEPTH; - /* The state stack: array, bottom, top. */ - yy_state_t yyssa[YYINITDEPTH]; - yy_state_t *yyss = yyssa; - yy_state_t *yyssp = yyss; + /* The state stack: array, bottom, top. */ + yy_state_t yyssa[YYINITDEPTH]; + yy_state_t *yyss = yyssa; + yy_state_t *yyssp = yyss; - /* The semantic value stack: array, bottom, top. */ - YYSTYPE yyvsa[YYINITDEPTH]; - YYSTYPE *yyvs = yyvsa; - YYSTYPE *yyvsp = yyvs; + /* The semantic value stack: array, bottom, top. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs = yyvsa; + YYSTYPE *yyvsp = yyvs; - int yyn; - /* The return value of yyparse. */ - int yyresult; - /* Lookahead symbol kind. */ - yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; - /* The variables used to return semantic value and location from the - action routines. */ - YYSTYPE yyval; + int yyn; + /* The return value of yyparse. */ + int yyresult; + /* Lookahead symbol kind. */ + yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; -#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) - /* The number of symbols on the RHS of the reduced rule. - Keep to zero when no symbol should be popped. */ - int yylen = 0; + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; - YYDPRINTF ((stderr, "Starting parse\n")); + YYDPRINTF((stderr, "Starting parse\n")); - yychar = YYEMPTY; /* Cause a token to be read. */ + yychar = YYEMPTY; /* Cause a token to be read. */ - goto yysetstate; + goto yysetstate; /*------------------------------------------------------------. | yynewstate -- push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: - /* In all cases, when you get here, the value and location stacks - have just been pushed. So pushing a state here evens the stacks. */ - yyssp++; + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; /*--------------------------------------------------------------------. | yysetstate -- set current state (the top of the stack) to yystate. | `--------------------------------------------------------------------*/ yysetstate: - YYDPRINTF ((stderr, "Entering state %d\n", yystate)); - YY_ASSERT (0 <= yystate && yystate < YYNSTATES); - YY_IGNORE_USELESS_CAST_BEGIN - *yyssp = YY_CAST (yy_state_t, yystate); - YY_IGNORE_USELESS_CAST_END - YY_STACK_PRINT (yyss, yyssp); - - if (yyss + yystacksize - 1 <= yyssp) + YYDPRINTF((stderr, "Entering state %d\n", yystate)); + YY_ASSERT(0 <= yystate && yystate < YYNSTATES); + YY_IGNORE_USELESS_CAST_BEGIN + *yyssp = YY_CAST(yy_state_t, yystate); + YY_IGNORE_USELESS_CAST_END + YY_STACK_PRINT(yyss, yyssp); + + if(yyss + yystacksize - 1 <= yyssp) #if !defined yyoverflow && !defined YYSTACK_RELOCATE - YYNOMEM; + YYNOMEM; #else - { - /* Get the current used size of the three stacks, in elements. */ - YYPTRDIFF_T yysize = yyssp - yyss + 1; + { + /* Get the current used size of the three stacks, in elements. */ + YYPTRDIFF_T yysize = yyssp - yyss + 1; # if defined yyoverflow - { - /* Give user a chance to reallocate the stack. Use copies of - these so that the &'s don't force the real ones into - memory. */ - yy_state_t *yyss1 = yyss; - YYSTYPE *yyvs1 = yyvs; - - /* Each stack pointer address is followed by the size of the - data in use in that stack, in bytes. This used to be a - conditional around just the two extra args, but that might - be undefined if yyoverflow is a macro. */ - yyoverflow (YY_("memory exhausted"), - &yyss1, yysize * YYSIZEOF (*yyssp), - &yyvs1, yysize * YYSIZEOF (*yyvsp), - &yystacksize); - yyss = yyss1; - yyvs = yyvs1; - } + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + yy_state_t *yyss1 = yyss; + YYSTYPE *yyvs1 = yyvs; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow(YY_("memory exhausted"), + &yyss1, + yysize * YYSIZEOF(*yyssp), + &yyvs1, + yysize * YYSIZEOF(*yyvsp), + &yystacksize); + yyss = yyss1; + yyvs = yyvs1; + } # else /* defined YYSTACK_RELOCATE */ - /* Extend the stack our own way. */ - if (YYMAXDEPTH <= yystacksize) - YYNOMEM; - yystacksize *= 2; - if (YYMAXDEPTH < yystacksize) - yystacksize = YYMAXDEPTH; - - { - yy_state_t *yyss1 = yyss; - union yyalloc *yyptr = - YY_CAST (union yyalloc *, - YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); - if (! yyptr) - YYNOMEM; - YYSTACK_RELOCATE (yyss_alloc, yyss); - YYSTACK_RELOCATE (yyvs_alloc, yyvs); + /* Extend the stack our own way. */ + if(YYMAXDEPTH <= yystacksize) YYNOMEM; + yystacksize *= 2; + if(YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; + + { + yy_state_t *yyss1 = yyss; + union yyalloc *yyptr = YY_CAST(union yyalloc *, + YYSTACK_ALLOC(YY_CAST(YYSIZE_T, YYSTACK_BYTES(yystacksize)))); + if(!yyptr) YYNOMEM; + YYSTACK_RELOCATE(yyss_alloc, yyss); + YYSTACK_RELOCATE(yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE - if (yyss1 != yyssa) - YYSTACK_FREE (yyss1); - } + if(yyss1 != yyssa) YYSTACK_FREE(yyss1); + } # endif - yyssp = yyss + yysize - 1; - yyvsp = yyvs + yysize - 1; + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; - YY_IGNORE_USELESS_CAST_BEGIN - YYDPRINTF ((stderr, "Stack size increased to %ld\n", - YY_CAST (long, yystacksize))); - YY_IGNORE_USELESS_CAST_END + YY_IGNORE_USELESS_CAST_BEGIN + YYDPRINTF((stderr, "Stack size increased to %ld\n", YY_CAST(long, yystacksize))); + YY_IGNORE_USELESS_CAST_END - if (yyss + yystacksize - 1 <= yyssp) - YYABORT; - } + if(yyss + yystacksize - 1 <= yyssp) YYABORT; + } #endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ - if (yystate == YYFINAL) - YYACCEPT; + if(yystate == YYFINAL) YYACCEPT; - goto yybackup; + goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - - /* First try to decide what to do without reference to lookahead token. */ - yyn = yypact[yystate]; - if (yypact_value_is_default (yyn)) - goto yydefault; - - /* Not known => get a lookahead token if don't already have one. */ - - /* YYCHAR is either empty, or end-of-input, or a valid lookahead. */ - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token\n")); - yychar = yylex (); - } - - if (yychar <= YYEOF) - { - yychar = YYEOF; - yytoken = YYSYMBOL_YYEOF; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else if (yychar == YYerror) - { - /* The scanner already issued an error message, process directly - to error recovery. But do not keep the error token as - lookahead, it is too special and may lead us to an endless - loop in error recovery. */ - yychar = YYUNDEF; - yytoken = YYSYMBOL_YYerror; - goto yyerrlab1; - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); - } - - /* If the proper action on seeing token YYTOKEN is to reduce or to - detect an error, take that action. */ - yyn += yytoken; - if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) - goto yydefault; - yyn = yytable[yyn]; - if (yyn <= 0) - { - if (yytable_value_is_error (yyn)) - goto yyerrlab; - yyn = -yyn; - goto yyreduce; - } - - /* Count tokens shifted since error; after three, turn off error - status. */ - if (yyerrstatus) - yyerrstatus--; - - /* Shift the lookahead token. */ - YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); - yystate = yyn; - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - /* Discard the shifted token. */ - yychar = YYEMPTY; - goto yynewstate; + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if(yypact_value_is_default(yyn)) goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either empty, or end-of-input, or a valid lookahead. */ + if(yychar == YYEMPTY) { + YYDPRINTF((stderr, "Reading a token\n")); + yychar = yylex(); + } + + if(yychar <= YYEOF) { + yychar = YYEOF; + yytoken = YYSYMBOL_YYEOF; + YYDPRINTF((stderr, "Now at end of input.\n")); + } else if(yychar == YYerror) { + /* The scanner already issued an error message, process directly + to error recovery. But do not keep the error token as + lookahead, it is too special and may lead us to an endless + loop in error recovery. */ + yychar = YYUNDEF; + yytoken = YYSYMBOL_YYerror; + goto yyerrlab1; + } else { + yytoken = YYTRANSLATE(yychar); + YY_SYMBOL_PRINT("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if(yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; + yyn = yytable[yyn]; + if(yyn <= 0) { + if(yytable_value_is_error(yyn)) goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if(yyerrstatus) yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT("Shifting", yytoken, &yylval, &yylloc); + yystate = yyn; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + /* Discard the shifted token. */ + yychar = YYEMPTY; + goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: - yyn = yydefact[yystate]; - if (yyn == 0) - goto yyerrlab; - goto yyreduce; + yyn = yydefact[yystate]; + if(yyn == 0) goto yyerrlab; + goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: - /* yyn is the number of a rule to reduce with. */ - yylen = yyr2[yyn]; + /* yyn is the number of a rule to reduce with. */ + yylen = yyr2[yyn]; - /* If YYLEN is nonzero, implement the default value of the action: - '$$ = $1'. + /* If YYLEN is nonzero, implement the default value of the action: + '$$ = $1'. - Otherwise, the following line sets YYVAL to garbage. - This behavior is undocumented and Bison - users should not rely upon it. Assigning to YYVAL - unconditionally makes the parser a bit smaller, and it avoids a - GCC warning that YYVAL may be used uninitialized. */ - yyval = yyvsp[1-yylen]; + Otherwise, the following line sets YYVAL to garbage. + This behavior is undocumented and Bison + users should not rely upon it. Assigning to YYVAL + unconditionally makes the parser a bit smaller, and it avoids a + GCC warning that YYVAL may be used uninitialized. */ + yyval = yyvsp[1 - yylen]; - YY_REDUCE_PRINT (yyn); - switch (yyn) - { - case 2: /* s: t */ + YY_REDUCE_PRINT(yyn); + switch(yyn) { + case 2: /* s: t */ #line 104 "src/egrep.y" - { unary(FINAL, yyvsp[0]); - line--; - } + { + unary(FINAL, yyvsp[0]); + line--; + } #line 1248 "y.tab.c" - break; + break; - case 3: /* t: b r */ + case 3: /* t: b r */ #line 109 "src/egrep.y" - { yyval = node(CAT, yyvsp[-1], yyvsp[0]); } + { yyval = node(CAT, yyvsp[-1], yyvsp[0]); } #line 1254 "y.tab.c" - break; + break; - case 4: /* t: OR b r OR */ + case 4: /* t: OR b r OR */ #line 111 "src/egrep.y" - { yyval = node(CAT, yyvsp[-2], yyvsp[-1]); } + { yyval = node(CAT, yyvsp[-2], yyvsp[-1]); } #line 1260 "y.tab.c" - break; + break; - case 5: /* t: OR b r */ + case 5: /* t: OR b r */ #line 113 "src/egrep.y" - { yyval = node(CAT, yyvsp[-1], yyvsp[0]); } + { yyval = node(CAT, yyvsp[-1], yyvsp[0]); } #line 1266 "y.tab.c" - break; + break; - case 6: /* t: b r OR */ + case 6: /* t: b r OR */ #line 115 "src/egrep.y" - { yyval = node(CAT, yyvsp[-2], yyvsp[-1]); } + { yyval = node(CAT, yyvsp[-2], yyvsp[-1]); } #line 1272 "y.tab.c" - break; + break; - case 7: /* b: %empty */ + case 7: /* b: %empty */ #line 118 "src/egrep.y" - { yyval = enter(DOT); - yyval = unary(STAR, yyval); } + { + yyval = enter(DOT); + yyval = unary(STAR, yyval); + } #line 1279 "y.tab.c" - break; + break; - case 8: /* r: CHAR */ + case 8: /* r: CHAR */ #line 122 "src/egrep.y" - { yyval = enter(yyvsp[0]); } + { yyval = enter(yyvsp[0]); } #line 1285 "y.tab.c" - break; + break; - case 9: /* r: DOT */ + case 9: /* r: DOT */ #line 124 "src/egrep.y" - { yyval = enter(DOT); } + { yyval = enter(DOT); } #line 1291 "y.tab.c" - break; + break; - case 10: /* r: CCL */ + case 10: /* r: CCL */ #line 126 "src/egrep.y" - { yyval = cclenter(CCL); } + { yyval = cclenter(CCL); } #line 1297 "y.tab.c" - break; + break; - case 11: /* r: NCCL */ + case 11: /* r: NCCL */ #line 128 "src/egrep.y" - { yyval = cclenter(NCCL); } + { yyval = cclenter(NCCL); } #line 1303 "y.tab.c" - break; + break; - case 12: /* r: r OR r */ + case 12: /* r: r OR r */ #line 132 "src/egrep.y" - { yyval = node(OR, yyvsp[-2], yyvsp[0]); } + { yyval = node(OR, yyvsp[-2], yyvsp[0]); } #line 1309 "y.tab.c" - break; + break; - case 13: /* r: r r */ + case 13: /* r: r r */ #line 134 "src/egrep.y" - { yyval = node(CAT, yyvsp[-1], yyvsp[0]); } + { yyval = node(CAT, yyvsp[-1], yyvsp[0]); } #line 1315 "y.tab.c" - break; + break; - case 14: /* r: r STAR */ + case 14: /* r: r STAR */ #line 136 "src/egrep.y" - { yyval = unary(STAR, yyvsp[-1]); } + { yyval = unary(STAR, yyvsp[-1]); } #line 1321 "y.tab.c" - break; + break; - case 15: /* r: r PLUS */ + case 15: /* r: r PLUS */ #line 138 "src/egrep.y" - { yyval = unary(PLUS, yyvsp[-1]); } + { yyval = unary(PLUS, yyvsp[-1]); } #line 1327 "y.tab.c" - break; + break; - case 16: /* r: r QUEST */ + case 16: /* r: r QUEST */ #line 140 "src/egrep.y" - { yyval = unary(QUEST, yyvsp[-1]); } + { yyval = unary(QUEST, yyvsp[-1]); } #line 1333 "y.tab.c" - break; + break; - case 17: /* r: '(' r ')' */ + case 17: /* r: '(' r ')' */ #line 142 "src/egrep.y" - { yyval = yyvsp[-1]; } + { yyval = yyvsp[-1]; } #line 1339 "y.tab.c" - break; + break; #line 1343 "y.tab.c" - default: break; - } - /* User semantic actions sometimes alter yychar, and that requires - that yytoken be updated with the new translation. We take the - approach of translating immediately before every use of yytoken. - One alternative is translating here after every semantic action, - but that translation would be missed if the semantic action invokes - YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or - if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an - incorrect destructor might then be invoked immediately. In the - case of YYERROR or YYBACKUP, subsequent parser actions might lead - to an incorrect destructor call or verbose syntax error message - before the lookahead is translated. */ - YY_SYMBOL_PRINT ("-> $$ =", YY_CAST (yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc); - - YYPOPSTACK (yylen); - yylen = 0; - - *++yyvsp = yyval; - - /* 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. */ - { - const int yylhs = yyr1[yyn] - YYNTOKENS; - const int yyi = yypgoto[yylhs] + *yyssp; - yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp - ? yytable[yyi] - : yydefgoto[yylhs]); - } - - goto yynewstate; + default: + break; + } + /* User semantic actions sometimes alter yychar, and that requires + that yytoken be updated with the new translation. We take the + approach of translating immediately before every use of yytoken. + One alternative is translating here after every semantic action, + but that translation would be missed if the semantic action invokes + YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or + if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an + incorrect destructor might then be invoked immediately. In the + case of YYERROR or YYBACKUP, subsequent parser actions might lead + to an incorrect destructor call or verbose syntax error message + before the lookahead is translated. */ + YY_SYMBOL_PRINT("-> $$ =", YY_CAST(yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc); + + YYPOPSTACK(yylen); + yylen = 0; + + *++yyvsp = yyval; + + /* 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. */ + { + const int yylhs = yyr1[yyn] - YYNTOKENS; + const int yyi = yypgoto[yylhs] + *yyssp; + yystate = + (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : + yydefgoto[yylhs]); + } + + goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar); - /* If not already recovering from an error, report this error. */ - if (!yyerrstatus) - { - ++yynerrs; - yyerror (YY_("syntax error")); - } - - if (yyerrstatus == 3) - { - /* If just tried and failed to reuse lookahead token after an - error, discard it. */ - - if (yychar <= YYEOF) - { - /* Return failure if at end of input. */ - if (yychar == YYEOF) - YYABORT; - } - else - { - yydestruct ("Error: discarding", - yytoken, &yylval); - yychar = YYEMPTY; - } - } - - /* Else will try to reuse lookahead token after shifting the error - token. */ - goto yyerrlab1; + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE(yychar); + /* If not already recovering from an error, report this error. */ + if(!yyerrstatus) { + ++yynerrs; + yyerror(YY_("syntax error")); + } + + if(yyerrstatus == 3) { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + if(yychar <= YYEOF) { + /* Return failure if at end of input. */ + if(yychar == YYEOF) YYABORT; + } else { + yydestruct("Error: discarding", yytoken, &yylval); + yychar = YYEMPTY; + } + } + + /* Else will try to reuse lookahead token after shifting the error + token. */ + goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: - /* Pacify compilers when the user code never invokes YYERROR and the - label yyerrorlab therefore never appears in user code. */ - if (0) - YYERROR; - ++yynerrs; + /* Pacify compilers when the user code never invokes YYERROR and the + label yyerrorlab therefore never appears in user code. */ + if(0) YYERROR; + ++yynerrs; - /* Do not reclaim the symbols of the rule whose action triggered - this YYERROR. */ - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - yystate = *yyssp; - goto yyerrlab1; + /* Do not reclaim the symbols of the rule whose action triggered + this YYERROR. */ + YYPOPSTACK(yylen); + yylen = 0; + YY_STACK_PRINT(yyss, yyssp); + yystate = *yyssp; + goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: - yyerrstatus = 3; /* Each real token shifted decrements this. */ - - /* Pop stack until we find a state that shifts the error token. */ - for (;;) - { - yyn = yypact[yystate]; - if (!yypact_value_is_default (yyn)) - { - yyn += YYSYMBOL_YYerror; - if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror) - { - yyn = yytable[yyn]; - if (0 < yyn) - break; - } - } + yyerrstatus = 3; /* Each real token shifted decrements this. */ + + /* Pop stack until we find a state that shifts the error token. */ + for(;;) { + yyn = yypact[yystate]; + if(!yypact_value_is_default(yyn)) { + yyn += YYSYMBOL_YYerror; + if(0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror) { + yyn = yytable[yyn]; + if(0 < yyn) break; + } + } - /* Pop the current state because it cannot handle the error token. */ - if (yyssp == yyss) - YYABORT; + /* Pop the current state because it cannot handle the error token. */ + if(yyssp == yyss) YYABORT; - yydestruct ("Error: popping", - YY_ACCESSING_SYMBOL (yystate), yyvsp); - YYPOPSTACK (1); - yystate = *yyssp; - YY_STACK_PRINT (yyss, yyssp); - } + yydestruct("Error: popping", YY_ACCESSING_SYMBOL(yystate), yyvsp); + YYPOPSTACK(1); + yystate = *yyssp; + YY_STACK_PRINT(yyss, yyssp); + } - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END - /* Shift the error token. */ - YY_SYMBOL_PRINT ("Shifting", YY_ACCESSING_SYMBOL (yyn), yyvsp, yylsp); + /* Shift the error token. */ + YY_SYMBOL_PRINT("Shifting", YY_ACCESSING_SYMBOL(yyn), yyvsp, yylsp); - yystate = yyn; - goto yynewstate; + yystate = yyn; + goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: - yyresult = 0; - goto yyreturnlab; + yyresult = 0; + goto yyreturnlab; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: - yyresult = 1; - goto yyreturnlab; + yyresult = 1; + goto yyreturnlab; /*-----------------------------------------------------------. | yyexhaustedlab -- YYNOMEM (memory exhaustion) comes here. | `-----------------------------------------------------------*/ yyexhaustedlab: - yyerror (YY_("memory exhausted")); - yyresult = 2; - goto yyreturnlab; + yyerror(YY_("memory exhausted")); + yyresult = 2; + goto yyreturnlab; /*----------------------------------------------------------. | yyreturnlab -- parsing is finished, clean up and return. | `----------------------------------------------------------*/ yyreturnlab: - if (yychar != YYEMPTY) - { - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = YYTRANSLATE (yychar); - yydestruct ("Cleanup: discarding lookahead", - yytoken, &yylval); - } - /* Do not reclaim the symbols of the rule whose action triggered - this YYABORT or YYACCEPT. */ - YYPOPSTACK (yylen); - YY_STACK_PRINT (yyss, yyssp); - while (yyssp != yyss) - { - yydestruct ("Cleanup: popping", - YY_ACCESSING_SYMBOL (+*yyssp), yyvsp); - YYPOPSTACK (1); - } + if(yychar != YYEMPTY) { + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = YYTRANSLATE(yychar); + yydestruct("Cleanup: discarding lookahead", yytoken, &yylval); + } + /* Do not reclaim the symbols of the rule whose action triggered + this YYABORT or YYACCEPT. */ + YYPOPSTACK(yylen); + YY_STACK_PRINT(yyss, yyssp); + while(yyssp != yyss) { + yydestruct("Cleanup: popping", YY_ACCESSING_SYMBOL(+*yyssp), yyvsp); + YYPOPSTACK(1); + } #ifndef yyoverflow - if (yyss != yyssa) - YYSTACK_FREE (yyss); + if(yyss != yyssa) YYSTACK_FREE(yyss); #endif - return yyresult; + return yyresult; } #line 146 "src/egrep.y" -static int -yyerror(char *s) -{ +static int yyerror(char *s) { message = s; longjmp(env, 1); - return 1; /* silence a warning */ + return 1; /* silence a warning */ } -static int -yylex(void) -{ - int cclcnt, x; - char c, d; - - switch(c = nextch()) { - case '|': - case '\n': - return (OR); - case '*': - return (STAR); - case '+': - return (PLUS); - case '?': - return (QUEST); - case '(': - case ')': - return (c); - case '.': - return (DOT); - case '\0': - return (0); - case '[': - x = CCL; - cclcnt = 0; - count = nxtchar++; - if ((c = nextch()) == '^') { - x = NCCL; - c = nextch(); +static int yylex(void) { + int cclcnt, x; + char c, d; + + switch(c = nextch()) { + case '|': + case '\n': + return (OR); + case '*': + return (STAR); + case '+': + return (PLUS); + case '?': + return (QUEST); + case '(': + case ')': + return (c); + case '.': + return (DOT); + case '\0': + return (0); + case '[': + x = CCL; + cclcnt = 0; + count = nxtchar++; + if((c = nextch()) == '^') { + x = NCCL; + c = nextch(); + } + do { + if(c == '\0') synerror(); + if((c == '-') && (cclcnt > 0) && (chars[nxtchar - 1] != 0)) { + if((d = nextch()) != 0) { + c = chars[nxtchar - 1]; + while((unsigned int)c < (unsigned int)d) { + if(nxtchar >= MAXLIN) overflo(); + chars[nxtchar++] = ++c; + cclcnt++; + } + continue; + } /* if() */ + } /* if() */ + if(nxtchar >= MAXLIN) overflo(); + chars[nxtchar++] = c; + cclcnt++; + } while((c = nextch()) != ']'); + chars[count] = cclcnt; + return (x); + case '\\': + if((c = nextch()) == '\0') synerror(); + yylval = c; + return (CHAR); + case '$': + case '^': + c = '\n'; + yylval = c; + return (CHAR); + default: + yylval = c; + return (CHAR); } - do { - if (c == '\0') - synerror(); - if ( (c == '-') - && (cclcnt > 0) - && (chars[nxtchar-1] != 0) - ) { - if ((d = nextch()) != 0) { - c = chars[nxtchar-1]; - while ((unsigned int)c < (unsigned int)d) { - if (nxtchar >= MAXLIN) - overflo(); - chars[nxtchar++] = ++c; - cclcnt++; - } - continue; - } /* if() */ - } /* if() */ - if (nxtchar >= MAXLIN) - overflo(); - chars[nxtchar++] = c; - cclcnt++; - } while ((c = nextch()) != ']'); - chars[count] = cclcnt; - return (x); - case '\\': - if ((c = nextch()) == '\0') - synerror(); - yylval = c; - return (CHAR); - case '$': - case '^': - c = '\n'; - yylval = c; - return (CHAR); - default: - yylval = c; - return (CHAR); - } } -static void -synerror(void) -{ - yyerror("Syntax error"); +static void synerror(void) { + yyerror("Syntax error"); } -static unsigned int -enter(int x) -{ - if(line >= MAXLIN) - overflo(); - name[line] = x; - left[line] = 0; - right[line] = 0; - return(line++); +static unsigned int enter(int x) { + if(line >= MAXLIN) overflo(); + name[line] = x; + left[line] = 0; + right[line] = 0; + return (line++); } -static unsigned int -cclenter(int x) -{ - unsigned int linno; +static unsigned int cclenter(int x) { + unsigned int linno; - linno = enter(x); - right[linno] = count; - return (linno); + linno = enter(x); + right[linno] = count; + return (linno); } -static int -node(int x, int l, int r) -{ - if(line >= MAXLIN) - overflo(); - name[line] = x; - left[line] = l; - right[line] = r; - parent[l] = line; - parent[r] = line; - return(line++); +static int node(int x, int l, int r) { + if(line >= MAXLIN) overflo(); + name[line] = x; + left[line] = l; + right[line] = r; + parent[l] = line; + parent[r] = line; + return (line++); } -static int -unary(int x, int d) -{ - if(line >= MAXLIN) - overflo(); - name[line] = x; - left[line] = d; - right[line] = 0; - parent[d] = line; - return(line++); +static int unary(int x, int d) { + if(line >= MAXLIN) overflo(); + name[line] = x; + left[line] = d; + right[line] = 0; + parent[d] = line; + return (line++); } -static void -overflo(void) -{ - yyerror("internal table overflow"); +static void overflo(void) { + yyerror("internal table overflow"); } -static void -cfoll(int v) -{ - unsigned int i; - - if (left[v] == 0) { - count = 0; - for (i = 1; i <= line; i++) - tmpstat[i] = 0; - follow(v); - add(foll, v); - } else if (right[v] == 0) - cfoll(left[v]); - else { - cfoll(left[v]); - cfoll(right[v]); - } +static void cfoll(int v) { + unsigned int i; + + if(left[v] == 0) { + count = 0; + for(i = 1; i <= line; i++) + tmpstat[i] = 0; + follow(v); + add(foll, v); + } else if(right[v] == 0) + cfoll(left[v]); + else { + cfoll(left[v]); + cfoll(right[v]); + } } -static void -cgotofn(void) -{ - unsigned int i, n, s; - int c, k; - char symbol[NCHARS]; - unsigned int j, l, pc, pos; - unsigned int nc; - int curpos; - unsigned int num, number, newpos; - - count = 0; - for (n=3; n<=line; n++) - tmpstat[n] = 0; - if (cstate(line-1)==0) { - tmpstat[line] = 1; - count++; - out[0] = 1; - } - for (n=3; n<=line; n++) - initstat[n] = tmpstat[n]; - count--; /*leave out position 1 */ - icount = count; - tmpstat[1] = 0; - add(state, 0); - n = 0; - for (s = 0; s <= n; s++) { - if (out[s] == 1) - continue; - for (i = 0; i < NCHARS; i++) - symbol[i] = 0; - num = positions[state[s]]; - count = icount; - for (i = 3; i <= line; i++) - tmpstat[i] = initstat[i]; - pos = state[s] + 1; - for (i = 0; i < num; i++) { - curpos = positions[pos]; - if ((c = name[curpos]) >= 0) { - if (c < NCHARS) { - symbol[c] = 1; - } else if (c == DOT) { - for (k = 0; k < NCHARS; k++) - if (k != '\n') - symbol[k] = 1; - } else if (c == CCL) { - nc = chars[right[curpos]]; - pc = right[curpos] + 1; - for (j = 0; j < nc; j++) - symbol[(unsigned char)chars[pc++]] = 1; - } else if (c == NCCL) { - nc = chars[right[curpos]]; - for (j = 0; j < NCHARS; j++) { - pc = right[curpos] + 1; - for (l = 0; l < nc; l++) - if (j==(unsigned char)chars[pc++]) - goto cont; - if (j != '\n') - symbol[j] = 1; - cont: - ; - } - } - } - pos++; - } /* for (i) */ - for (c=0; c= 0) - if ((k == c) - || (k == DOT) - || (k == CCL && member(c, right[curpos], 1)) - || (k == NCCL && member(c, right[curpos], 0)) - ) { - number = positions[foll[curpos]]; - newpos = foll[curpos] + 1; - for (j = 0; j < number; j++) { - if (tmpstat[positions[newpos]] != 1) { - tmpstat[positions[newpos]] = 1; - count++; + for(i = 0; i < num; i++) { + curpos = positions[pos]; + if((c = name[curpos]) >= 0) { + if(c < NCHARS) { + symbol[c] = 1; + } else if(c == DOT) { + for(k = 0; k < NCHARS; k++) + if(k != '\n') symbol[k] = 1; + } else if(c == CCL) { + nc = chars[right[curpos]]; + pc = right[curpos] + 1; + for(j = 0; j < nc; j++) + symbol[(unsigned char)chars[pc++]] = 1; + } else if(c == NCCL) { + nc = chars[right[curpos]]; + for(j = 0; j < NCHARS; j++) { + pc = right[curpos] + 1; + for(l = 0; l < nc; l++) + if(j == (unsigned char)chars[pc++]) goto cont; + if(j != '\n') symbol[j] = 1; + cont:; + } } - newpos++; - } } - pos++; - } /* end nextstate */ - if (notin(n)) { - if (n >= NSTATES) - overflo(); - add(state, ++n); - if (tmpstat[line] == 1) - out[n] = 1; - gotofn[s][c] = n; - } else { - gotofn[s][c] = xstate; - } - } /* if (symbol) */ - } /* for(c) */ - } /* for(s) */ + pos++; + } /* for (i) */ + for(c = 0; c < NCHARS; c++) { + if(symbol[c] == 1) { + /* nextstate(s,c) */ + count = icount; + for(i = 3; i <= line; i++) + tmpstat[i] = initstat[i]; + pos = state[s] + 1; + for(i = 0; i < num; i++) { + curpos = positions[pos]; + if((k = name[curpos]) >= 0) + if((k == c) || (k == DOT) || + (k == CCL && member(c, right[curpos], 1)) || + (k == NCCL && member(c, right[curpos], 0))) { + number = positions[foll[curpos]]; + newpos = foll[curpos] + 1; + for(j = 0; j < number; j++) { + if(tmpstat[positions[newpos]] != 1) { + tmpstat[positions[newpos]] = 1; + count++; + } + newpos++; + } + } + pos++; + } /* end nextstate */ + if(notin(n)) { + if(n >= NSTATES) overflo(); + add(state, ++n); + if(tmpstat[line] == 1) out[n] = 1; + gotofn[s][c] = n; + } else { + gotofn[s][c] = xstate; + } + } /* if (symbol) */ + } /* for(c) */ + } /* for(s) */ } -static int -cstate(int v) -{ +static int cstate(int v) { int b; - if (left[v] == 0) { - if (tmpstat[v] != 1) { + if(left[v] == 0) { + if(tmpstat[v] != 1) { tmpstat[v] = 1; count++; } - return(1); - } - else if (right[v] == 0) { - if (cstate(left[v]) == 0) return (0); - else if (name[v] == PLUS) return (1); - else return (0); - } - else if (name[v] == CAT) { - if (cstate(left[v]) == 0 && cstate(right[v]) == 0) return (0); - else return (1); - } - else { /* name[v] == OR */ + return (1); + } else if(right[v] == 0) { + if(cstate(left[v]) == 0) + return (0); + else if(name[v] == PLUS) + return (1); + else + return (0); + } else if(name[v] == CAT) { + if(cstate(left[v]) == 0 && cstate(right[v]) == 0) + return (0); + else + return (1); + } else { /* name[v] == OR */ b = cstate(right[v]); - if (cstate(left[v]) == 0 || b == 0) return (0); - else return (1); + if(cstate(left[v]) == 0 || b == 0) + return (0); + else + return (1); } } -static int -member(int symb, int set, int torf) -{ - unsigned int i, num, pos; - - num = chars[set]; - pos = set + 1; - for (i = 0; i < num; i++) - if (symb == (unsigned char)(chars[pos++])) - return (torf); - return (!torf); +static int member(int symb, int set, int torf) { + unsigned int i, num, pos; + + num = chars[set]; + pos = set + 1; + for(i = 0; i < num; i++) + if(symb == (unsigned char)(chars[pos++])) return (torf); + return (!torf); } -static int -notin(int n) -{ +static int notin(int n) { int i, j, pos; - for (i=0; i<=n; i++) { - if (positions[state[i]] == count) { + for(i = 0; i <= n; i++) { + if(positions[state[i]] == count) { pos = state[i] + 1; - for (j=0; j < count; j++) - if (tmpstat[positions[pos++]] != 1) goto nxt; + for(j = 0; j < count; j++) + if(tmpstat[positions[pos++]] != 1) goto nxt; xstate = i; return (0); } - nxt: ; + nxt:; } return (1); } -static void -add(int *array, int n) -{ - unsigned int i; - - if (nxtpos + count > MAXPOS) - overflo(); - array[n] = nxtpos; - positions[nxtpos++] = count; - for (i=3; i <= line; i++) { - if (tmpstat[i] == 1) { - positions[nxtpos++] = i; +static void add(int *array, int n) { + unsigned int i; + + if(nxtpos + count > MAXPOS) overflo(); + array[n] = nxtpos; + positions[nxtpos++] = count; + for(i = 3; i <= line; i++) { + if(tmpstat[i] == 1) { positions[nxtpos++] = i; } } - } } -static void -follow(unsigned int v) -{ - unsigned int p; - - if (v == line) - return; - p = parent[v]; - switch(name[p]) { - case STAR: - case PLUS: cstate(v); - follow(p); - return; - - case OR: - case QUEST: follow(p); - return; - - case CAT: - if (v == left[p]) { - if (cstate(right[p]) == 0) { - follow(p); - return; - } - } else - follow(p); - return; - case FINAL: - if (tmpstat[line] != 1) { - tmpstat[line] = 1; - count++; +static void follow(unsigned int v) { + unsigned int p; + + if(v == line) return; + p = parent[v]; + switch(name[p]) { + case STAR: + case PLUS: + cstate(v); + follow(p); + return; + + case OR: + case QUEST: + follow(p); + return; + + case CAT: + if(v == left[p]) { + if(cstate(right[p]) == 0) { + follow(p); + return; + } + } else + follow(p); + return; + case FINAL: + if(tmpstat[line] != 1) { + tmpstat[line] = 1; + count++; + } + return; } - return; - } } -char * -egrepinit(const char *egreppat) -{ - /* initialize the global data */ - memset(gotofn, 0, sizeof(gotofn)); - memset(state, 0, sizeof(state)); - memset(out, 0, sizeof(out)); - line = 1; - memset(name, 0, sizeof(name)); - memset(left, 0, sizeof(left)); - memset(right, 0, sizeof(right)); - memset(parent, 0, sizeof(parent)); - memset(foll, 0, sizeof(foll)); - memset(positions, 0, sizeof(positions)); - memset(chars, 0, sizeof(chars)); - nxtpos = 0; - nxtchar = 0; - memset(tmpstat, 0, sizeof(tmpstat)); - memset(initstat, 0, sizeof(initstat)); - xstate = 0; - count = 0; - icount = 0; - input = egreppat; - message = NULL; - if (setjmp(env) == 0) { - yyparse(); - cfoll(line-1); - cgotofn(); - } - return(message); +char *egrepinit(const char *egreppat) { + /* initialize the global data */ + memset(gotofn, 0, sizeof(gotofn)); + memset(state, 0, sizeof(state)); + memset(out, 0, sizeof(out)); + line = 1; + memset(name, 0, sizeof(name)); + memset(left, 0, sizeof(left)); + memset(right, 0, sizeof(right)); + memset(parent, 0, sizeof(parent)); + memset(foll, 0, sizeof(foll)); + memset(positions, 0, sizeof(positions)); + memset(chars, 0, sizeof(chars)); + nxtpos = 0; + nxtchar = 0; + memset(tmpstat, 0, sizeof(tmpstat)); + memset(initstat, 0, sizeof(initstat)); + xstate = 0; + count = 0; + icount = 0; + input = egreppat; + message = NULL; + if(setjmp(env) == 0) { + yyparse(); + cfoll(line - 1); + cgotofn(); + } + return (message); } -static char buf[2 * BUFSIZ]; +static char buf[2 * BUFSIZ]; static const char *buf_end = buf + (sizeof(buf) / sizeof(*buf)); -static size_t read_next_chunk(char **p, FILE *fptr) -{ - if (*p <= (buf + BUFSIZ)) { - /* bwlow the middle, so enough space left for one entire BUFSIZ */ - return fread(*p, sizeof(**p), BUFSIZ, fptr); - } else if (*p == buf_end) { - /* exactly at end ... wrap around and use lower half */ - *p = buf; - return fread(*p, sizeof(**p), BUFSIZ, fptr); - } - /* somewhere in second half, so do a limited read */ - return fread(*p, sizeof(**p), buf_end - *p, fptr); +static size_t read_next_chunk(char **p, FILE *fptr) { + if(*p <= (buf + BUFSIZ)) { + /* bwlow the middle, so enough space left for one entire BUFSIZ */ + return fread(*p, sizeof(**p), BUFSIZ, fptr); + } else if(*p == buf_end) { + /* exactly at end ... wrap around and use lower half */ + *p = buf; + return fread(*p, sizeof(**p), BUFSIZ, fptr); + } + /* somewhere in second half, so do a limited read */ + return fread(*p, sizeof(**p), buf_end - *p, fptr); } -int -egrep(char *file, FILE *output, char *format) -{ - char *p; - unsigned int cstat; - int ccount; - char *nlp; - unsigned int istat; - int in_line; - FILE *fptr; - - if ((fptr = myfopen(file, "r")) == NULL) - return(-1); - - lnum = 1; - p = buf; - nlp = p; - ccount = read_next_chunk(&p, fptr); - - if (ccount <= 0) { - fclose(fptr); - return(0); - } - in_line = 1; - istat = cstat = (unsigned int) gotofn[0]['\n']; - if (out[cstat]) - goto found; - for (;;) { - if (!iflag) { - /* all input chars made positive */ - cstat = (unsigned int) gotofn[cstat][(unsigned char)*p]; - } else { - /* for -i option*/ - cstat = (unsigned int) gotofn[cstat][tolower((unsigned char)*p)]; - } - if (out[cstat]) { - found: - for(;;) { - if (*p++ == '\n') { - in_line = 0; - succeed: - fprintf(output, format, file, lnum); - if (p <= nlp) { - while (nlp < buf_end) - putc(*nlp++, output); - nlp = buf; - } - while (nlp < p) - putc(*nlp++, output); - lnum++; - nlp = p; - if (out[cstat = istat] == 0) - goto brk2; - } /* if (p++ == \n) */ - cfound: - if (--ccount <= 0) { - ccount = read_next_chunk(&p, fptr); - if (ccount <= 0) { - if (in_line) { - in_line = 0; - goto succeed; - } - fclose(fptr); - return(0); - } - } /* if(ccount <= 0) */ - in_line = 1; - } /* for(ever) */ - } /* if(out[cstat]) */ - - if (*p++ == '\n') { - in_line = 0; - lnum++; - nlp = p; - if (out[(cstat=istat)]) - goto cfound; - } - brk2: - if (--ccount <= 0) { - ccount = read_next_chunk(&p, fptr); - if (ccount <= 0) - break; +int egrep(char *file, FILE *output, char *format) { + char *p; + unsigned int cstat; + int ccount; + char *nlp; + unsigned int istat; + int in_line; + FILE *fptr; + + if((fptr = myfopen(file, "r")) == NULL) return (-1); + + lnum = 1; + p = buf; + nlp = p; + ccount = read_next_chunk(&p, fptr); + + if(ccount <= 0) { + fclose(fptr); + return (0); } in_line = 1; - } - fclose(fptr); - return(0); + istat = cstat = (unsigned int)gotofn[0]['\n']; + if(out[cstat]) goto found; + for(;;) { + if(!iflag) { + /* all input chars made positive */ + cstat = (unsigned int)gotofn[cstat][(unsigned char)*p]; + } else { + /* for -i option*/ + cstat = (unsigned int)gotofn[cstat][tolower((unsigned char)*p)]; + } + if(out[cstat]) { + found: + for(;;) { + if(*p++ == '\n') { + in_line = 0; + succeed: + fprintf(output, format, file, lnum); + if(p <= nlp) { + while(nlp < buf_end) + putc(*nlp++, output); + nlp = buf; + } + while(nlp < p) + putc(*nlp++, output); + lnum++; + nlp = p; + if(out[cstat = istat] == 0) goto brk2; + } /* if (p++ == \n) */ + cfound: + if(--ccount <= 0) { + ccount = read_next_chunk(&p, fptr); + if(ccount <= 0) { + if(in_line) { + in_line = 0; + goto succeed; + } + fclose(fptr); + return (0); + } + } /* if(ccount <= 0) */ + in_line = 1; + } /* for(ever) */ + } /* if(out[cstat]) */ + + if(*p++ == '\n') { + in_line = 0; + lnum++; + nlp = p; + if(out[(cstat = istat)]) goto cfound; + } + brk2: + if(--ccount <= 0) { + ccount = read_next_chunk(&p, fptr); + if(ccount <= 0) break; + } + in_line = 1; + } + fclose(fptr); + return (0); } -void -egrepcaseless(int i) -{ - iflag = i; /* simulate "egrep -i" */ +void egrepcaseless(int i) { + iflag = i; /* simulate "egrep -i" */ } diff --git a/src/egrep.h b/src/egrep.h index 2791837..5b6a180 100644 --- a/src/egrep.h +++ b/src/egrep.h @@ -36,7 +36,7 @@ private implementation details that can be changed or removed. */ #ifndef YY_YY_EGREP_H_INCLUDED -# define YY_YY_EGREP_H_INCLUDED +#define YY_YY_EGREP_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 @@ -48,43 +48,43 @@ extern int yydebug; /* Token kinds. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE - enum yytokentype - { - YYEMPTY = -2, - YYEOF = 0, /* "end of file" */ - YYerror = 256, /* error */ - YYUNDEF = 257, /* "invalid token" */ - CHAR = 258, /* CHAR */ - DOT = 259, /* DOT */ - CCL = 260, /* CCL */ - NCCL = 261, /* NCCL */ - OR = 262, /* OR */ - CAT = 263, /* CAT */ - STAR = 264, /* STAR */ - PLUS = 265, /* PLUS */ - QUEST = 266 /* QUEST */ - }; - typedef enum yytokentype yytoken_kind_t; + +enum yytokentype { + YYEMPTY = -2, + YYEOF = 0, /* "end of file" */ + YYerror = 256, /* error */ + YYUNDEF = 257, /* "invalid token" */ + CHAR = 258, /* CHAR */ + DOT = 259, /* DOT */ + CCL = 260, /* CCL */ + NCCL = 261, /* NCCL */ + OR = 262, /* OR */ + CAT = 263, /* CAT */ + STAR = 264, /* STAR */ + PLUS = 265, /* PLUS */ + QUEST = 266 /* QUEST */ +}; +typedef enum yytokentype yytoken_kind_t; #endif /* Token kinds. */ #define YYEMPTY -2 -#define YYEOF 0 +#define YYEOF 0 #define YYerror 256 #define YYUNDEF 257 -#define CHAR 258 -#define DOT 259 -#define CCL 260 -#define NCCL 261 -#define OR 262 -#define CAT 263 -#define STAR 264 -#define PLUS 265 -#define QUEST 266 +#define CHAR 258 +#define DOT 259 +#define CCL 260 +#define NCCL 261 +#define OR 262 +#define CAT 263 +#define STAR 264 +#define PLUS 265 +#define QUEST 266 /* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef int YYSTYPE; -# define YYSTYPE_IS_TRIVIAL 1 +#if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED +typedef int YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif @@ -92,7 +92,7 @@ typedef int YYSTYPE; extern YYSTYPE yylval; -int yyparse (void); +int yyparse(void); #endif /* !YY_YY_EGREP_H_INCLUDED */ diff --git a/src/exec.c b/src/exec.c index 6e8e75d..7da3edf 100644 --- a/src/exec.c +++ b/src/exec.c @@ -39,20 +39,20 @@ #include "global.h" #include #include -#include /* pid_t */ +#include /* pid_t */ #ifdef __DJGPP__ -#include +# include #endif #include -static sighandler_t oldsigquit; /* old value of quit signal */ -static sighandler_t oldsighup; /* old value of hangup signal */ -static sighandler_t oldsigtstp; /* old value of SIGTSTP */ +static sighandler_t oldsigquit; /* old value of quit signal */ +static sighandler_t oldsighup; /* old value of hangup signal */ +static sighandler_t oldsigtstp; /* old value of SIGTSTP */ -#ifndef __MSDOS__ /* none of these is needed, there */ -static int join(pid_t p); -static int myexecvp(char *a, char **args); -static pid_t myfork(void); +#ifndef __MSDOS__ /* none of these is needed, there */ +static int join(pid_t p); +static int myexecvp(char *a, char **args); +static pid_t myfork(void); #endif /* execute forks and executes a program or shell script, waits for it to @@ -60,39 +60,37 @@ static pid_t myfork(void); */ /*VARARGS1*/ -int -execute(char *a, ...) /* NOTE: "exec" is already defined on u370 */ +int execute(char *a, ...) /* NOTE: "exec" is already defined on u370 */ { - va_list ap; - int exitcode = -1; - char *argv[BUFSIZ]; - pid_t p; + va_list ap; + int exitcode = -1; + char *argv[BUFSIZ]; + pid_t p; - /* fork and exec the program or shell script */ - endwin(); /* restore the terminal modes */ - mousecleanup(); - fflush(stdout); - va_start(ap, a); + /* fork and exec the program or shell script */ + endwin(); /* restore the terminal modes */ + mousecleanup(); + fflush(stdout); + va_start(ap, a); - for (p = 0; (argv[p] = va_arg(ap, char *)) != 0; p++){} + for(p = 0; (argv[p] = va_arg(ap, char *)) != 0; p++) { } #ifdef __MSDOS__ - /* HBB 20010313: in MSDOG, everything is completely different. - * No fork()/exec()/wait(), but rather a single libc call: */ - exitcode = spawnvp(P_WAIT, a, argv); + /* HBB 20010313: in MSDOG, everything is completely different. + * No fork()/exec()/wait(), but rather a single libc call: */ + exitcode = spawnvp(P_WAIT, a, argv); #else - if ((p = myfork()) == 0) { - myexecvp(a, argv); /* child */ - } - else { - exitcode = join(p); /* parent */ - } + if((p = myfork()) == 0) { + myexecvp(a, argv); /* child */ + } else { + exitcode = join(p); /* parent */ + } #endif /* MSDOS */ entercurses(); - va_end(ap); - return(exitcode); + va_end(ap); + return (exitcode); } #ifndef __MSDOS__ /* None of the following functions is used there */ @@ -100,79 +98,71 @@ execute(char *a, ...) /* NOTE: "exec" is already defined on u370 */ /* myexecvp is an interface to the execvp system call to * modify argv[0] to reference the last component of its path-name. */ -static int -myexecvp(char *a, char **args) -{ - char msg[MSGLEN + 1]; - - /* modify argv[0] to reference the last component of its path name */ - args[0] = basename(args[0]); - - /* execute the program or shell script */ - execvp(a, args); /* returns only on failure */ - snprintf(msg, sizeof(msg), "\nCannot exec %s", a); - perror(msg); /* display the reason */ - askforreturn(); /* wait until the user sees the message */ - myexit(1); /* exit the child */ - /* NOTREACHED */ - return 0; +static int myexecvp(char *a, char **args) { + char msg[MSGLEN + 1]; + + /* modify argv[0] to reference the last component of its path name */ + args[0] = basename(args[0]); + + /* execute the program or shell script */ + execvp(a, args); /* returns only on failure */ + snprintf(msg, sizeof(msg), "\nCannot exec %s", a); + perror(msg); /* display the reason */ + askforreturn(); /* wait until the user sees the message */ + myexit(1); /* exit the child */ + /* NOTREACHED */ + return 0; } /* myfork acts like fork but also handles signals */ -static pid_t -myfork(void) -{ - pid_t p; /* process number */ - - p = fork(); - - /* the parent ignores the interrupt, quit, and hangup signals */ - if (p > 0) { - oldsigquit = signal(SIGQUIT, SIG_IGN); - oldsighup = signal(SIGHUP, SIG_IGN); -#ifdef SIGTSTP - oldsigtstp = signal(SIGTSTP, SIG_DFL); -#endif - } - /* so they can be used to stop the child */ - else if (p == 0) { - signal(SIGINT, SIG_DFL); - signal(SIGQUIT, SIG_DFL); - signal(SIGHUP, SIG_DFL); -#ifdef SIGTSTP - signal(SIGTSTP, SIG_DFL); -#endif - } - /* check for fork failure */ - if (p == -1) { - myperror("Cannot fork"); - } - return p; +static pid_t myfork(void) { + pid_t p; /* process number */ + + p = fork(); + + /* the parent ignores the interrupt, quit, and hangup signals */ + if(p > 0) { + oldsigquit = signal(SIGQUIT, SIG_IGN); + oldsighup = signal(SIGHUP, SIG_IGN); +# ifdef SIGTSTP + oldsigtstp = signal(SIGTSTP, SIG_DFL); +# endif + } + /* so they can be used to stop the child */ + else if(p == 0) { + signal(SIGINT, SIG_DFL); + signal(SIGQUIT, SIG_DFL); + signal(SIGHUP, SIG_DFL); +# ifdef SIGTSTP + signal(SIGTSTP, SIG_DFL); +# endif + } + /* check for fork failure */ + if(p == -1) { myperror("Cannot fork"); } + return p; } /* join is the compliment of fork */ -static int -join(pid_t p) -{ - int status = -1; - pid_t w; - - /* wait for the correct child to exit */ - do { - w = wait(&status); - } while (p != -1 && w != p); - - /* restore signal handling */ - signal(SIGQUIT, oldsigquit); - signal(SIGHUP, oldsighup); -#ifdef SIGTSTP - signal(SIGTSTP, oldsigtstp); -#endif +static int join(pid_t p) { + int status = -1; + pid_t w; + + /* wait for the correct child to exit */ + do { + w = wait(&status); + } while(p != -1 && w != p); + + /* restore signal handling */ + signal(SIGQUIT, oldsigquit); + signal(SIGHUP, oldsighup); +# ifdef SIGTSTP + signal(SIGTSTP, oldsigtstp); +# endif - /* return the child's exit code */ - return(status >> 8); + /* return the child's exit code */ + return (status >> 8); } #endif /* !MSDOS */ diff --git a/src/find.c b/src/find.c index 3515b26..c567874 100644 --- a/src/find.c +++ b/src/find.c @@ -38,12 +38,12 @@ #include "global.h" #include "build.h" -#include "scanner.h" /* for token definitions */ +#include "scanner.h" /* for token definitions */ #include #include #include -#include /* jmp_buf */ +#include /* jmp_buf */ /* most of these functions have been optimized so their innermost loops have * only one test for the desired character by putting the char and @@ -53,43 +53,43 @@ * and restart the inner loop. */ -char *blockp; /* pointer to current char in block */ -char block[BUFSIZ + 2]; /* leave room for end-of-block mark */ -int blocklen; /* length of disk block read */ -char blockmark; /* mark character to be searched for */ -long blocknumber; /* block number */ - -static char global[] = ""; /* dummy global function name */ -static char cpattern[PATLEN + 1]; /* compressed pattern */ -static long lastfcnoffset; /* last function name offset */ -static POSTING *postingp; /* retrieved posting set pointer */ -static long postingsfound; /* retrieved number of postings */ -static regex_t regexp; /* regular expression */ -static bool isregexp_valid = false; /* regular expression status */ - -static bool match(void); -static bool matchrest(void); -static POSTING *getposting(void); -static char *lcasify(const char *s); -static void findcalledbysub(const char *file, bool macro); -static void findterm(const char *pattern); -static void putline(FILE *output); -static char *find_symbol_or_assignment(const char *pattern, bool assign_flag); -static bool check_for_assignment(void); -static void putpostingref(POSTING *p, const char *pat); -static void putref(int seemore, const char *file, const char *func); -static void putsource(int seemore, FILE *output); -static FILE *nonglobalrefs; /* non-global references file */ - -static sigjmp_buf env; /* setjmp/longjmp buffer */ - -typedef enum { /* findinit return code */ - NOERROR, - NOTSYMBOL, - REGCMPERROR +char *blockp; /* pointer to current char in block */ +char block[BUFSIZ + 2]; /* leave room for end-of-block mark */ +int blocklen; /* length of disk block read */ +char blockmark; /* mark character to be searched for */ +long blocknumber; /* block number */ + +static char global[] = ""; /* dummy global function name */ +static char cpattern[PATLEN + 1]; /* compressed pattern */ +static long lastfcnoffset; /* last function name offset */ +static POSTING *postingp; /* retrieved posting set pointer */ +static long postingsfound; /* retrieved number of postings */ +static regex_t regexp; /* regular expression */ +static bool isregexp_valid = false; /* regular expression status */ + +static bool match(void); +static bool matchrest(void); +static POSTING *getposting(void); +static char *lcasify(const char *s); +static void findcalledbysub(const char *file, bool macro); +static void findterm(const char *pattern); +static void putline(FILE *output); +static char *find_symbol_or_assignment(const char *pattern, bool assign_flag); +static bool check_for_assignment(void); +static void putpostingref(POSTING *p, const char *pat); +static void putref(int seemore, const char *file, const char *func); +static void putsource(int seemore, FILE *output); +static FILE *nonglobalrefs; /* non-global references file */ + +static sigjmp_buf env; /* setjmp/longjmp buffer */ + +typedef enum { /* findinit return code */ + NOERROR, + NOTSYMBOL, + REGCMPERROR } FINDINIT; -typedef char * (*FP)(const char *); /* pointer to function returning a character pointer */ +typedef char *(*FP)(const char *); /* pointer to function returning a character pointer */ /* Paralel array to "fields", indexed by "field" */ FP field_searchers[FIELDS + 1] = { findsymbol, @@ -102,981 +102,874 @@ FP field_searchers[FIELDS + 1] = { findfile, findinclude, findassign, - findallfcns /* samuel only */ + findallfcns /* samuel only */ }; /**/ struct TI { - char *text1; - char *text2; + char *text1; + char *text2; }; extern struct TI fields[FIELDS + 1]; /* Internal prototypes: */ -static void jumpback(int sig); -static void -jumpback(int sig) -{ - signal(sig, jumpback); - siglongjmp(env, 1); -} +static void jumpback(int sig); +static void jumpback(int sig) { + signal(sig, jumpback); + siglongjmp(env, 1); +} /* find the symbol in the cross-reference */ -char * -findsymbol(const char *pattern) -{ - return find_symbol_or_assignment(pattern, false); +char *findsymbol(const char *pattern) { + return find_symbol_or_assignment(pattern, false); } /* find the symbol in the cross-reference, and look for assignments */ -char * -findassign(const char *pattern) -{ - return find_symbol_or_assignment(pattern, true); +char *findassign(const char *pattern) { + return find_symbol_or_assignment(pattern, true); } - /* Test reference whether it's an assignment to the symbol found at +/* Test reference whether it's an assignment to the symbol found at * (global variable) 'blockp' */ -static bool -check_for_assignment(void) -{ - /* Do the extra work here to determine if this is an - * assignment or not. Do this by examining the next character - * or two in blockp */ - char *asgn_char = blockp; - - while (isspace((unsigned char) asgn_char[0])) { - /* skip any whitespace or \n */ - asgn_char++; - if (asgn_char[0] == '\0') { - /* get the next block when we reach the end of - * the current block */ - if (NULL == (asgn_char = read_block())) - return false; - } - } - /* check for digraph starting with = */ - if ((asgn_char[0] & 0x80) && (dichar1[(asgn_char[0] & 0177)/8] == '=')) { - return true; - } - /* check for plain '=', not '==' */ - if ((asgn_char[0] == '=') && - (((asgn_char[1] != '=') && !(asgn_char[1] & 0x80)) || - ((asgn_char[1] & 0x80) && (dichar1[(asgn_char[1]& 0177)/8] != '=')))) { - return true; - } - - /* check for operator assignments: +=, ... ^= ? */ - if ( ( (asgn_char[0] == '+') - || (asgn_char[0] == '-') - || (asgn_char[0] == '*') - || (asgn_char[0] == '/') - || (asgn_char[0] == '%') - || (asgn_char[0] == '&') - || (asgn_char[0] == '|') - || (asgn_char[0] == '^') - ) - && ((asgn_char[1] == '=') || ((asgn_char[1] & 0x80) && (dichar1[(asgn_char[1] &0177)/8] == '='))) - - ) { - return true; - } - - /* check for two-letter operator assignments: <<= or >>= ? */ - if ( ( (asgn_char[0] == '<') - || (asgn_char[0] == '>') - ) - && (asgn_char[1] == asgn_char[0]) - && ((asgn_char[2] == '=') || ((asgn_char[2] & 0x80) && (dichar1[(asgn_char[2] & 0177)/8] == '='))) - ) - return true; - return false; +static bool check_for_assignment(void) { + /* Do the extra work here to determine if this is an + * assignment or not. Do this by examining the next character + * or two in blockp */ + char *asgn_char = blockp; + + while(isspace((unsigned char)asgn_char[0])) { + /* skip any whitespace or \n */ + asgn_char++; + if(asgn_char[0] == '\0') { + /* get the next block when we reach the end of + * the current block */ + if(NULL == (asgn_char = read_block())) return false; + } + } + /* check for digraph starting with = */ + if((asgn_char[0] & 0x80) && (dichar1[(asgn_char[0] & 0177) / 8] == '=')) { + return true; + } + /* check for plain '=', not '==' */ + if((asgn_char[0] == '=') && + (((asgn_char[1] != '=') && !(asgn_char[1] & 0x80)) || + ((asgn_char[1] & 0x80) && (dichar1[(asgn_char[1] & 0177) / 8] != '=')))) { + return true; + } + + /* check for operator assignments: +=, ... ^= ? */ + if(((asgn_char[0] == '+') || (asgn_char[0] == '-') || (asgn_char[0] == '*') || + (asgn_char[0] == '/') || (asgn_char[0] == '%') || (asgn_char[0] == '&') || + (asgn_char[0] == '|') || (asgn_char[0] == '^')) && + ((asgn_char[1] == '=') || + ((asgn_char[1] & 0x80) && (dichar1[(asgn_char[1] & 0177) / 8] == '='))) + + ) { + return true; + } + + /* check for two-letter operator assignments: <<= or >>= ? */ + if(((asgn_char[0] == '<') || (asgn_char[0] == '>')) && + (asgn_char[1] == asgn_char[0]) && + ((asgn_char[2] == '=') || + ((asgn_char[2] & 0x80) && (dichar1[(asgn_char[2] & 0177) / 8] == '=')))) + return true; + return false; } /* The actual routine that does the work for findsymbol() and -* findassign() */ -static char * -find_symbol_or_assignment(const char *pattern, bool assign_flag) -{ - char file[PATHLEN + 1]; /* source file name */ - char function[PATLEN + 1]; /* function name */ - char macro[PATLEN + 1]; /* macro name */ - char symbol[PATLEN + 1]; /* symbol name */ - char *cp; - char *s; - size_t s_len = 0; - char firstchar; /* first character of a potential symbol */ - bool fcndef = false; - - if ((invertedindex == true) && (assign_flag == false)) { - long lastline = 0; - POSTING *p; - - findterm(pattern); - while ((p = getposting()) != NULL) { - if (p->type != INCLUDE && p->lineoffset != lastline) { - putpostingref(p, 0); - lastline = p->lineoffset; - } - } - return NULL; - } - - (void) scanpast('\t'); /* find the end of the header */ - skiprefchar(); /* skip the file marker */ - fetch_string_from_dbase(file, sizeof(file)); - strcpy(function, global); /* set the dummy global function name */ - strcpy(macro, global); /* set the dummy global macro name */ - - /* find the next symbol */ - /* note: this code was expanded in-line for speed */ - /* other macros were replaced by code using cp instead of blockp */ - cp = blockp; - for (;;) { - setmark('\n'); - do { /* innermost loop optimized to only one test */ - while (*cp != '\n') { - ++cp; - } - } while (*(cp + 1) == '\0' && (cp = read_block()) != NULL); - - /* skip the found character */ - if (cp != NULL && *(++cp + 1) == '\0') { - cp = read_block(); - } - if (cp == NULL) { - break; - } - /* look for a source file, function, or macro name */ - if (*cp == '\t') { - blockp = cp; - switch (getrefchar()) { - - case NEWFILE: /* file name */ - - /* save the name */ - skiprefchar(); - fetch_string_from_dbase(file, sizeof(file)); - - /* check for the end of the symbols */ - if (*file == '\0') { - return NULL; - } - progress("Search", searchcount, nsrcfiles); - /* FALLTHROUGH */ - - case FCNEND: /* function end */ - (void) strcpy(function, global); - goto notmatched; /* don't match name */ - - case FCNDEF: /* function name */ - fcndef = true; - s = function; - s_len = sizeof(function); - break; - - case DEFINE: /* macro name */ - if (fileversion >= 10) { - s = macro; - s_len = sizeof(macro); - } else { - s = symbol; - s_len = sizeof(symbol); - } - break; - - case DEFINEEND: /* macro end */ - (void) strcpy(macro, global); - goto notmatched; - - case INCLUDE: /* #include file */ - goto notmatched; /* don't match name */ - - default: /* other symbol */ - s = symbol; - s_len = sizeof(symbol); - } - /* save the name */ - skiprefchar(); - fetch_string_from_dbase(s, s_len); - - /* see if this is a regular expression pattern */ - if (isregexp_valid == true) { - if (caseless == true) { - s = lcasify(s); - } - if (*s != '\0' && regexec (®exp, s, (size_t)0, NULL, 0) == 0) { - goto matched; - } - } - /* match the symbol to the text pattern */ - else if (strequal(pattern, s)) { - goto matched; - } - goto notmatched; - } - /* if this is a regular expression pattern */ - if (isregexp_valid == true) { - - /* if this is a symbol */ - - /************************************************** - * The first character may be a digraph'ed char, so - * unpack it into firstchar, and then test that. - * - * Assume that all digraphed chars have the 8th bit - * set (0200). - **************************************************/ - if (*cp & 0200) { /* digraph char? */ - firstchar = dichar1[(*cp & 0177) / 8]; - } - else { - firstchar = *cp; - } - - if (isalpha((unsigned char)firstchar) || firstchar == '_') { - blockp = cp; - fetch_string_from_dbase(symbol, sizeof(symbol)); - if (caseless == true) { - s = lcasify(symbol); /* point to lower case version */ - } - else { - s = symbol; - } - - /* match the symbol to the regular expression */ - if (*s != '\0' && regexec (®exp, s, (size_t)0, NULL, 0) == 0) { - goto matched; - } - goto notmatched; - } - } - /* match the character to the text pattern */ - else if (*cp == cpattern[0]) { - blockp = cp; - - /* match the rest of the symbol to the text pattern */ - if (matchrest()) { - s = NULL; - matched: - /* if the assignment flag is set then - * we are looking for assignments and - * some extra filtering is needed */ - if(assign_flag == true - && ! check_for_assignment()) - goto notmatched; - - - /* output the file, function or macro, and source line */ - if (strcmp(macro, global) && s != macro) { - putref(0, file, macro); - } - else if (fcndef == true || s != function) { - fcndef = false; - putref(0, file, function); - } - else { - putref(0, file, global); - } - } - notmatched: - if (blockp == NULL) { - return NULL; - } - fcndef = false; - cp = blockp; - } - } - blockp = cp; - - return NULL; + * findassign() */ +static char *find_symbol_or_assignment(const char *pattern, bool assign_flag) { + char file[PATHLEN + 1]; /* source file name */ + char function[PATLEN + 1]; /* function name */ + char macro[PATLEN + 1]; /* macro name */ + char symbol[PATLEN + 1]; /* symbol name */ + char *cp; + char *s; + size_t s_len = 0; + char firstchar; /* first character of a potential symbol */ + bool fcndef = false; + + if((invertedindex == true) && (assign_flag == false)) { + long lastline = 0; + POSTING *p; + + findterm(pattern); + while((p = getposting()) != NULL) { + if(p->type != INCLUDE && p->lineoffset != lastline) { + putpostingref(p, 0); + lastline = p->lineoffset; + } + } + return NULL; + } + + (void)scanpast('\t'); /* find the end of the header */ + skiprefchar(); /* skip the file marker */ + fetch_string_from_dbase(file, sizeof(file)); + strcpy(function, global); /* set the dummy global function name */ + strcpy(macro, global); /* set the dummy global macro name */ + + /* find the next symbol */ + /* note: this code was expanded in-line for speed */ + /* other macros were replaced by code using cp instead of blockp */ + cp = blockp; + for(;;) { + setmark('\n'); + do { /* innermost loop optimized to only one test */ + while(*cp != '\n') { + ++cp; + } + } while(*(cp + 1) == '\0' && (cp = read_block()) != NULL); + + /* skip the found character */ + if(cp != NULL && *(++cp + 1) == '\0') { cp = read_block(); } + if(cp == NULL) { break; } + /* look for a source file, function, or macro name */ + if(*cp == '\t') { + blockp = cp; + switch(getrefchar()) { + + case NEWFILE: /* file name */ + + /* save the name */ + skiprefchar(); + fetch_string_from_dbase(file, sizeof(file)); + + /* check for the end of the symbols */ + if(*file == '\0') { return NULL; } + progress("Search", searchcount, nsrcfiles); + /* FALLTHROUGH */ + + case FCNEND: /* function end */ + (void)strcpy(function, global); + goto notmatched; /* don't match name */ + + case FCNDEF: /* function name */ + fcndef = true; + s = function; + s_len = sizeof(function); + break; + + case DEFINE: /* macro name */ + if(fileversion >= 10) { + s = macro; + s_len = sizeof(macro); + } else { + s = symbol; + s_len = sizeof(symbol); + } + break; + + case DEFINEEND: /* macro end */ + (void)strcpy(macro, global); + goto notmatched; + + case INCLUDE: /* #include file */ + goto notmatched; /* don't match name */ + + default: /* other symbol */ + s = symbol; + s_len = sizeof(symbol); + } + /* save the name */ + skiprefchar(); + fetch_string_from_dbase(s, s_len); + + /* see if this is a regular expression pattern */ + if(isregexp_valid == true) { + if(caseless == true) { s = lcasify(s); } + if(*s != '\0' && regexec(®exp, s, (size_t)0, NULL, 0) == 0) { + goto matched; + } + } + /* match the symbol to the text pattern */ + else if(strequal(pattern, s)) { + goto matched; + } + goto notmatched; + } + /* if this is a regular expression pattern */ + if(isregexp_valid == true) { + + /* if this is a symbol */ + + /************************************************** + * The first character may be a digraph'ed char, so + * unpack it into firstchar, and then test that. + * + * Assume that all digraphed chars have the 8th bit + * set (0200). + **************************************************/ + if(*cp & 0200) { /* digraph char? */ + firstchar = dichar1[(*cp & 0177) / 8]; + } else { + firstchar = *cp; + } + + if(isalpha((unsigned char)firstchar) || firstchar == '_') { + blockp = cp; + fetch_string_from_dbase(symbol, sizeof(symbol)); + if(caseless == true) { + s = lcasify(symbol); /* point to lower case version */ + } else { + s = symbol; + } + + /* match the symbol to the regular expression */ + if(*s != '\0' && regexec(®exp, s, (size_t)0, NULL, 0) == 0) { + goto matched; + } + goto notmatched; + } + } + /* match the character to the text pattern */ + else if(*cp == cpattern[0]) { + blockp = cp; + + /* match the rest of the symbol to the text pattern */ + if(matchrest()) { + s = NULL; + matched: + /* if the assignment flag is set then + * we are looking for assignments and + * some extra filtering is needed */ + if(assign_flag == true && !check_for_assignment()) goto notmatched; + + + /* output the file, function or macro, and source line */ + if(strcmp(macro, global) && s != macro) { + putref(0, file, macro); + } else if(fcndef == true || s != function) { + fcndef = false; + putref(0, file, function); + } else { + putref(0, file, global); + } + } + notmatched: + if(blockp == NULL) { return NULL; } + fcndef = false; + cp = blockp; + } + } + blockp = cp; + + return NULL; } + /* find the function definition or #define */ -char * -finddef(const char *pattern) -{ - char file[PATHLEN + 1]; /* source file name */ - - if (invertedindex == true) { - POSTING *p; - - findterm(pattern); - while ((p = getposting()) != NULL) { - switch (p->type) { - case DEFINE:/* could be a macro */ - case FCNDEF: - case CLASSDEF: - case ENUMDEF: - case MEMBERDEF: - case STRUCTDEF: - case TYPEDEF: - case UNIONDEF: - case GLOBALDEF:/* other global definition */ - putpostingref(p, pattern); - } - } - return NULL; - } - - - /* find the next file name or definition */ - while (scanpast('\t') != NULL) { - switch (*blockp) { - - case NEWFILE: - skiprefchar(); /* save file name */ - fetch_string_from_dbase(file, sizeof(file)); - if (*file == '\0') { /* if end of symbols */ - return NULL; - } - progress("Search", searchcount, nsrcfiles); - break; - - case DEFINE: /* could be a macro */ - case FCNDEF: - case CLASSDEF: - case ENUMDEF: - case MEMBERDEF: - case STRUCTDEF: - case TYPEDEF: - case UNIONDEF: - case GLOBALDEF: /* other global definition */ - skiprefchar(); /* match name to pattern */ - if (match()) { - - /* output the file, function and source line */ - putref(0, file, pattern); - } - break; - } - } - - return NULL; +char *finddef(const char *pattern) { + char file[PATHLEN + 1]; /* source file name */ + + if(invertedindex == true) { + POSTING *p; + + findterm(pattern); + while((p = getposting()) != NULL) { + switch(p->type) { + case DEFINE: /* could be a macro */ + case FCNDEF: + case CLASSDEF: + case ENUMDEF: + case MEMBERDEF: + case STRUCTDEF: + case TYPEDEF: + case UNIONDEF: + case GLOBALDEF: /* other global definition */ + putpostingref(p, pattern); + } + } + return NULL; + } + + + /* find the next file name or definition */ + while(scanpast('\t') != NULL) { + switch(*blockp) { + + case NEWFILE: + skiprefchar(); /* save file name */ + fetch_string_from_dbase(file, sizeof(file)); + if(*file == '\0') { /* if end of symbols */ + return NULL; + } + progress("Search", searchcount, nsrcfiles); + break; + + case DEFINE: /* could be a macro */ + case FCNDEF: + case CLASSDEF: + case ENUMDEF: + case MEMBERDEF: + case STRUCTDEF: + case TYPEDEF: + case UNIONDEF: + case GLOBALDEF: /* other global definition */ + skiprefchar(); /* match name to pattern */ + if(match()) { + + /* output the file, function and source line */ + putref(0, file, pattern); + } + break; + } + } + + return NULL; } + /* find all function definitions (used by samuel only) */ -char * -findallfcns(const char *dummy) -{ - char file[PATHLEN + 1]; /* source file name */ - char function[PATLEN + 1]; /* function name */ - - (void) dummy; /* unused argument */ - - /* find the next file name or definition */ - while (scanpast('\t') != NULL) { - switch (*blockp) { - - case NEWFILE: - skiprefchar(); /* save file name */ - fetch_string_from_dbase(file, sizeof(file)); - if (*file == '\0') { /* if end of symbols */ - return NULL; - } - progress("Search", searchcount, nsrcfiles); - /* FALLTHROUGH */ - - case FCNEND: /* function end */ - (void) strcpy(function, global); - break; - - case FCNDEF: - case CLASSDEF: - skiprefchar(); /* save function name */ - fetch_string_from_dbase(function, sizeof(function)); - - /* output the file, function and source line */ - putref(0, file, function); - break; - } - } - return NULL; +char *findallfcns(const char *dummy) { + char file[PATHLEN + 1]; /* source file name */ + char function[PATLEN + 1]; /* function name */ + + (void)dummy; /* unused argument */ + + /* find the next file name or definition */ + while(scanpast('\t') != NULL) { + switch(*blockp) { + + case NEWFILE: + skiprefchar(); /* save file name */ + fetch_string_from_dbase(file, sizeof(file)); + if(*file == '\0') { /* if end of symbols */ + return NULL; + } + progress("Search", searchcount, nsrcfiles); + /* FALLTHROUGH */ + + case FCNEND: /* function end */ + (void)strcpy(function, global); + break; + + case FCNDEF: + case CLASSDEF: + skiprefchar(); /* save function name */ + fetch_string_from_dbase(function, sizeof(function)); + + /* output the file, function and source line */ + putref(0, file, function); + break; + } + } + return NULL; } - /* find the functions calling this function */ - -char * -findcalling(const char *pattern) -{ - char file[PATHLEN + 1]; /* source file name */ - char function[PATLEN + 1]; /* function name */ - char tmpfunc[10][PATLEN + 1];/* 10 temporary function names */ - char macro[PATLEN + 1]; /* macro name */ - char *tmpblockp; - int morefuns, i; - - if (invertedindex == true) { - POSTING *p; - - findterm(pattern); - while ((p = getposting()) != NULL) { - if (p->type == FCNCALL) { - putpostingref(p, 0); - } - } - return NULL; - } - /* find the next file name or function definition */ - *macro = '\0'; /* a macro can be inside a function, but not vice versa */ - tmpblockp = 0; - morefuns = 0; /* one function definition is normal case */ - for (i = 0; i < 10; i++) *(tmpfunc[i]) = '\0'; - while (scanpast('\t') != NULL) { - switch (*blockp) { - - case NEWFILE: /* save file name */ - skiprefchar(); - fetch_string_from_dbase(file, sizeof(file)); - if (*file == '\0') { /* if end of symbols */ - return NULL; - } - progress("Search", searchcount, nsrcfiles); - (void) strcpy(function, global); - break; - - case DEFINE: /* could be a macro */ - if (fileversion >= 10) { - skiprefchar(); - fetch_string_from_dbase(macro, sizeof(macro)); - } - break; - - case DEFINEEND: - *macro = '\0'; - break; - - case FCNDEF: /* save calling function name */ - skiprefchar(); - fetch_string_from_dbase(function, sizeof(function)); - for (i = 0; i < morefuns; i++) - if ( !strcmp(tmpfunc[i], function) ) - break; - if (i == morefuns) { - (void) strcpy(tmpfunc[morefuns], function); - if (++morefuns >= 10) morefuns = 9; - } - break; - - case FCNEND: - for (i = 0; i < morefuns; i++) - *(tmpfunc[i]) = '\0'; - morefuns = 0; - break; - - case FCNCALL: /* match function called to pattern */ - skiprefchar(); - if (match()) { - - /* output the file, calling function or macro, and source */ - if (*macro != '\0') { - putref(1, file, macro); - } - else { - tmpblockp = blockp; - for (i = 0; i < morefuns; i++) { - blockp = tmpblockp; - putref(1, file, tmpfunc[i]); - } - } - } - } - } - - return NULL; +/* find the functions calling this function */ + +char *findcalling(const char *pattern) { + char file[PATHLEN + 1]; /* source file name */ + char function[PATLEN + 1]; /* function name */ + char tmpfunc[10][PATLEN + 1]; /* 10 temporary function names */ + char macro[PATLEN + 1]; /* macro name */ + char *tmpblockp; + int morefuns, i; + + if(invertedindex == true) { + POSTING *p; + + findterm(pattern); + while((p = getposting()) != NULL) { + if(p->type == FCNCALL) { putpostingref(p, 0); } + } + return NULL; + } + /* find the next file name or function definition */ + *macro = '\0'; /* a macro can be inside a function, but not vice versa */ + tmpblockp = 0; + morefuns = 0; /* one function definition is normal case */ + for(i = 0; i < 10; i++) + *(tmpfunc[i]) = '\0'; + while(scanpast('\t') != NULL) { + switch(*blockp) { + + case NEWFILE: /* save file name */ + skiprefchar(); + fetch_string_from_dbase(file, sizeof(file)); + if(*file == '\0') { /* if end of symbols */ + return NULL; + } + progress("Search", searchcount, nsrcfiles); + (void)strcpy(function, global); + break; + + case DEFINE: /* could be a macro */ + if(fileversion >= 10) { + skiprefchar(); + fetch_string_from_dbase(macro, sizeof(macro)); + } + break; + + case DEFINEEND: + *macro = '\0'; + break; + + case FCNDEF: /* save calling function name */ + skiprefchar(); + fetch_string_from_dbase(function, sizeof(function)); + for(i = 0; i < morefuns; i++) + if(!strcmp(tmpfunc[i], function)) break; + if(i == morefuns) { + (void)strcpy(tmpfunc[morefuns], function); + if(++morefuns >= 10) morefuns = 9; + } + break; + + case FCNEND: + for(i = 0; i < morefuns; i++) + *(tmpfunc[i]) = '\0'; + morefuns = 0; + break; + + case FCNCALL: /* match function called to pattern */ + skiprefchar(); + if(match()) { + + /* output the file, calling function or macro, and source */ + if(*macro != '\0') { + putref(1, file, macro); + } else { + tmpblockp = blockp; + for(i = 0; i < morefuns; i++) { + blockp = tmpblockp; + putref(1, file, tmpfunc[i]); + } + } + } + } + } + + return NULL; } /* find the text in the source files */ -char * -findstring(const char *pattern) -{ - char egreppat[2 * PATLEN]; - char *cp = egreppat; - const char* pp; - - /* translate special characters in the regular expression */ - for (pp = pattern; *pp != '\0'; ++pp) { - if (strchr(".*[\\^$+?|()", *pp) != NULL) { - *cp++ = '\\'; - } - *cp++ = *pp; - } - *cp = '\0'; - - /* search the source files */ - return(findregexp(egreppat)); +char *findstring(const char *pattern) { + char egreppat[2 * PATLEN]; + char *cp = egreppat; + const char *pp; + + /* translate special characters in the regular expression */ + for(pp = pattern; *pp != '\0'; ++pp) { + if(strchr(".*[\\^$+?|()", *pp) != NULL) { *cp++ = '\\'; } + *cp++ = *pp; + } + *cp = '\0'; + + /* search the source files */ + return (findregexp(egreppat)); } /* find this regular expression in the source files */ -char * -findregexp(const char *egreppat) -{ - unsigned int i; - char *egreperror; - - /* compile the pattern */ - if ((egreperror = egrepinit(egreppat)) == NULL) { - - /* search the files */ - for (i = 0; i < nsrcfiles; ++i) { - char *file = filepath(srcfiles[i]); - - progress("Search", searchcount, nsrcfiles); - if (egrep(file, refsfound, "%s %ld ") < 0) { - posterr ("Cannot open file %s", file); - } - } - } - return(egreperror); +char *findregexp(const char *egreppat) { + unsigned int i; + char *egreperror; + + /* compile the pattern */ + if((egreperror = egrepinit(egreppat)) == NULL) { + + /* search the files */ + for(i = 0; i < nsrcfiles; ++i) { + char *file = filepath(srcfiles[i]); + + progress("Search", searchcount, nsrcfiles); + if(egrep(file, refsfound, "%s %ld ") < 0) { + posterr("Cannot open file %s", file); + } + } + } + return (egreperror); } /* find matching file names */ -char * -findfile(const char *dummy) -{ - unsigned int i; +char *findfile(const char *dummy) { + unsigned int i; - (void) dummy; /* unused argument */ + (void)dummy; /* unused argument */ - for (i = 0; i < nsrcfiles; ++i) { - char *s; + for(i = 0; i < nsrcfiles; ++i) { + char *s; - if (caseless == true) { - s = lcasify(srcfiles[i]); - } else { - s = srcfiles[i]; - } - if (regexec (®exp, s, (size_t)0, NULL, 0) == 0) { - (void) fprintf(refsfound, "%s 1 \n", - srcfiles[i]); - } - } + if(caseless == true) { + s = lcasify(srcfiles[i]); + } else { + s = srcfiles[i]; + } + if(regexec(®exp, s, (size_t)0, NULL, 0) == 0) { + (void)fprintf(refsfound, "%s 1 \n", srcfiles[i]); + } + } - return NULL; + return NULL; } /* find files #including this file */ -char * -findinclude(const char *pattern) -{ - char file[PATHLEN + 1]; /* source file name */ - - if (invertedindex == true) { - POSTING *p; - - findterm(pattern); - while ((p = getposting()) != NULL) { - if (p->type == INCLUDE) { - putpostingref(p, 0); - } - } - return NULL; - } - - /* find the next file name or function definition */ - while (scanpast('\t') != NULL) { - switch (*blockp) { - - case NEWFILE: /* save file name */ - skiprefchar(); - fetch_string_from_dbase(file, sizeof(file)); - if (*file == '\0') { /* if end of symbols */ - return NULL; - } - progress("Search", searchcount, nsrcfiles); - break; - - case INCLUDE: /* match function called to pattern */ - skiprefchar(); - skiprefchar(); /* skip global or local #include marker */ - if (match()) { - - /* output the file and source line */ - putref(0, file, global); - } - } - } - - return NULL; +char *findinclude(const char *pattern) { + char file[PATHLEN + 1]; /* source file name */ + + if(invertedindex == true) { + POSTING *p; + + findterm(pattern); + while((p = getposting()) != NULL) { + if(p->type == INCLUDE) { putpostingref(p, 0); } + } + return NULL; + } + + /* find the next file name or function definition */ + while(scanpast('\t') != NULL) { + switch(*blockp) { + + case NEWFILE: /* save file name */ + skiprefchar(); + fetch_string_from_dbase(file, sizeof(file)); + if(*file == '\0') { /* if end of symbols */ + return NULL; + } + progress("Search", searchcount, nsrcfiles); + break; + + case INCLUDE: /* match function called to pattern */ + skiprefchar(); + skiprefchar(); /* skip global or local #include marker */ + if(match()) { + + /* output the file and source line */ + putref(0, file, global); + } + } + } + + return NULL; } /* initialize */ -int -findinit(const char *pattern_) -{ - char* pattern = strdup(pattern_); - int r = NOERROR; - char buf[PATLEN + 3]; - bool isregexp = false; - int i; - char *s; - unsigned char c; - - /* HBB: be nice: free regexp before allocating a new one */ - if(isregexp_valid == true) - regfree(®exp); - - isregexp_valid = false; - - /* remove trailing white space */ - for (s = pattern + strlen(pattern) - 1; - isspace((unsigned char)*s); - --s) { - *s = '\0'; - } - - /* Make sure pattern is lowercased. Curses - * mode gets this right all on its own, but at least -L mode - * doesn't */ - if (caseless == true) { - pattern = lcasify(pattern); - } - - /* allow a partial match for a file name */ - if (field == FILENAME || field == INCLUDES) { - if (regcomp (®exp, pattern, REG_EXTENDED | REG_NOSUB) != 0) { - r = REGCMPERROR; - } else { - isregexp_valid = true; - } +int findinit(const char *pattern_) { + char *pattern = strdup(pattern_); + int r = NOERROR; + char buf[PATLEN + 3]; + bool isregexp = false; + int i; + char *s; + unsigned char c; + + /* HBB: be nice: free regexp before allocating a new one */ + if(isregexp_valid == true) regfree(®exp); + + isregexp_valid = false; + + /* remove trailing white space */ + for(s = pattern + strlen(pattern) - 1; isspace((unsigned char)*s); --s) { + *s = '\0'; + } + + /* Make sure pattern is lowercased. Curses + * mode gets this right all on its own, but at least -L mode + * doesn't */ + if(caseless == true) { pattern = lcasify(pattern); } + + /* allow a partial match for a file name */ + if(field == FILENAME || field == INCLUDES) { + if(regcomp(®exp, pattern, REG_EXTENDED | REG_NOSUB) != 0) { + r = REGCMPERROR; + } else { + isregexp_valid = true; + } goto end; - } - /* see if the pattern is a regular expression */ - if (strpbrk(pattern, "^.[{*+$|(") != NULL) { - isregexp = true; - } else { - /* check for a valid C symbol */ - s = pattern; - if (!isalpha((unsigned char)*s) && *s != '_') { - r = NOTSYMBOL; + } + /* see if the pattern is a regular expression */ + if(strpbrk(pattern, "^.[{*+$|(") != NULL) { + isregexp = true; + } else { + /* check for a valid C symbol */ + s = pattern; + if(!isalpha((unsigned char)*s) && *s != '_') { + r = NOTSYMBOL; goto end; - } - while (*++s != '\0') { - if (!isalnum((unsigned char)*s) && *s != '_') { - r = NOTSYMBOL; + } + while(*++s != '\0') { + if(!isalnum((unsigned char)*s) && *s != '_') { + r = NOTSYMBOL; goto end; - } - } - /* look for use of the -T option (truncate symbol to 8 - characters) on a database not built with -T */ - if (trun_syms == true && isuptodate == true && - dbtruncated == false && s - pattern >= 8) { - (void) strcpy(pattern + 8, ".*"); - isregexp = true; - } - } - /* if this is a regular expression or letter case is to be ignored */ - /* or there is an inverted index */ - if (isregexp == true || caseless == true || invertedindex == true) { - - /* remove a leading ^ */ - s = pattern; - if (*s == '^') { - (void) strcpy(newpat, s + 1); - (void) strcpy(s, newpat); - } - /* remove a trailing $ */ - i = strlen(s) - 1; - if (s[i] == '$') { - if (i > 0 && s[i-1] == '\\' ) { - s[i-1] = '$'; - } - s[i] = '\0'; - } - /* if requested, try to truncate a C symbol pattern */ - if (trun_syms == true && strpbrk(s, "[{*+") == NULL) { - s[8] = '\0'; - } - /* must be an exact match */ - /* note: regcomp doesn't recognize ^*keypad$ as a syntax error - unless it is given as a single arg */ - (void) snprintf(buf, sizeof(buf), "^%s$", s); - if (regcomp (®exp, buf, REG_EXTENDED | REG_NOSUB) != 0) { - r = REGCMPERROR; + } + } + /* look for use of the -T option (truncate symbol to 8 + characters) on a database not built with -T */ + if(trun_syms == true && isuptodate == true && dbtruncated == false && + s - pattern >= 8) { + (void)strcpy(pattern + 8, ".*"); + isregexp = true; + } + } + /* if this is a regular expression or letter case is to be ignored */ + /* or there is an inverted index */ + if(isregexp == true || caseless == true || invertedindex == true) { + + /* remove a leading ^ */ + s = pattern; + if(*s == '^') { + (void)strcpy(newpat, s + 1); + (void)strcpy(s, newpat); + } + /* remove a trailing $ */ + i = strlen(s) - 1; + if(s[i] == '$') { + if(i > 0 && s[i - 1] == '\\') { s[i - 1] = '$'; } + s[i] = '\0'; + } + /* if requested, try to truncate a C symbol pattern */ + if(trun_syms == true && strpbrk(s, "[{*+") == NULL) { s[8] = '\0'; } + /* must be an exact match */ + /* note: regcomp doesn't recognize ^*keypad$ as a syntax error + unless it is given as a single arg */ + (void)snprintf(buf, sizeof(buf), "^%s$", s); + if(regcomp(®exp, buf, REG_EXTENDED | REG_NOSUB) != 0) { + r = REGCMPERROR; goto end; - } - else - { - isregexp_valid = true; - } - } - else { - /* if requested, truncate a C symbol pattern */ - if (trun_syms == true && field <= CALLING) { - pattern[8] = '\0'; - } - /* compress the string pattern for matching */ - s = cpattern; - for (i = 0; (c = pattern[i]) != '\0'; ++i) { - if (IS_A_DICODE(c, pattern[i + 1])) { - c = DICODE_COMPRESS(c, pattern[i + 1]); - ++i; - } - *s++ = c; - } - *s = '\0'; - } - - end: + } else { + isregexp_valid = true; + } + } else { + /* if requested, truncate a C symbol pattern */ + if(trun_syms == true && field <= CALLING) { pattern[8] = '\0'; } + /* compress the string pattern for matching */ + s = cpattern; + for(i = 0; (c = pattern[i]) != '\0'; ++i) { + if(IS_A_DICODE(c, pattern[i + 1])) { + c = DICODE_COMPRESS(c, pattern[i + 1]); + ++i; + } + *s++ = c; + } + *s = '\0'; + } + +end: free(pattern); - return r; + return r; } -void -findcleanup(void) -{ - /* discard any regular expression */ +void findcleanup(void) { + /* discard any regular expression */ } /* match the pattern to the string */ -static bool -match(void) -{ - char string[PATLEN + 1]; - - /* see if this is a regular expression pattern */ - if (isregexp_valid == true) { - fetch_string_from_dbase(string, sizeof(string)); - if (*string == '\0') { - return(false); - } - if (caseless == true) { - return (regexec (®exp, lcasify(string), (size_t)0, NULL, 0) ? false : true); - } - else { - return (regexec (®exp, string, (size_t)0, NULL, 0) ? false : true); - } - } - /* it is a string pattern */ - return((bool) (*blockp == cpattern[0] && matchrest())); +static bool match(void) { + char string[PATLEN + 1]; + + /* see if this is a regular expression pattern */ + if(isregexp_valid == true) { + fetch_string_from_dbase(string, sizeof(string)); + if(*string == '\0') { return (false); } + if(caseless == true) { + return (regexec(®exp, lcasify(string), (size_t)0, NULL, 0) ? false : true); + } else { + return (regexec(®exp, string, (size_t)0, NULL, 0) ? false : true); + } + } + /* it is a string pattern */ + return ((bool)(*blockp == cpattern[0] && matchrest())); } /* match the rest of the pattern to the name */ -static bool -matchrest(void) -{ - int i = 1; - - skiprefchar(); - do { - while (*blockp == cpattern[i]) { - ++blockp; - ++i; - } - } while (*(blockp + 1) == '\0' && read_block() != NULL); - - if (*blockp == '\n' && cpattern[i] == '\0') { - return(true); - } - return(false); +static bool matchrest(void) { + int i = 1; + + skiprefchar(); + do { + while(*blockp == cpattern[i]) { + ++blockp; + ++i; + } + } while(*(blockp + 1) == '\0' && read_block() != NULL); + + if(*blockp == '\n' && cpattern[i] == '\0') { return (true); } + return (false); } /* put the reference into the file */ -static void -putref(int seemore, const char *file, const char *func) -{ - FILE *output; - - if (strcmp(func, global) == 0) { - output = refsfound; - } - else { - output = nonglobalrefs; - } - (void) fprintf(output, "%s %s ", file, func); - putsource(seemore, output); +static void putref(int seemore, const char *file, const char *func) { + FILE *output; + + if(strcmp(func, global) == 0) { + output = refsfound; + } else { + output = nonglobalrefs; + } + (void)fprintf(output, "%s %s ", file, func); + putsource(seemore, output); } /* put the source line into the file */ -static void -putsource(int seemore, FILE *output) -{ - char *tmpblockp; - char *cp, nextc = '\0'; - bool Change = false, retreat = false; - - if (fileversion <= 5) { - (void) scanpast(' '); - putline(output); - (void) putc('\n', output); - return; - } - /* scan back to the beginning of the source line */ - cp = tmpblockp = blockp; - while (*cp != '\n' || nextc != '\n') { - nextc = *cp; - if (--cp < block) { - retreat = true; - /* read the previous block */ - (void) dbseek((blocknumber - 1) * BUFSIZ); - cp = block + (BUFSIZ - 1); - } - } - blockp = cp; - if (*blockp != '\n' || getrefchar() != '\n' || - (!isdigit(getrefchar()) && fileversion >= 12)) { - postfatal("Internal error: cannot get source line from database"); - /* NOTREACHED */ - } - /* until a double newline is found */ - do { - /* skip a symbol type */ - if (*blockp == '\t') { - /* if retreat == true, that means tmpblockp and blockp - * point to different blocks. Offset comparison should - * falseT be performed until they point to the same block. - */ - if (seemore && Change == false && retreat == false && - blockp > tmpblockp) { - Change = true; - cp = blockp; - } - skiprefchar(); - skiprefchar(); - } - /* output a piece of the source line */ - putline(output); - if (retreat == true) retreat = false; - } while (blockp != NULL && getrefchar() != '\n'); - (void) putc('\n', output); - if (Change == true) blockp = cp; +static void putsource(int seemore, FILE *output) { + char *tmpblockp; + char *cp, nextc = '\0'; + bool Change = false, retreat = false; + + if(fileversion <= 5) { + (void)scanpast(' '); + putline(output); + (void)putc('\n', output); + return; + } + /* scan back to the beginning of the source line */ + cp = tmpblockp = blockp; + while(*cp != '\n' || nextc != '\n') { + nextc = *cp; + if(--cp < block) { + retreat = true; + /* read the previous block */ + (void)dbseek((blocknumber - 1) * BUFSIZ); + cp = block + (BUFSIZ - 1); + } + } + blockp = cp; + if(*blockp != '\n' || getrefchar() != '\n' || + (!isdigit(getrefchar()) && fileversion >= 12)) { + postfatal("Internal error: cannot get source line from database"); + /* NOTREACHED */ + } + /* until a double newline is found */ + do { + /* skip a symbol type */ + if(*blockp == '\t') { + /* if retreat == true, that means tmpblockp and blockp + * point to different blocks. Offset comparison should + * falseT be performed until they point to the same block. + */ + if(seemore && Change == false && retreat == false && blockp > tmpblockp) { + Change = true; + cp = blockp; + } + skiprefchar(); + skiprefchar(); + } + /* output a piece of the source line */ + putline(output); + if(retreat == true) retreat = false; + } while(blockp != NULL && getrefchar() != '\n'); + (void)putc('\n', output); + if(Change == true) blockp = cp; } /* put the rest of the cross-reference line into the file */ -static void -putline(FILE *output) -{ - char *cp; - unsigned c; - - setmark('\n'); - cp = blockp; - do { - while ((c = (unsigned)(*cp)) != '\n') { - - /* check for a compressed digraph */ - if (c > '\177') { - c &= 0177; - (void) putc(dichar1[c / 8], output); - (void) putc(dichar2[c & 7], output); - } - /* check for a compressed keyword */ - else if (c < ' ') { - (void) fputs(keyword[c].text, output); - if (keyword[c].delim != '\0') { - (void) putc(' ', output); - } - if (keyword[c].delim == '(') { - (void) putc('(', output); - } - } - else { - (void) putc((int) c, output); - } - ++cp; - } - } while (*(cp + 1) == '\0' && (cp = read_block()) != NULL); - blockp = cp; +static void putline(FILE *output) { + char *cp; + unsigned c; + + setmark('\n'); + cp = blockp; + do { + while((c = (unsigned)(*cp)) != '\n') { + + /* check for a compressed digraph */ + if(c > '\177') { + c &= 0177; + (void)putc(dichar1[c / 8], output); + (void)putc(dichar2[c & 7], output); + } + /* check for a compressed keyword */ + else if(c < ' ') { + (void)fputs(keyword[c].text, output); + if(keyword[c].delim != '\0') { (void)putc(' ', output); } + if(keyword[c].delim == '(') { (void)putc('(', output); } + } else { + (void)putc((int)c, output); + } + ++cp; + } + } while(*(cp + 1) == '\0' && (cp = read_block()) != NULL); + blockp = cp; } - /* put the rest of the cross-reference line into the string */ -void -fetch_string_from_dbase(char *s, size_t length) -{ - char *cp; - unsigned int c; - - assert(length > sizeof (char *)); - - setmark('\n'); - cp = blockp; - do { - while (length > 1 && (c = (unsigned int)(*cp)) != '\n') { - if (c >= 0x80 && length > 2) { - c &= 0x7f; - *s++ = dichar1[c / 8]; - *s++ = dichar2[c & 7]; - length -= 2; - } else { - *s++ = c; - length--; - } - ++cp; - } - } while (length > 0 && cp[1] == '\0' && (cp = read_block()) != NULL); - blockp = cp; - *s = '\0'; +void fetch_string_from_dbase(char *s, size_t length) { + char *cp; + unsigned int c; + + assert(length > sizeof(char *)); + + setmark('\n'); + cp = blockp; + do { + while(length > 1 && (c = (unsigned int)(*cp)) != '\n') { + if(c >= 0x80 && length > 2) { + c &= 0x7f; + *s++ = dichar1[c / 8]; + *s++ = dichar2[c & 7]; + length -= 2; + } else { + *s++ = c; + length--; + } + ++cp; + } + } while(length > 0 && cp[1] == '\0' && (cp = read_block()) != NULL); + blockp = cp; + *s = '\0'; } - /* scan past the next occurence of this character in the cross-reference */ -char * -scanpast(char c) -{ - char *cp; - - setmark(c); - cp = blockp; - do { /* innermost loop optimized to only one test */ - while (*cp != c) { - ++cp; - } - } while (*(cp + 1) == '\0' && (cp = read_block()) != NULL); - blockp = cp; - if (cp != NULL) { - skiprefchar(); /* skip the found character */ - } - return(blockp); +char *scanpast(char c) { + char *cp; + + setmark(c); + cp = blockp; + do { /* innermost loop optimized to only one test */ + while(*cp != c) { + ++cp; + } + } while(*(cp + 1) == '\0' && (cp = read_block()) != NULL); + blockp = cp; + if(cp != NULL) { skiprefchar(); /* skip the found character */ } + return (blockp); } /* read a block of the cross-reference */ /* HBB 20040430: renamed from readblock(), to avoid name clash on QNX */ -char * -read_block(void) -{ - /* read the next block */ - blocklen = read(symrefs, block, BUFSIZ); - blockp = block; - - /* add the search character and end-of-block mark */ - block[blocklen] = blockmark; - block[blocklen + 1] = '\0'; - - /* return NULL on end-of-file */ - if (blocklen == 0) { - blockp = NULL; - } - else { - ++blocknumber; - } - return(blockp); +char *read_block(void) { + /* read the next block */ + blocklen = read(symrefs, block, BUFSIZ); + blockp = block; + + /* add the search character and end-of-block mark */ + block[blocklen] = blockmark; + block[blocklen + 1] = '\0'; + + /* return NULL on end-of-file */ + if(blocklen == 0) { + blockp = NULL; + } else { + ++blocknumber; + } + return (blockp); } -static char * -lcasify(const char *s) -{ - static char ls[PATLEN+1]; /* largest possible match string */ - char *lptr = ls; - - while(*s) { - *lptr = tolower((unsigned char)*s); - lptr++; - s++; - } - *lptr = '\0'; - return ls; +static char *lcasify(const char *s) { + static char ls[PATLEN + 1]; /* largest possible match string */ + char *lptr = ls; + + while(*s) { + *lptr = tolower((unsigned char)*s); + lptr++; + s++; + } + *lptr = '\0'; + return ls; } /* find the functions called by this function */ @@ -1086,380 +979,347 @@ lcasify(const char *s) * too. Implemented as a pointer to static storage containing 'y' or * 'n', for the boolean result values true and false */ -char * -findcalledby(const char *pattern) -{ - char file[PATHLEN + 1]; /* source file name */ - static char found_caller = 'n'; /* seen calling function? */ - bool macro = false; - - if (invertedindex == true) { - POSTING *p; - - findterm(pattern); - while ((p = getposting()) != NULL) { - switch (p->type) { - case DEFINE: /* could be a macro */ - case FCNDEF: - if (dbseek(p->lineoffset) != -1 && - scanpast('\t') != NULL) { /* skip def */ - found_caller = 'y'; - findcalledbysub(srcfiles[p->fileindex], macro); - } - } - } - return(&found_caller); - } - /* find the function definition(s) */ - while (scanpast('\t') != NULL) { - switch (*blockp) { - - case NEWFILE: - skiprefchar(); /* save file name */ - fetch_string_from_dbase(file, sizeof(file)); - if (*file == '\0') { /* if end of symbols */ - return(&found_caller); - } - progress("Search", searchcount, nsrcfiles); - break; - - case DEFINE: /* could be a macro */ - if (fileversion < 10) { - break; - } - macro = true; - /* FALLTHROUGH */ - - case FCNDEF: - skiprefchar(); /* match name to pattern */ - if (match()) { - found_caller = 'y'; - findcalledbysub(file, macro); - } - break; - } - } - - return (&found_caller); +char *findcalledby(const char *pattern) { + char file[PATHLEN + 1]; /* source file name */ + static char found_caller = 'n'; /* seen calling function? */ + bool macro = false; + + if(invertedindex == true) { + POSTING *p; + + findterm(pattern); + while((p = getposting()) != NULL) { + switch(p->type) { + case DEFINE: /* could be a macro */ + case FCNDEF: + if(dbseek(p->lineoffset) != -1 && + scanpast('\t') != NULL) { /* skip def */ + found_caller = 'y'; + findcalledbysub(srcfiles[p->fileindex], macro); + } + } + } + return (&found_caller); + } + /* find the function definition(s) */ + while(scanpast('\t') != NULL) { + switch(*blockp) { + + case NEWFILE: + skiprefchar(); /* save file name */ + fetch_string_from_dbase(file, sizeof(file)); + if(*file == '\0') { /* if end of symbols */ + return (&found_caller); + } + progress("Search", searchcount, nsrcfiles); + break; + + case DEFINE: /* could be a macro */ + if(fileversion < 10) { break; } + macro = true; + /* FALLTHROUGH */ + + case FCNDEF: + skiprefchar(); /* match name to pattern */ + if(match()) { + found_caller = 'y'; + findcalledbysub(file, macro); + } + break; + } + } + + return (&found_caller); } /* find this term, which can be a regular expression */ -static void -findterm(const char *pattern) -{ - char *s; - int len; - char prefix[PATLEN + 1]; - char term[PATLEN + 1]; - - npostings = 0; /* will be non-zero after database built */ - lastfcnoffset = 0; /* clear the last function name found */ - boolclear(); /* clear the posting set */ - - /* get the string prefix (if any) of the regular expression */ - (void) strcpy(prefix, pattern); - if ((s = strpbrk(prefix, ".[{*+")) != NULL) { - *s = '\0'; - } - /* if letter case is to be ignored */ - if (caseless == true) { - - /* convert the prefix to upper case because it is lexically - less than lower case */ - s = prefix; - while (*s != '\0') { - *s = toupper((unsigned char)*s); - ++s; - } - } - /* find the term lexically >= the prefix */ - (void) invfind(&invcontrol, prefix); - if (caseless == true) { /* restore lower case */ - (void) strcpy(prefix, lcasify(prefix)); - } - /* a null prefix matches the null term in the inverted index, - so move to the first real term */ - if (*prefix == '\0') { - (void) invforward(&invcontrol); - } - len = strlen(prefix); - do { - (void) invterm(&invcontrol, term); /* get the term */ - s = term; - if (caseless == true) { - s = lcasify(s); /* make it lower case */ - } - /* if it matches */ - if (regexec (®exp, s, (size_t)0, NULL, 0) == 0) { - - /* add its postings to the set */ - if ((postingp = boolfile(&invcontrol, &npostings, bool_OR)) == NULL) { - break; - } - } - /* if there is a prefix */ - else if (len > 0) { - - /* if ignoring letter case and the term is out of the - range of possible matches */ - if (caseless == true) { - if (strncmp(term, prefix, len) > 0) { - break; /* stop searching */ - } - } - /* if using letter case and the prefix doesn't match */ - else if (strncmp(term, prefix, len) != 0) { - break; /* stop searching */ - } - } - /* display progress about every three seconds */ - if (++searchcount % 50 == 0) { - progress("Symbols matched", searchcount, totalterms); - } - } while (invforward(&invcontrol)); /* while didn't wrap around */ - - /* initialize the progress message for retrieving the references */ - searchcount = 0; - postingsfound = npostings; +static void findterm(const char *pattern) { + char *s; + int len; + char prefix[PATLEN + 1]; + char term[PATLEN + 1]; + + npostings = 0; /* will be non-zero after database built */ + lastfcnoffset = 0; /* clear the last function name found */ + boolclear(); /* clear the posting set */ + + /* get the string prefix (if any) of the regular expression */ + (void)strcpy(prefix, pattern); + if((s = strpbrk(prefix, ".[{*+")) != NULL) { *s = '\0'; } + /* if letter case is to be ignored */ + if(caseless == true) { + + /* convert the prefix to upper case because it is lexically + less than lower case */ + s = prefix; + while(*s != '\0') { + *s = toupper((unsigned char)*s); + ++s; + } + } + /* find the term lexically >= the prefix */ + (void)invfind(&invcontrol, prefix); + if(caseless == true) { /* restore lower case */ + (void)strcpy(prefix, lcasify(prefix)); + } + /* a null prefix matches the null term in the inverted index, + so move to the first real term */ + if(*prefix == '\0') { (void)invforward(&invcontrol); } + len = strlen(prefix); + do { + (void)invterm(&invcontrol, term); /* get the term */ + s = term; + if(caseless == true) { s = lcasify(s); /* make it lower case */ } + /* if it matches */ + if(regexec(®exp, s, (size_t)0, NULL, 0) == 0) { + + /* add its postings to the set */ + if((postingp = boolfile(&invcontrol, &npostings, bool_OR)) == NULL) { break; } + } + /* if there is a prefix */ + else if(len > 0) { + + /* if ignoring letter case and the term is out of the + range of possible matches */ + if(caseless == true) { + if(strncmp(term, prefix, len) > 0) { break; /* stop searching */ } + } + /* if using letter case and the prefix doesn't match */ + else if(strncmp(term, prefix, len) != 0) { + break; /* stop searching */ + } + } + /* display progress about every three seconds */ + if(++searchcount % 50 == 0) { + progress("Symbols matched", searchcount, totalterms); + } + } while(invforward(&invcontrol)); /* while didn't wrap around */ + + /* initialize the progress message for retrieving the references */ + searchcount = 0; + postingsfound = npostings; } /* get the next posting for this term */ -static POSTING * -getposting(void) -{ - if (npostings-- <= 0) { - return(NULL); - } - /* display progress about every three seconds */ - if (++searchcount % 100 == 0) { - progress("Possible references retrieved", searchcount, - postingsfound); - } - return(postingp++); +static POSTING *getposting(void) { + if(npostings-- <= 0) { return (NULL); } + /* display progress about every three seconds */ + if(++searchcount % 100 == 0) { + progress("Possible references retrieved", searchcount, postingsfound); + } + return (postingp++); } /* put the posting reference into the file */ -static void -putpostingref(POSTING *p, const char *pat) -{ - // initialize function to "unknown" so that the first line of temp1 - // is properly formed if symbol matches a header file entry first time - static char function[PATLEN + 1] = "unknown";/* function name */ - - if (p->fcnoffset == 0) { - if (p->type == FCNDEF) { /* need to find the function name */ - if (dbseek(p->lineoffset) != -1) { - scanpast(FCNDEF); - fetch_string_from_dbase(function, sizeof(function)); - } - } - else if (p->type != FCNCALL) { - strcpy(function, global); - } - } - else if (p->fcnoffset != lastfcnoffset) { - if (dbseek(p->fcnoffset) != -1) { - fetch_string_from_dbase(function, sizeof(function)); - lastfcnoffset = p->fcnoffset; - } - } - if (dbseek(p->lineoffset) != -1) { - if (pat) - putref(0, srcfiles[p->fileindex], pat); - else - putref(0, srcfiles[p->fileindex], function); - } +static void putpostingref(POSTING *p, const char *pat) { + // initialize function to "unknown" so that the first line of temp1 + // is properly formed if symbol matches a header file entry first time + static char function[PATLEN + 1] = "unknown"; /* function name */ + + if(p->fcnoffset == 0) { + if(p->type == FCNDEF) { /* need to find the function name */ + if(dbseek(p->lineoffset) != -1) { + scanpast(FCNDEF); + fetch_string_from_dbase(function, sizeof(function)); + } + } else if(p->type != FCNCALL) { + strcpy(function, global); + } + } else if(p->fcnoffset != lastfcnoffset) { + if(dbseek(p->fcnoffset) != -1) { + fetch_string_from_dbase(function, sizeof(function)); + lastfcnoffset = p->fcnoffset; + } + } + if(dbseek(p->lineoffset) != -1) { + if(pat) + putref(0, srcfiles[p->fileindex], pat); + else + putref(0, srcfiles[p->fileindex], function); + } } /* seek to the database offset */ -long -dbseek(long offset) -{ - long n; - int rc = 0; - - if ((n = offset / BUFSIZ) != blocknumber) { - if ((rc = lseek(symrefs, n * BUFSIZ, 0)) == -1) { - myperror("Lseek failed"); - (void) sleep(3); - return(rc); - } - (void) read_block(); - blocknumber = n; - } - blockp = block + offset % BUFSIZ; - return(rc); +long dbseek(long offset) { + long n; + int rc = 0; + + if((n = offset / BUFSIZ) != blocknumber) { + if((rc = lseek(symrefs, n * BUFSIZ, 0)) == -1) { + myperror("Lseek failed"); + (void)sleep(3); + return (rc); + } + (void)read_block(); + blocknumber = n; + } + blockp = block + offset % BUFSIZ; + return (rc); } -static void -findcalledbysub(const char *file, bool macro) -{ - /* find the next function call or the end of this function */ - while (scanpast('\t') != NULL) { - switch (*blockp) { - - case DEFINE: /* #define inside a function */ - if (fileversion >= 10) { /* skip it */ - while (scanpast('\t') != NULL && - *blockp != DEFINEEND) - ; - } - break; - - case FCNCALL: /* function call */ - - /* output the file name */ - (void) fprintf(refsfound, "%s ", file); - - /* output the function name */ - skiprefchar(); - putline(refsfound); - (void) putc(' ', refsfound); - - /* output the source line */ - putsource(1, refsfound); - break; - - case DEFINEEND: /* #define end */ - - if (invertedindex == false) { - if (macro == true) { - return; - } - break; /* inside a function */ - } - /* FALLTHROUGH */ - - case FCNDEF: /* function end (pre 9.5) */ - - if (invertedindex == false) break; - /* FALLTHROUGH */ - - case FCNEND: /* function end */ - case NEWFILE: /* file end */ - return; - } - } +static void findcalledbysub(const char *file, bool macro) { + /* find the next function call or the end of this function */ + while(scanpast('\t') != NULL) { + switch(*blockp) { + + case DEFINE: /* #define inside a function */ + if(fileversion >= 10) { /* skip it */ + while(scanpast('\t') != NULL && *blockp != DEFINEEND) + ; + } + break; + + case FCNCALL: /* function call */ + + /* output the file name */ + (void)fprintf(refsfound, "%s ", file); + + /* output the function name */ + skiprefchar(); + putline(refsfound); + (void)putc(' ', refsfound); + + /* output the source line */ + putsource(1, refsfound); + break; + + case DEFINEEND: /* #define end */ + + if(invertedindex == false) { + if(macro == true) { return; } + break; /* inside a function */ + } + /* FALLTHROUGH */ + + case FCNDEF: /* function end (pre 9.5) */ + + if(invertedindex == false) break; + /* FALLTHROUGH */ + + case FCNEND: /* function end */ + case NEWFILE: /* file end */ + return; + } + } } /* open the references found file for writing */ -bool -writerefsfound(void) -{ - if (refsfound == NULL) { - if ((refsfound = myfopen(temp1, "wb")) == NULL) { - cannotopen(temp1); - return(false); - } - } else { - (void) fclose(refsfound); - if ( (refsfound = myfopen(temp1, "wb")) == NULL) { - postmsg("Cannot reopen temporary file"); - return(false); - } - } - return(true); +bool writerefsfound(void) { + if(refsfound == NULL) { + if((refsfound = myfopen(temp1, "wb")) == NULL) { + cannotopen(temp1); + return (false); + } + } else { + (void)fclose(refsfound); + if((refsfound = myfopen(temp1, "wb")) == NULL) { + postmsg("Cannot reopen temporary file"); + return (false); + } + } + return (true); } /* Perform token search based on "field" */ -bool -search(const char* query) -{ - char msg[MSGLEN+1]; - char *findresult = NULL; /* find function output */ - bool funcexist = true; /* find "function" error */ - FINDINIT rc = NOERROR; /* findinit return code */ - sighandler_t savesig; /* old value of signal */ - FP f; /* searching function */ - int c; - - /* open the references found file for writing */ - if (writerefsfound() == false) { - return(false); - } - /* find the pattern - stop on an interrupt */ - if (linemode == false) { - postmsg("Searching"); - } - searchcount = 0; - savesig = signal(SIGINT, jumpback); - if (sigsetjmp(env, 1) == 0) { - f = field_searchers[field]; - if (f == findregexp || f == findstring) { - findresult = (*f)(query); - } else { - if ((nonglobalrefs = myfopen(temp2, "wb")) == NULL) { - cannotopen(temp2); - return(false); - } - if ((rc = findinit(query)) == NOERROR) { - (void) dbseek(0L); /* read the first block */ - findresult = (*f)(query); - if (f == findcalledby) - funcexist = (*findresult == 'y'); - findcleanup(); - - /* append the non-global references */ - (void) fclose(nonglobalrefs); - if ((nonglobalrefs = myfopen(temp2, "rb")) - == NULL) { - cannotopen(temp2); - return(false); - } - while ((c = getc(nonglobalrefs)) != EOF) { - (void) putc(c, refsfound); - } - } - (void) fclose(nonglobalrefs); - } - } - signal(SIGINT, savesig); - - /* rewind the cross-reference file */ - (void) lseek(symrefs, (long) 0, 0); - - /* reopen the references found file for reading */ - (void) fclose(refsfound); - if ((refsfound = myfopen(temp1, "rb")) == NULL) { - cannotopen(temp1); - return(false); - } - nextline = 1; - totallines = 0; - disprefs = 0; - - /* see if it is empty */ - if ((c = getc(refsfound)) == EOF) { - if (findresult != NULL) { - (void) snprintf(msg, sizeof(msg), "Egrep %s in this pattern: %s", - findresult, query); - } else if (rc == NOTSYMBOL) { - (void) snprintf(msg, sizeof(msg), "This is not a C symbol: %s", - query); - } else if (rc == REGCMPERROR) { - (void) snprintf(msg, sizeof(msg), "Error in this regcomp(3) regular expression: %s", - query); - - } else if (funcexist == false) { - (void) snprintf(msg, sizeof(msg), "Function definition does not exist: %s", - query); - } else { - (void) snprintf(msg, sizeof(msg), "Could not find the %s: %s", - fields[field].text2, query); - } +bool search(const char *query) { + char msg[MSGLEN + 1]; + char *findresult = NULL; /* find function output */ + bool funcexist = true; /* find "function" error */ + FINDINIT rc = NOERROR; /* findinit return code */ + sighandler_t savesig; /* old value of signal */ + FP f; /* searching function */ + int c; + + /* open the references found file for writing */ + if(writerefsfound() == false) { return (false); } + /* find the pattern - stop on an interrupt */ + if(linemode == false) { postmsg("Searching"); } + searchcount = 0; + savesig = signal(SIGINT, jumpback); + if(sigsetjmp(env, 1) == 0) { + f = field_searchers[field]; + if(f == findregexp || f == findstring) { + findresult = (*f)(query); + } else { + if((nonglobalrefs = myfopen(temp2, "wb")) == NULL) { + cannotopen(temp2); + return (false); + } + if((rc = findinit(query)) == NOERROR) { + (void)dbseek(0L); /* read the first block */ + findresult = (*f)(query); + if(f == findcalledby) funcexist = (*findresult == 'y'); + findcleanup(); + + /* append the non-global references */ + (void)fclose(nonglobalrefs); + if((nonglobalrefs = myfopen(temp2, "rb")) == NULL) { + cannotopen(temp2); + return (false); + } + while((c = getc(nonglobalrefs)) != EOF) { + (void)putc(c, refsfound); + } + } + (void)fclose(nonglobalrefs); + } + } + signal(SIGINT, savesig); + + /* rewind the cross-reference file */ + (void)lseek(symrefs, (long)0, 0); + + /* reopen the references found file for reading */ + (void)fclose(refsfound); + if((refsfound = myfopen(temp1, "rb")) == NULL) { + cannotopen(temp1); + return (false); + } + nextline = 1; + totallines = 0; + disprefs = 0; + + /* see if it is empty */ + if((c = getc(refsfound)) == EOF) { + if(findresult != NULL) { + (void)snprintf(msg, + sizeof(msg), + "Egrep %s in this pattern: %s", + findresult, + query); + } else if(rc == NOTSYMBOL) { + (void)snprintf(msg, sizeof(msg), "This is not a C symbol: %s", query); + } else if(rc == REGCMPERROR) { + (void)snprintf(msg, + sizeof(msg), + "Error in this regcomp(3) regular expression: %s", + query); + + } else if(funcexist == false) { + (void)snprintf(msg, + sizeof(msg), + "Function definition does not exist: %s", + query); + } else { + (void)snprintf(msg, + sizeof(msg), + "Could not find the %s: %s", + fields[field].text2, + query); + } postmsg(msg); - return(false); - } - /* put back the character read */ - (void) ungetc(c, refsfound); + return (false); + } + /* put back the character read */ + (void)ungetc(c, refsfound); - countrefs(); + countrefs(); - window_change |= CH_RESULT; + window_change |= CH_RESULT; - return(true); + return (true); } diff --git a/src/global.h b/src/global.h index 869b076..133680b 100644 --- a/src/global.h +++ b/src/global.h @@ -43,46 +43,47 @@ #include #include #include -#include /* isalpha, isdigit, etc. */ -#include /* SIGINT and SIGQUIT */ -#include /* standard I/O package */ -#include /* standard library functions */ +#include /* isalpha, isdigit, etc. */ +#include /* SIGINT and SIGQUIT */ +#include /* standard I/O package */ +#include /* standard library functions */ #include #include #include -#include /* string functions */ +#include /* string functions */ -#include "constants.h" /* misc. constants */ -#include "invlib.h" /* inverted index library */ -#include "library.h" /* library function return values */ -#include "stddef.h" /* size_t */ +#include "constants.h" /* misc. constants */ +#include "invlib.h" /* inverted index library */ +#include "library.h" /* library function return values */ +#include "stddef.h" /* size_t */ typedef void (*sighandler_t)(int); -typedef struct { /* mouse action */ - int button; - int percent; - int x1; - int y1; - int x2; - int y2; +typedef struct { /* mouse action */ + int button; + int percent; + int x1; + int y1; + int x2; + int y2; } MOUSE; -struct cmd { /* command history struct */ - struct cmd *prev, *next; /* list ptrs */ - int field; /* input field number */ - char *text; /* input field text */ +struct cmd { /* command history struct */ + struct cmd *prev, *next; /* list ptrs */ + int field; /* input field number */ + char *text; /* input field text */ }; enum { - CH_NONE = 0x0000, - CH_RESULT = 0x0001 << 0, - CH_INPUT = 0x0001 << 1, - CH_MODE = 0x0001 << 2, - CH_HELP = 0x0001 << 3, /* do NOT add to CH_ALL */ - CH_ALL = CH_RESULT | CH_INPUT | CH_MODE + CH_NONE = 0x0000, + CH_RESULT = 0x0001 << 0, + CH_INPUT = 0x0001 << 1, + CH_MODE = 0x0001 << 2, + CH_HELP = 0x0001 << 3, /* do NOT add to CH_ALL */ + CH_ALL = CH_RESULT | CH_INPUT | CH_MODE }; + enum { INPUT_NORMAL, INPUT_APPEND, @@ -97,224 +98,225 @@ enum { #endif /* digraph data for text compression */ -extern char dichar1[]; /* 16 most frequent first chars */ -extern char dichar2[]; /* 8 most frequent second chars - using the above as first chars */ -extern char dicode1[]; /* digraph first character code */ -extern char dicode2[]; /* digraph second character code */ +extern char dichar1[]; /* 16 most frequent first chars */ +extern char dichar2[]; /* 8 most frequent second chars + using the above as first chars */ +extern char dicode1[]; /* digraph first character code */ +extern char dicode2[]; /* digraph second character code */ /* and some macros to help using dicodes: */ /* Check if a given pair of chars is compressable as a dicode: */ -#define IS_A_DICODE(inchar1, inchar2) \ - (dicode1[(unsigned char)(inchar1)] && dicode2[(unsigned char)(inchar2)]) +#define IS_A_DICODE(inchar1, inchar2) \ + (dicode1[(unsigned char)(inchar1)] && dicode2[(unsigned char)(inchar2)]) /* Combine the pair into a dicode */ -#define DICODE_COMPRESS(inchar1, inchar2) \ - ((0200 - 2) + dicode1[(unsigned char)(inchar1)] \ - + dicode2[(unsigned char)(inchar2)]) +#define DICODE_COMPRESS(inchar1, inchar2) \ + ((0200 - 2) + dicode1[(unsigned char)(inchar1)] + dicode2[(unsigned char)(inchar2)]) #define PROGRAM_NAME "Csope" /* main.c global data */ -extern char *editor, *home, *shell, *lineflag; /* environment variables */ -extern char *home; /* Home directory */ -extern bool lineflagafterfile; -extern bool compress; /* compress the characters in the crossref */ -extern bool dbtruncated; /* database symbols truncated to 8 chars */ -extern int dispcomponents; /* file path components to display */ -extern bool editallprompt; /* prompt between editing files */ -extern unsigned int fileargc; /* file argument count */ -extern char **fileargv; /* file argument values */ -extern int fileversion; /* cross-reference file version */ -extern bool incurses; /* in curses */ -extern bool invertedindex; /* the database has an inverted index */ -extern bool isuptodate; /* consider the crossref up-to-date */ -extern bool kernelmode; /* don't use DFLT_INCDIR - bad for kernels */ -extern bool linemode; /* use line oriented user interface */ -extern bool verbosemode; /* print extra information on line mode */ -extern bool recurse_dir; /* recurse dirs when searching for src files */ -extern char *namefile; /* file of file names */ -extern bool ogs; /* display OGS book and subsystem names */ -extern char *prependpath; /* prepend path to file names */ -extern FILE *refsfound; /* references found file */ -extern long totalterms; /* total inverted index terms */ -extern bool trun_syms; /* truncate symbols to 8 characters */ -extern char tempstring[TEMPSTRING_LEN + 1]; /* global dummy string buffer */ - -extern char *tmpdir; /* temporary directory */ -extern char temp1[]; /* temporary file name */ -extern char temp2[]; /* temporary file name */ +extern char *editor, *home, *shell, *lineflag; /* environment variables */ +extern char *home; /* Home directory */ +extern bool lineflagafterfile; +extern bool compress; /* compress the characters in the crossref */ +extern bool dbtruncated; /* database symbols truncated to 8 chars */ +extern int dispcomponents; /* file path components to display */ +extern bool editallprompt; /* prompt between editing files */ +extern unsigned int fileargc; /* file argument count */ +extern char **fileargv; /* file argument values */ +extern int fileversion; /* cross-reference file version */ +extern bool incurses; /* in curses */ +extern bool invertedindex; /* the database has an inverted index */ +extern bool isuptodate; /* consider the crossref up-to-date */ +extern bool kernelmode; /* don't use DFLT_INCDIR - bad for kernels */ +extern bool linemode; /* use line oriented user interface */ +extern bool verbosemode; /* print extra information on line mode */ +extern bool recurse_dir; /* recurse dirs when searching for src files */ +extern char *namefile; /* file of file names */ +extern bool ogs; /* display OGS book and subsystem names */ +extern char *prependpath; /* prepend path to file names */ +extern FILE *refsfound; /* references found file */ +extern long totalterms; /* total inverted index terms */ +extern bool trun_syms; /* truncate symbols to 8 characters */ +extern char tempstring[TEMPSTRING_LEN + 1]; /* global dummy string buffer */ + +extern char *tmpdir; /* temporary directory */ +extern char temp1[]; /* temporary file name */ +extern char temp2[]; /* temporary file name */ /* command.c global data */ -extern bool caseless; /* ignore letter case when searching */ -extern bool *change; /* change this line */ -extern unsigned int curdispline; -extern char newpat[]; /* new pattern */ +extern bool caseless; /* ignore letter case when searching */ +extern bool *change; /* change this line */ +extern unsigned int curdispline; +extern char newpat[]; /* new pattern */ /* crossref.c global data */ -extern long dboffset; /* new database offset */ -extern bool errorsfound; /* prompt before clearing error messages */ -extern long lineoffset; /* source line database offset */ -extern long npostings; /* number of postings */ -extern unsigned long symbols; /* number of symbols */ +extern long dboffset; /* new database offset */ +extern bool errorsfound; /* prompt before clearing error messages */ +extern long lineoffset; /* source line database offset */ +extern long npostings; /* number of postings */ +extern unsigned long symbols; /* number of symbols */ /* dir.c global data */ -extern char currentdir[]; /* current directory */ -extern char **incdirs; /* #include directories */ -extern char **srcdirs; /* source directories */ -extern char **srcfiles; /* source files */ -extern size_t nincdirs; /* number of #include directories */ -extern size_t nsrcdirs; /* number of source directories */ -extern size_t nsrcfiles; /* number of source files */ -extern size_t msrcfiles; /* maximum number of source files */ +extern char currentdir[]; /* current directory */ +extern char **incdirs; /* #include directories */ +extern char **srcdirs; /* source directories */ +extern char **srcfiles; /* source files */ +extern size_t nincdirs; /* number of #include directories */ +extern size_t nsrcdirs; /* number of source directories */ +extern size_t nsrcfiles; /* number of source files */ +extern size_t msrcfiles; /* maximum number of source files */ /* display.c global data */ -extern int subsystemlen; /* OGS subsystem name display field length */ -extern int booklen; /* OGS book name display field length */ -extern int filelen; /* file name display field length */ -extern int fcnlen; /* function name display field length */ -extern int numlen; /* line number display field length */ -extern int *displine; /* screen line of displayed reference */ -extern unsigned int disprefs; /* displayed references */ -extern int field; /* input field */ -extern unsigned int mdisprefs; /* maximum displayed references */ -extern unsigned int nextline; /* next line to be shown */ -extern long searchcount; /* count of files searched */ -extern unsigned int totallines; /* total reference lines */ -extern int window_change; /* bitmask type to mark which windows have to be rerendered by display() */ +extern int subsystemlen; /* OGS subsystem name display field length */ +extern int booklen; /* OGS book name display field length */ +extern int filelen; /* file name display field length */ +extern int fcnlen; /* function name display field length */ +extern int numlen; /* line number display field length */ +extern int *displine; /* screen line of displayed reference */ +extern unsigned int disprefs; /* displayed references */ +extern int field; /* input field */ +extern unsigned int mdisprefs; /* maximum displayed references */ +extern unsigned int nextline; /* next line to be shown */ +extern long searchcount; /* count of files searched */ +extern unsigned int totallines; /* total reference lines */ +extern int window_change; /* bitmask type to mark which windows have to be rerendered by + display() */ /* find.c global data */ -extern char block[]; /* cross-reference file block */ -extern char blockmark; /* mark character to be searched for */ -extern long blocknumber; /* block number */ -extern char *blockp; /* pointer to current character in block */ -extern int blocklen; /* length of disk block read */ +extern char block[]; /* cross-reference file block */ +extern char blockmark; /* mark character to be searched for */ +extern long blocknumber; /* block number */ +extern char *blockp; /* pointer to current character in block */ +extern int blocklen; /* length of disk block read */ /* lookup.c global data */ -extern struct keystruct { - char *text; - char delim; - struct keystruct *next; +extern struct keystruct { + char *text; + char delim; + struct keystruct *next; } keyword[]; /* mouse.c global data */ -extern bool mouse; /* mouse interface */ +extern bool mouse; /* mouse interface */ /* readline.c global data */ -extern char* rl_line_buffer; -extern char input_line[PATLEN + 1]; -extern int rl_point; +extern char *rl_line_buffer; +extern char input_line[PATLEN + 1]; +extern int rl_point; -//extern bool unixpcmouse; /* UNIX PC mouse interface */ +// extern bool unixpcmouse; /* UNIX PC mouse interface */ /* cscope functions called from more than one function or between files */ -char *filepath(char *file); -char *findsymbol(const char *pattern); -char *finddef(const char *pattern); -char *findcalledby(const char *pattern); -char *findcalling(const char *pattern); -char *findstring(const char *pattern); -char *findregexp(const char *egreppat); -char *findfile(const char *dummy); -char *findinclude(const char *pattern); -char *findassign(const char *pattern); -char *findallfcns(const char *dummy); -char *inviewpath(char *file); -char *lookup(char *ident); -char *pathcomponents(char *path, int components); -char *read_block(void); -char *scanpast(char c); - -char ** parse_options(int *argc, char **argv); -void error_usage(void); -void longusage(void); -void usage(void); -extern bool remove_symfile_onexit; -extern bool onesearch; /* one search only in line mode */ -extern char *reflines; /* symbol reference lines file */ -extern bool do_press_any_key; /* wait for any key to continue */ -extern int current_page; -#define topref current_page*mdisprefs -void verswp_field(void); -void horswp_field(void); -bool interpret(int c); // XXX: probably rename -int handle_input(const int c); -int dispchar2int(const char c); -int process_mouse(); +char *filepath(char *file); +char *findsymbol(const char *pattern); +char *finddef(const char *pattern); +char *findcalledby(const char *pattern); +char *findcalling(const char *pattern); +char *findstring(const char *pattern); +char *findregexp(const char *egreppat); +char *findfile(const char *dummy); +char *findinclude(const char *pattern); +char *findassign(const char *pattern); +char *findallfcns(const char *dummy); +char *inviewpath(char *file); +char *lookup(char *ident); +char *pathcomponents(char *path, int components); +char *read_block(void); +char *scanpast(char c); + +char **parse_options(int *argc, char **argv); +void error_usage(void); +void longusage(void); +void usage(void); +extern bool remove_symfile_onexit; +extern bool onesearch; /* one search only in line mode */ +extern char *reflines; /* symbol reference lines file */ +extern bool do_press_any_key; /* wait for any key to continue */ +extern int current_page; +#define topref current_page *mdisprefs +void verswp_field(void); +void horswp_field(void); +bool interpret(int c); // XXX: probably rename +int handle_input(const int c); +int dispchar2int(const char c); +int process_mouse(); extern int input_mode; -int changestring(const char* from, const char* to, const bool *const change, const int change_len); - -long seekpage(const size_t i); -long seekrelline(unsigned i); -void PCS_reset(void); - -void rlinit(void); - -void addcmd(int f, char *s); -void addsrcfile(char *path); -void askforchar(void); -void askforreturn(void); -void cannotwrite(const char *const file); -void cannotopen(const char *const file); -void clearmsg(void); -void clearmsg2(void); -void countrefs(void); -void crossref(char *srcfile); -void dispinit(void); -void display(void); -void drawscrollbar(int top, int bot); -void edit(char *file, const char *const linenum); -void editall(void); -void editref(int); -void entercurses(void); -void exitcurses(void); -void findcleanup(void); -void freesrclist(void); -void freeinclist(void); -void freecrossref(void); -void freefilelist(void); -const char* help(void); -void incfile(char *file, char *type); -void includedir(char *_dirname); -void initsymtab(void); -void makefilelist(void); -void mousecleanup(void); -void mousemenu(void); -void mouseinit(void); -void mousereinit(void); -void myexit(int sig); -void myperror(char *text); -void ogsnames(char *file, char **subsystem, char **book); -void progress(char *what, long current, long max); -void putfilename(char *srcfile); -void postmsg(char *msg); -void postmsg2(char *msg); -void posterr(char *msg,...); -void postfatal(const char *msg,...); -void putposting(char *term, int type); -void fetch_string_from_dbase(char *, size_t); -void resetcmd(void); -void shellpath(char *out, int limit, char *in); -void sourcedir(char *dirlist); -void myungetch(int c); -void warning(char *text); -void writestring(char *s); - -bool infilelist(char *file); -bool readrefs(char *filename); -bool search(const char* query); -bool writerefsfound(void); - -int findinit(const char *pattern_); -MOUSE *getmouseaction(char leading_char); -struct cmd *currentcmd(void); -struct cmd *prevcmd(void); -struct cmd *nextcmd(void); - -int egrep(char *file, FILE *output, char *format); -int hash(char *ss); -int execute(char *a, ...); -long dbseek(long offset); +int changestring(const char *from, const char *to, const bool *const change, + const int change_len); + +long seekpage(const size_t i); +long seekrelline(unsigned i); +void PCS_reset(void); + +void rlinit(void); + +void addcmd(int f, char *s); +void addsrcfile(char *path); +void askforchar(void); +void askforreturn(void); +void cannotwrite(const char *const file); +void cannotopen(const char *const file); +void clearmsg(void); +void clearmsg2(void); +void countrefs(void); +void crossref(char *srcfile); +void dispinit(void); +void display(void); +void drawscrollbar(int top, int bot); +void edit(char *file, const char *const linenum); +void editall(void); +void editref(int); +void entercurses(void); +void exitcurses(void); +void findcleanup(void); +void freesrclist(void); +void freeinclist(void); +void freecrossref(void); +void freefilelist(void); +const char *help(void); +void incfile(char *file, char *type); +void includedir(char *_dirname); +void initsymtab(void); +void makefilelist(void); +void mousecleanup(void); +void mousemenu(void); +void mouseinit(void); +void mousereinit(void); +void myexit(int sig); +void myperror(char *text); +void ogsnames(char *file, char **subsystem, char **book); +void progress(char *what, long current, long max); +void putfilename(char *srcfile); +void postmsg(char *msg); +void postmsg2(char *msg); +void posterr(char *msg, ...); +void postfatal(const char *msg, ...); +void putposting(char *term, int type); +void fetch_string_from_dbase(char *, size_t); +void resetcmd(void); +void shellpath(char *out, int limit, char *in); +void sourcedir(char *dirlist); +void myungetch(int c); +void warning(char *text); +void writestring(char *s); + +bool infilelist(char *file); +bool readrefs(char *filename); +bool search(const char *query); +bool writerefsfound(void); + +int findinit(const char *pattern_); +MOUSE *getmouseaction(char leading_char); +struct cmd *currentcmd(void); +struct cmd *prevcmd(void); +struct cmd *nextcmd(void); + +int egrep(char *file, FILE *output, char *format); +int hash(char *ss); +int execute(char *a, ...); +long dbseek(long offset); #endif /* CSCOPE_GLOBAL_H */ diff --git a/src/help.c b/src/help.c index 123dd1e..b412d86 100644 --- a/src/help.c +++ b/src/help.c @@ -39,101 +39,91 @@ #include "global.h" #include /* - max num of lines of help screen - - this number needs to be increased if more than n help items are needed + max num of lines of help screen - + this number needs to be increased if more than n help items are needed */ const char tooltip_winput[] = "Search [Enter] -Mode [^k] +Mode [^j] Right [Tab] Down [%]"; -const char tooltip_wmode[] = "-Mode [Up] +Mode [Down] Right [Tab] Up [%]"; -const char tooltip_wresult[] = "Edit [Enter] Up [Up] Down [Down] Left [Tab] Previous [-] Next [+]"; +const char tooltip_wmode[] = "-Mode [Up] +Mode [Down] Right [Tab] Up [%]"; +const char tooltip_wresult[] = + "Edit [Enter] Up [Up] Down [Down] Left [Tab] Previous [-] Next [+]"; -static char help_msg[] = - "Press the RETURN key repeatedly to move to the desired input field, type the\n" - "pattern to search for, and then press the RETURN key. For the first 4 and\n" - "last 2 input fields, the pattern can be a regcomp(3) regular expression.\n" - "If the search is successful, you can use these single-character commands:\n\n" - "0-9a-zA-Z\tEdit the file containing the displayed line.\n" - "space bar\tDisplay next set of matching lines.\n" - "+\t\tDisplay next set of matching lines.\n" - "^V\t\tDisplay next set of matching lines.\n" - "-\t\tDisplay previous set of matching lines.\n" - "^E\t\tEdit all lines.\n" - ">\t\tWrite the list of lines being displayed to a file.\n" - ">>\t\tAppend the list of lines being displayed to a file.\n" - "<\t\tRead lines from a file.\n" - "^\t\tFilter all lines through a shell command.\n" - "|\t\tPipe all lines to a shell command.\n" - "\nAt any time you can use these single-character commands:\n\n" - "TAB\t\tSwap positions between input and output areas.\n" - "RETURN\t\tMove to the next input field.\n" - "^N\t\tMove to the next input field.\n" - "^P\t\tMove to the previous input field.\n" - "^Y / ^A\t\tSearch with the last pattern typed.\n" - "^B\t\tRecall previous input field and search pattern.\n" - "^F\t\tRecall next input field and search pattern.\n" - "^C\t\tToggle ignore/use letter case when searching.\n" - "^R\t\tRebuild the cross-reference.\n" - "!\t\tStart an interactive shell (type ^D to return).\n" - "^L\t\tRedraw the screen.\n" - "?\t\tDisplay this list of commands.\n" - "^D\t\tExit the program.\n" - "\nNote: If the first character of the pattern you want to search for matches\n" - "a command, type a \\ character first.\n" - "Note: Some ctrl keys may be occupied by your terminal configuration.\n" -; +static char help_msg[] = + "Press the RETURN key repeatedly to move to the desired input field, type the\n" + "pattern to search for, and then press the RETURN key. For the first 4 and\n" + "last 2 input fields, the pattern can be a regcomp(3) regular expression.\n" + "If the search is successful, you can use these single-character commands:\n\n" + "0-9a-zA-Z\tEdit the file containing the displayed line.\n" + "space bar\tDisplay next set of matching lines.\n" + "+\t\tDisplay next set of matching lines.\n" + "^V\t\tDisplay next set of matching lines.\n" + "-\t\tDisplay previous set of matching lines.\n" + "^E\t\tEdit all lines.\n" + ">\t\tWrite the list of lines being displayed to a file.\n" + ">>\t\tAppend the list of lines being displayed to a file.\n" + "<\t\tRead lines from a file.\n" + "^\t\tFilter all lines through a shell command.\n" + "|\t\tPipe all lines to a shell command.\n" + "\nAt any time you can use these single-character commands:\n\n" + "TAB\t\tSwap positions between input and output areas.\n" + "RETURN\t\tMove to the next input field.\n" + "^N\t\tMove to the next input field.\n" + "^P\t\tMove to the previous input field.\n" + "^Y / ^A\t\tSearch with the last pattern typed.\n" + "^B\t\tRecall previous input field and search pattern.\n" + "^F\t\tRecall next input field and search pattern.\n" + "^C\t\tToggle ignore/use letter case when searching.\n" + "^R\t\tRebuild the cross-reference.\n" + "!\t\tStart an interactive shell (type ^D to return).\n" + "^L\t\tRedraw the screen.\n" + "?\t\tDisplay this list of commands.\n" + "^D\t\tExit the program.\n" + "\nNote: If the first character of the pattern you want to search for matches\n" + "a command, type a \\ character first.\n" + "Note: Some ctrl keys may be occupied by your terminal configuration.\n"; -static char changeing_help_msg[] = - "When changing text, you can use these single-character commands:\n\n" - "0-9a-zA-Z\tMark or unmark the line to be changed.\n" - "*\t\tMark or unmark all displayed lines to be changed.\n" - "space bar\tDisplay next set of lines.\n" - "+\t\tDisplay next set of lines.\n" - "-\t\tDisplay previous set of lines.\n" - "^A\t\tMark or unmark all lines to be changed.\n" - "^D\t\tChange the marked lines and exit.\n" - "ESC\t\tExit without changing the marked lines.\n" - "!\t\tStart an interactive shell (type ^D to return).\n" - "^L\t\tRedraw the screen.\n" - "?\t\tDisplay this list of commands.\n" -; +static char changeing_help_msg[] = + "When changing text, you can use these single-character commands:\n\n" + "0-9a-zA-Z\tMark or unmark the line to be changed.\n" + "*\t\tMark or unmark all displayed lines to be changed.\n" + "space bar\tDisplay next set of lines.\n" + "+\t\tDisplay next set of lines.\n" + "-\t\tDisplay previous set of lines.\n" + "^A\t\tMark or unmark all lines to be changed.\n" + "^D\t\tChange the marked lines and exit.\n" + "ESC\t\tExit without changing the marked lines.\n" + "!\t\tStart an interactive shell (type ^D to return).\n" + "^L\t\tRedraw the screen.\n" + "?\t\tDisplay this list of commands.\n"; -const char* -help(void) -{ - if (input_mode == INPUT_CHANGE) { +const char *help(void) { + if(input_mode == INPUT_CHANGE) { return help_msg; - } else { + } else { return changeing_help_msg; - } + } } /* error exit including short usage information */ -void -error_usage(void) -{ - usage(); - fputs("Try the -h option for more information.\n", stderr); - myexit(1); +void error_usage(void) { + usage(); + fputs("Try the -h option for more information.\n", stderr); + myexit(1); } /* normal usage message */ -void -usage(void) -{ - fputs( - "Usage: " PROGRAM_NAME " [-bcCdehklLqRTuUvV] [-f file] [-F file] [-i file] [-I dir] [-s dir]\n" - " [-p number] [-P path] [-[0-8] pattern] [source files]\n", - stderr - ); +void usage(void) { + fputs("Usage: " PROGRAM_NAME + " [-bcCdehklLqRTuUvV] [-f file] [-F file] [-i file] [-I dir] [-s dir]\n" + " [-p number] [-P path] [-[0-8] pattern] [source files]\n", + stderr); } - /* long usage message */ -void -longusage(void) -{ - usage(); - fprintf(stderr, "\ +void longusage(void) { + usage(); + fprintf(stderr, + "\ \n\ -b Build the cross-reference only.\n\ -C Ignore letter case when searching.\n\ @@ -142,16 +132,18 @@ longusage(void) -e Suppress the -e command prompt between files.\n\ -F symfile Read symbol reference lines from symfile.\n\ -f reffile Use reffile as cross-ref file name instead of %s.\n", - REFFILE); - fprintf(stderr, "\ + REFFILE); + fprintf(stderr, + "\ -h This help screen.\n\ -I incdir Look in incdir for any #include files.\n\ -i namefile Browse through files listed in namefile, instead of %s\n", - NAMEFILE); - fprintf(stderr, "\ + NAMEFILE); + fprintf(stderr, + "\ -k Kernel Mode - don't use %s for #include files.\n", - DFLT_INCDIR); - fputs("\ + DFLT_INCDIR); + fputs("\ -L Do a single search with line-oriented output.\n\ -l Line-oriented interface.\n\ -num pattern Go to input field num (counting from 0) and find pattern.\n\ @@ -167,5 +159,5 @@ longusage(void) -V Print the version number.\n\ \n\ Please see the manpage for more information.\n", - stderr); + stderr); } diff --git a/src/history.c b/src/history.c index a92dc9e..c969ba1 100644 --- a/src/history.c +++ b/src/history.c @@ -39,66 +39,57 @@ -static struct cmd *tail, *current; +static struct cmd *tail, *current; /* add a cmd to the history list */ -void -addcmd(int f, char *s) /* field number and command text */ +void addcmd(int f, char *s) /* field number and command text */ { - struct cmd *h; - - h = malloc(sizeof(struct cmd)); - if( tail) { - tail->next = h; - h->next = 0; - h->prev = tail; - tail = h; - } else { - tail = h; - h->next = h->prev = 0; - } - h->field = f; - h->text = strdup( s); - current = 0; + struct cmd *h; + + h = malloc(sizeof(struct cmd)); + if(tail) { + tail->next = h; + h->next = 0; + h->prev = tail; + tail = h; + } else { + tail = h; + h->next = h->prev = 0; + } + h->field = f; + h->text = strdup(s); + current = 0; } /* return previous history item */ -struct cmd * -prevcmd(void) -{ - if( current) { - if( current->prev) /* stay on first item */ - return current = current->prev; - else - return current; - } else if( tail) - return current = tail; - else - return NULL; +struct cmd *prevcmd(void) { + if(current) { + if(current->prev) /* stay on first item */ + return current = current->prev; + else + return current; + } else if(tail) + return current = tail; + else + return NULL; } /* return next history item */ -struct cmd * -nextcmd(void) -{ - if( current) { - if( current->next) /* stay on first item */ - return current = current->next; - else - return current; - } else - return NULL; +struct cmd *nextcmd(void) { + if(current) { + if(current->next) /* stay on first item */ + return current = current->next; + else + return current; + } else + return NULL; } /* reset current to tail */ -void -resetcmd(void) -{ - current = 0; +void resetcmd(void) { + current = 0; } -struct cmd * -currentcmd(void) -{ - return current; +struct cmd *currentcmd(void) { + return current; } diff --git a/src/input.c b/src/input.c index 629f38b..a5376f1 100644 --- a/src/input.c +++ b/src/input.c @@ -37,7 +37,7 @@ #include "global.h" #include -#include /* jmp_buf */ +#include /* jmp_buf */ #include #include #if HAVE_SYS_TERMIOS_H @@ -48,522 +48,489 @@ bool do_press_any_key = false; -static jmp_buf env; /* setjmp/longjmp buffer */ -static int prevchar; /* previous, ungotten character */ +static jmp_buf env; /* setjmp/longjmp buffer */ +static int prevchar; /* previous, ungotten character */ /* Internal prototypes: */ static void catchint(int sig); /* catch the interrupt signal */ -static void -catchint(int sig){ +static void catchint(int sig) { UNUSED(sig); - signal(SIGINT, catchint); - longjmp(env, 1); + signal(SIGINT, catchint); + longjmp(env, 1); } /* unget a character */ -void -myungetch(int c) -{ - prevchar = c; +void myungetch(int c) { + prevchar = c; } + /* ask user to enter a character after reading the message */ -void -askforchar(void){ - addstr("Type any character to continue: "); - getch(); +void askforchar(void) { + addstr("Type any character to continue: "); + getch(); } /* ask user to press the RETURN key after reading the message */ -void -askforreturn(void){ - fprintf(stderr, "Press the RETURN key to continue: "); - getchar(); - /* HBB 20060419: message probably messed up the screen --- redraw */ - if (incurses == true) { - redrawwin(curscr); - } +void askforreturn(void) { + fprintf(stderr, "Press the RETURN key to continue: "); + getchar(); + /* HBB 20060419: message probably messed up the screen --- redraw */ + if(incurses == true) { redrawwin(curscr); } } /* expand the ~ and $ shell meta characters in a path */ -void -shellpath(char *out, int limit, char *in){ - char *lastchar; - char *s, *v; - - /* skip leading white space */ - while (isspace((unsigned char)*in)) { - ++in; - } - lastchar = out + limit - 1; - - /* a tilde (~) by itself represents $HOME; followed by a name it - represents the $LOGDIR of that login name */ - if (*in == '~') { - *out++ = *in++; /* copy the ~ because it may not be expanded */ - - /* get the login name */ - s = out; - while (s < lastchar && *in != '/' && *in != '\0' && !isspace((unsigned char)*in)) { - *s++ = *in++; - } - *s = '\0'; - - /* if the login name is null, then use $HOME */ - if (*out == '\0') { - v = getenv("HOME"); - } else { /* get the home directory of the login name */ - v = logdir(out); - } - /* copy the directory name if it isn't too big */ - if (v != NULL && strlen(v) < (lastchar - out)) { - strcpy(out - 1, v); - out += strlen(v) - 1; - } else { - /* login not found, so ~ must be part of the file name */ - out += strlen(out); - } - } - /* get the rest of the path */ - while (out < lastchar && *in != '\0' && !isspace((unsigned char)*in)) { - - /* look for an environment variable */ - if (*in == '$') { - *out++ = *in++; /* copy the $ because it may not be expanded */ - - /* get the variable name */ - s = out; - while (s < lastchar && *in != '/' && *in != '\0' && - !isspace((unsigned char)*in)) { - *s++ = *in++; - } - *s = '\0'; - - /* get its value, but only it isn't too big */ - if ((v = getenv(out)) != NULL && strlen(v) < (lastchar - out)) { - strcpy(out - 1, v); - out += strlen(v) - 1; - } else { - /* var not found, or too big, so assume $ must be part of the - * file name */ - out += strlen(out); - } - } - else { /* ordinary character */ - *out++ = *in++; - } - } - *out = '\0'; +void shellpath(char *out, int limit, char *in) { + char *lastchar; + char *s, *v; + + /* skip leading white space */ + while(isspace((unsigned char)*in)) { + ++in; + } + lastchar = out + limit - 1; + + /* a tilde (~) by itself represents $HOME; followed by a name it + represents the $LOGDIR of that login name */ + if(*in == '~') { + *out++ = *in++; /* copy the ~ because it may not be expanded */ + + /* get the login name */ + s = out; + while(s < lastchar && *in != '/' && *in != '\0' && !isspace((unsigned char)*in)) { + *s++ = *in++; + } + *s = '\0'; + + /* if the login name is null, then use $HOME */ + if(*out == '\0') { + v = getenv("HOME"); + } else { /* get the home directory of the login name */ + v = logdir(out); + } + /* copy the directory name if it isn't too big */ + if(v != NULL && strlen(v) < (lastchar - out)) { + strcpy(out - 1, v); + out += strlen(v) - 1; + } else { + /* login not found, so ~ must be part of the file name */ + out += strlen(out); + } + } + /* get the rest of the path */ + while(out < lastchar && *in != '\0' && !isspace((unsigned char)*in)) { + + /* look for an environment variable */ + if(*in == '$') { + *out++ = *in++; /* copy the $ because it may not be expanded */ + + /* get the variable name */ + s = out; + while(s < lastchar && *in != '/' && *in != '\0' && + !isspace((unsigned char)*in)) { + *s++ = *in++; + } + *s = '\0'; + + /* get its value, but only it isn't too big */ + if((v = getenv(out)) != NULL && strlen(v) < (lastchar - out)) { + strcpy(out - 1, v); + out += strlen(v) - 1; + } else { + /* var not found, or too big, so assume $ must be part of the + * file name */ + out += strlen(out); + } + } else { /* ordinary character */ + *out++ = *in++; + } + } + *out = '\0'; } -static int -wmode_input(const int c){ - switch (c) { - case KEY_ENTER: - case '\r': - case '\n': - case ctrl('N'): /* go to next input field */ - case KEY_DOWN: - case KEY_RIGHT: - field = (field + 1) % FIELDS; - resetcmd(); +static int wmode_input(const int c) { + switch(c) { + case KEY_ENTER: + case '\r': + case '\n': + case ctrl('N'): /* go to next input field */ + case KEY_DOWN: + case KEY_RIGHT: + field = (field + 1) % FIELDS; + resetcmd(); break; - case ctrl('P'): /* go to previous input field */ - case KEY_UP: - case KEY_LEFT: - field = (field + (FIELDS - 1)) % FIELDS; - resetcmd(); + case ctrl('P'): /* go to previous input field */ + case KEY_UP: + case KEY_LEFT: + field = (field + (FIELDS - 1)) % FIELDS; + resetcmd(); break; - case KEY_HOME: /* go to first input field */ - field = 0; - resetcmd(); + case KEY_HOME: /* go to first input field */ + field = 0; + resetcmd(); break; - case KEY_LL: /* go to last input field */ - curdispline = disprefs; + case KEY_LL: /* go to last input field */ + curdispline = disprefs; break; default: return 0; - } + } window_change |= CH_MODE; return 1; } -static int -wresult_input(const int c){ - switch (c) { - case KEY_ENTER: /* open for editing */ - case '\r': - case '\n': - editref(curdispline); - window_change = CH_ALL; +static int wresult_input(const int c) { + switch(c) { + case KEY_ENTER: /* open for editing */ + case '\r': + case '\n': + editref(curdispline); + window_change = CH_ALL; break; - case ctrl('N'): - case KEY_DOWN: - case KEY_RIGHT: - if ((curdispline + 1) < disprefs) { - ++curdispline; - } + case ctrl('N'): + case KEY_DOWN: + case KEY_RIGHT: + if((curdispline + 1) < disprefs) { ++curdispline; } break; - case ctrl('P'): - case KEY_UP: - case KEY_LEFT: - if (curdispline) { - --curdispline; - } + case ctrl('P'): + case KEY_UP: + case KEY_LEFT: + if(curdispline) { --curdispline; } break; - case KEY_HOME: - curdispline = 0; + case KEY_HOME: + curdispline = 0; break; - case KEY_LL: - field = FIELDS - 1; - resetcmd(); + case KEY_LL: + field = FIELDS - 1; + resetcmd(); break; - default: - if(c > mdisprefs){ goto noredisp; } - const int pos = dispchar2int(c); - if(pos > -1){ editref(pos); } + default: + if(c > mdisprefs) { goto noredisp; } + const int pos = dispchar2int(c); + if(pos > -1) { editref(pos); } goto noredisp; - } + } window_change |= CH_RESULT; - noredisp: +noredisp: return 1; } -static int -global_input(const int c){ - switch(c){ - case '\t': - horswp_field(); - break; - case '%': - verswp_field(); - break; +static int global_input(const int c) { + switch(c) { + case '\t': + horswp_field(); + break; + case '%': + verswp_field(); + break; case ctrl('K'): - field = (field + (FIELDS - 1)) % FIELDS; - resetcmd(); + field = (field + (FIELDS - 1)) % FIELDS; + resetcmd(); window_change |= CH_MODE; - break; + break; case ctrl('J'): - field = (field + 1) % FIELDS; - resetcmd(); + field = (field + 1) % FIELDS; + resetcmd(); window_change |= CH_MODE; - break; - case ctrl('H'): /* display previous page */ - case '-': - case KEY_PPAGE: - if (totallines == 0) { return 0; } /* don't redisplay if there are no lines */ - curdispline = 0; - if(current_page > 0){ + break; + case ctrl('H'): /* display previous page */ + case '-': + case KEY_PPAGE: + if(totallines == 0) { return 0; } /* don't redisplay if there are no lines */ + curdispline = 0; + if(current_page > 0) { --current_page; window_change |= CH_RESULT; } - break; - case '+': - case ctrl('L'): - case KEY_NPAGE: - if (totallines == 0) { return 0; } /* don't redisplay if there are no lines */ - curdispline = 0; + break; + case '+': + case ctrl('L'): + case KEY_NPAGE: + if(totallines == 0) { return 0; } /* don't redisplay if there are no lines */ + curdispline = 0; ++current_page; window_change |= CH_RESULT; - break; - case '>': /* write or append the lines to a file */ - break; // XXX - //char filename[PATHLEN + 1]; - //char* s; - //char ch; - //FILE* file; - //if (totallines == 0) { - // postmsg("There are no lines to write to a file"); - // return(NO); - //} - //move(PRLINE, 0); - ////addstr("Write to file: "); // XXX - //s = "w"; - //if ((ch = getch()) == '>') { - //move(PRLINE, 0); - ////addstr(appendprompt); // XXX fix - ////ch = '\0'; - ////s = "a"; - ////} - ////if (ch != '\r' && mygetline("", newpat, COLS - sizeof(appendprompt), c, NO) > 0) { - //// shellpath(filename, sizeof(filename), newpat); - //// if ((file = myfopen(filename, s)) == NULL) { - //// cannotopen(filename); - //// } else { - //// seekline(1); - //// while ((ch = getc(refsfound)) != EOF) { - //// putc(ch, file); - //// } - //// seekline(topline); - //// fclose(file); - //// } - ////} - ////clearprompt(); - break; - case '<': /* read lines from a file */ - break; // XXX - //move(PRLINE, 0); - //addstr(readprompt); // XXX fix - //if (mygetline("", newpat, COLS - sizeof(readprompt), '\0', NO) > 0) { - // clearprompt(); - // shellpath(filename, sizeof(filename), newpat); - // if (readrefs(filename) == NO) { - // postmsg2("Ignoring an empty file"); - // return(NO); - // } - // window_change |= CH_INPUT; - // return(YES); - //} - //clearprompt(); - return 0; - case '|': /* pipe the lines to a shell command */ - case '^': - break; // XXX fix - if (totallines == 0) { - postmsg("There are no lines to pipe to a shell command"); - return 0; - } - /* get the shell command */ - //move(PRLINE, 0); - //addstr(pipeprompt); - //if (mygetline("", newpat, COLS - sizeof(pipeprompt), '\0', NO) == 0) { - // clearprompt(); - // return(NO); - //} - ///* if the ^ command, redirect output to a temp file */ - //if (commandc == '^') { - // strcat(strcat(newpat, " >"), temp2); - // /* HBB 20020708: somebody might have even - // * their non-interactive default shells - // * complain about clobbering - // * redirections... --> delete before - // * overwriting */ - // remove(temp2); - //} - //exitcurses(); - //if ((file = mypopen(newpat, "w")) == NULL) { - // fprintf(stderr, "cscope: cannot open pipe to shell command: %s\n", newpat); - //} else { - // seekline(1); - // while ((c = getc(refsfound)) != EOF) { - // putc(c, file); - // } - // seekline(topline); - // mypclose(file); - //} - //if (commandc == '^') { - // if (readrefs(temp2) == NO) { - // postmsg("Ignoring empty output of ^ command"); - // } - //} - //askforreturn(); - //entercurses(); - break; - case '!': /* shell escape */ - execute(shell, shell, NULL); + break; + case '>': /* write or append the lines to a file */ + break; // XXX + // char filename[PATHLEN + 1]; + // char* s; + // char ch; + // FILE* file; + // if (totallines == 0) { + // postmsg("There are no lines to write to a file"); + // return(NO); + // } + // move(PRLINE, 0); + ////addstr("Write to file: "); // XXX + // s = "w"; + // if ((ch = getch()) == '>') { + // move(PRLINE, 0); + ////addstr(appendprompt); // XXX fix + ////ch = '\0'; + ////s = "a"; + ////} + ////if (ch != '\r' && mygetline("", newpat, COLS - sizeof(appendprompt), c, + ///NO) > 0) { / shellpath(filename, sizeof(filename), newpat); / if + ///((file = myfopen(filename, s)) == NULL) { / cannotopen(filename); / + ///} else { / seekline(1); / while ((ch = getc(refsfound)) != + ///EOF) { / putc(ch, file); / } / seekline(topline); / + ///fclose(file); / } + ////} + ////clearprompt(); + break; + case '<': /* read lines from a file */ + break; // XXX + // move(PRLINE, 0); + // addstr(readprompt); // XXX fix + // if (mygetline("", newpat, COLS - sizeof(readprompt), '\0', NO) > 0) { + // clearprompt(); + // shellpath(filename, sizeof(filename), newpat); + // if (readrefs(filename) == NO) { + // postmsg2("Ignoring an empty file"); + // return(NO); + // } + // window_change |= CH_INPUT; + // return(YES); + // } + // clearprompt(); + return 0; + case '|': /* pipe the lines to a shell command */ + case '^': + break; // XXX fix + if(totallines == 0) { + postmsg("There are no lines to pipe to a shell command"); + return 0; + } + /* get the shell command */ + // move(PRLINE, 0); + // addstr(pipeprompt); + // if (mygetline("", newpat, COLS - sizeof(pipeprompt), '\0', NO) == 0) { + // clearprompt(); + // return(NO); + // } + ///* if the ^ command, redirect output to a temp file */ + // if (commandc == '^') { + // strcat(strcat(newpat, " >"), temp2); + // /* HBB 20020708: somebody might have even + // * their non-interactive default shells + // * complain about clobbering + // * redirections... --> delete before + // * overwriting */ + // remove(temp2); + // } + // exitcurses(); + // if ((file = mypopen(newpat, "w")) == NULL) { + // fprintf(stderr, "cscope: cannot open pipe to shell command: %s\n", + // newpat); + // } else { + // seekline(1); + // while ((c = getc(refsfound)) != EOF) { + // putc(c, file); + // } + // seekline(topline); + // mypclose(file); + // } + // if (commandc == '^') { + // if (readrefs(temp2) == NO) { + // postmsg("Ignoring empty output of ^ command"); + // } + // } + // askforreturn(); + // entercurses(); + break; + case '!': /* shell escape */ + execute(shell, shell, NULL); current_page = 0; - break; - case KEY_RESIZE: - /* XXX: fill in*/ - break; - case ctrl('U'): /* redraw screen */ - case KEY_CLEAR: - window_change = CH_ALL; - break; - case '?': /* help */ + break; + case KEY_RESIZE: + /* XXX: fill in*/ + break; + case ctrl('U'): /* redraw screen */ + case KEY_CLEAR: + window_change = CH_ALL; + break; + case '?': /* help */ window_change = CH_HELP; - break; - case ctrl('E'): /* edit all lines */ - editall(); - break; - default: - return 0; - } - - return 1; + break; + case ctrl('E'): /* edit all lines */ + editall(); + break; + default: + return 0; + } + + return 1; } -extern const void *const winput; -extern const void *const wmode; -extern const void *const wresult; +extern const void *const winput; +extern const void *const wmode; +extern const void *const wresult; extern const void *const *const current_window; -int -change_input(const int c){ - MOUSE *p; /* mouse data */ - - switch(c){ - case '*': /* invert page */ - for(int i = 0; topref + i < nextline; i++){ - change[topref + i] = !change[topref + i]; - } - window_change |= CH_RESULT; - break; - case ctrl('A'): /* invert all lines */ - for(unsigned i = 0; i < totallines; i++) { - change[i] = !change[i]; - } - window_change |= CH_RESULT; - break; - case ctrl('X'): /* mouse selection */ - if ((p = getmouseaction(DUMMYCHAR)) == NULL) { - break; /* unknown control sequence */ - } - /* if the button number is a scrollbar tag */ - if (p->button == '0') { - //scrollbar(p); +int change_input(const int c) { + MOUSE *p; /* mouse data */ + + switch(c) { + case '*': /* invert page */ + for(int i = 0; topref + i < nextline; i++) { + change[topref + i] = !change[topref + i]; + } + window_change |= CH_RESULT; break; - } - /* find the selected line */ - /* NOTE: the selection is forced into range */ - { - int i; - for(i = disprefs - 1; i > 0; --i) { - if (p->y1 >= displine[i]) { - break; + case ctrl('A'): /* invert all lines */ + for(unsigned i = 0; i < totallines; i++) { + change[i] = !change[i]; + } + window_change |= CH_RESULT; + break; + case ctrl('X'): /* mouse selection */ + if((p = getmouseaction(DUMMYCHAR)) == NULL) { + break; /* unknown control sequence */ + } + /* if the button number is a scrollbar tag */ + if(p->button == '0') { + // scrollbar(p); + break; + } + /* find the selected line */ + /* NOTE: the selection is forced into range */ + { + int i; + for(i = disprefs - 1; i > 0; --i) { + if(p->y1 >= displine[i]) { break; } } + change[i] = !change[i]; } - change[i] = !change[i]; - } - break; - case ctrl('D'): - changestring(input_line, newpat, change, totallines); - break; - default: - { - /* if a line was selected */ - const int cc = dispchar2int(c); - if(cc != -1){ - change[cc] = !change[cc]; - window_change |= CH_RESULT; + break; + case ctrl('D'): + changestring(input_line, newpat, change, totallines); + break; + default: + { + /* if a line was selected */ + const int cc = dispchar2int(c); + if(cc != -1) { + change[cc] = !change[cc]; + window_change |= CH_RESULT; + } } - } } return 0; } -int -changestring(const char* from, - const char* to, - const bool *const change, - const int change_len -){ - char newfile[PATHLEN + 1]; /* new file name */ - char oldfile[PATHLEN + 1]; /* old file name */ - char linenum[NUMLEN + 1]; /* file line number */ - char msg[MSGLEN + 1]; /* message */ - FILE *script; /* shell script file */ - - /* Return early */ - bool anymarked = false; /* any line marked */ - for(int i = 0; i < change_len; i++){ - if(change[i]){ +int changestring(const char *from, const char *to, const bool *const change, + const int change_len) { + char newfile[PATHLEN + 1]; /* new file name */ + char oldfile[PATHLEN + 1]; /* old file name */ + char linenum[NUMLEN + 1]; /* file line number */ + char msg[MSGLEN + 1]; /* message */ + FILE *script; /* shell script file */ + + /* Return early */ + bool anymarked = false; /* any line marked */ + for(int i = 0; i < change_len; i++) { + if(change[i]) { anymarked = true; break; } } - if(!anymarked){ return false; } + if(!anymarked) { return false; } - /* open the temporary file */ - if((script = myfopen(temp2, "w")) == NULL) { + /* open the temporary file */ + if((script = myfopen(temp2, "w")) == NULL) { cannotopen(temp2); - return(false); - } + return (false); + } - /* for each line containing the old text */ - fprintf(script, "ed - <<\\!\n"); - *oldfile = '\0'; + /* for each line containing the old text */ + fprintf(script, "ed - <<\\!\n"); + *oldfile = '\0'; fseek(refsfound, 0, SEEK_SET); - for(int i = 0; - fscanf(refsfound, "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s%*[^\n]", newfile, linenum) == 2; - ++i) - { + for(int i = 0; fscanf(refsfound, + "%" PATHLEN_STR "s%*s%" NUMLEN_STR "s%*[^\n]", + newfile, + linenum) == 2; + ++i) { /* see if the line is to be changed */ - if (!change[i]) { break; } - - /* if this is a new file */ - if (strcmp(newfile, oldfile) != 0) { - - /* make sure it can be changed */ - if (access(newfile, WRITE) != 0) { - snprintf(msg, sizeof(msg), "Cannot write to file %s", newfile); - postmsg(msg); - goto end; - } - /* if there was an old file */ - if (*oldfile != '\0') { - fprintf(script, "w\n"); /* save it */ + if(!change[i]) { break; } + + /* if this is a new file */ + if(strcmp(newfile, oldfile) != 0) { + + /* make sure it can be changed */ + if(access(newfile, WRITE) != 0) { + snprintf(msg, sizeof(msg), "Cannot write to file %s", newfile); + postmsg(msg); + goto end; + } + /* if there was an old file */ + if(*oldfile != '\0') { fprintf(script, "w\n"); /* save it */ } + /* edit the new file */ + strcpy(oldfile, newfile); + fprintf(script, "e %s\n", oldfile); } - /* edit the new file */ - strcpy(oldfile, newfile); - fprintf(script, "e %s\n", oldfile); - } - /* output substitute command */ - fprintf(script, "%ss/", linenum); /* change */ - for(const char *s = from; *s != '\0'; ++s) { + /* output substitute command */ + fprintf(script, "%ss/", linenum); /* change */ + for(const char *s = from; *s != '\0'; ++s) { /* old text */ - if (strchr("/\\[.^*", *s) != NULL) { - putc('\\', script); - } - if (caseless == true && isalpha((unsigned char)*s)) { + if(strchr("/\\[.^*", *s) != NULL) { putc('\\', script); } + if(caseless == true && isalpha((unsigned char)*s)) { putc('[', script); if(islower((unsigned char)*s)) { - putc(toupper((unsigned char)*s), script); - putc(*s, script); + putc(toupper((unsigned char)*s), script); + putc(*s, script); } else { - putc(*s, script); - putc(tolower((unsigned char)*s), script); + putc(*s, script); + putc(tolower((unsigned char)*s), script); } putc(']', script); } else { putc(*s, script); } - } - putc('/', script); /* to */ - for(const char *s = to; *s != '\0'; ++s) { /* new text */ - if (strchr("/\\&", *s) != NULL) { - putc('\\', script); - } + } + putc('/', script); /* to */ + for(const char *s = to; *s != '\0'; ++s) { /* new text */ + if(strchr("/\\&", *s) != NULL) { putc('\\', script); } putc(*s, script); - } - fprintf(script, "/gp\n"); /* and print */ - } - fprintf(script, "w\nq\n!\n"); /* write and quit */ - fflush(script); + } + fprintf(script, "/gp\n"); /* and print */ + } + fprintf(script, "w\nq\n!\n"); /* write and quit */ + fflush(script); /* edit the files */ fprintf(stderr, "Changed lines:\n\r"); execute("sh", "sh", temp2, NULL); askforchar(); end: - fclose(script); - return true; + fclose(script); + return true; } -int -handle_input(const int c){ +int handle_input(const int c) { /* - was wating for any input - */ - if(do_press_any_key){ + if(do_press_any_key) { do_press_any_key = false; return 0; } - /* --- global --- */ - const int r = global_input(c); - if(r){ return 0; } - /* --- mode specific --- */ - switch(input_mode){ + /* --- global --- */ + const int r = global_input(c); + if(r) { return 0; } + /* --- mode specific --- */ + switch(input_mode) { case INPUT_NORMAL: - if(*current_window == winput){ + if(*current_window == winput) { return interpret(c); - }else if(*current_window == wmode){ + } else if(*current_window == wmode) { return wmode_input(c); - }else if(*current_window == wresult){ + } else if(*current_window == wresult) { return wresult_input(c); } assert("'current_window' dangling."); @@ -574,5 +541,5 @@ handle_input(const int c){ return change_input(c); } - return 0; + return 0; } diff --git a/src/invlib.c b/src/invlib.c index 1691981..9b3f896 100644 --- a/src/invlib.c +++ b/src/invlib.c @@ -35,476 +35,461 @@ #include #include #if SHARE -#include -#include -#include -#define ERR -1 +# include +# include +# include +# define ERR -1 #endif #include "invlib.h" #include "global.h" #include -#define DEBUG 0 /* debugging code and realloc messages */ -#define BLOCKSIZE 2 * BUFSIZ /* logical block size */ -#define POSTINC 10000 /* posting buffer size increment */ -#define SEP ' ' /* sorted posting field separator */ -#define SETINC 100 /* posting set size increment */ -#define STATS 0 /* print statistics */ -#define SUPERINC 10000 /* super index size increment */ -#define TERMMAX 512 /* term max size */ -#define FMTVERSION 1 /* inverted index format version */ -#define ZIPFSIZE 200 /* zipf curve size */ +#define DEBUG 0 /* debugging code and realloc messages */ +#define BLOCKSIZE 2 * BUFSIZ /* logical block size */ +#define POSTINC 10000 /* posting buffer size increment */ +#define SEP ' ' /* sorted posting field separator */ +#define SETINC 100 /* posting set size increment */ +#define STATS 0 /* print statistics */ +#define SUPERINC 10000 /* super index size increment */ +#define TERMMAX 512 /* term max size */ +#define FMTVERSION 1 /* inverted index format version */ +#define ZIPFSIZE 200 /* zipf curve size */ #if DEBUG /* FIXME HBB 20010705: nowhere in the source is `invbreak' ever set to * a value other than the (silent) initialization to zero. Pretty * useless, that looks */ -int invbreak; +int invbreak; #endif -static int boolready(void); -static int invnewterm(void); -static void invstep(INVCONTROL *invcntl); -static void invcannotalloc(unsigned n); -static void invcannotopen(char *file); -static void invcannotwrite(char *file); +static int boolready(void); +static int invnewterm(void); +static void invstep(INVCONTROL *invcntl); +static void invcannotalloc(unsigned n); +static void invcannotopen(char *file); +static void invcannotwrite(char *file); #if STATS -int showzipf; /* show postings per term distribution */ +int showzipf; /* show postings per term distribution */ #endif -static POSTING *item, *enditem, *item1 = NULL, *item2 = NULL; -static unsigned int setsize1, setsize2; -static long numitems, totterm, zerolong; -static char *indexfile, *postingfile; -static FILE *outfile, *fpost; -static size_t supersize = SUPERINC, supintsize; -static unsigned int numpost, numlogblk, amtused, nextpost; -static unsigned int lastinblk, numinvitems; -static POSTING *POST, *postptr; -static unsigned long *SUPINT, *supint, nextsupfing; -static char *SUPFING, *supfing; -static char thisterm[TERMMAX]; +static POSTING *item, *enditem, *item1 = NULL, *item2 = NULL; +static unsigned int setsize1, setsize2; +static long numitems, totterm, zerolong; +static char *indexfile, *postingfile; +static FILE *outfile, *fpost; +static size_t supersize = SUPERINC, supintsize; +static unsigned int numpost, numlogblk, amtused, nextpost; +static unsigned int lastinblk, numinvitems; +static POSTING *POST, *postptr; +static unsigned long *SUPINT, *supint, nextsupfing; +static char *SUPFING, *supfing; +static char thisterm[TERMMAX]; + typedef union logicalblk { - long invblk[BLOCKSIZE / sizeof(long)]; - char chrblk[BLOCKSIZE]; + long invblk[BLOCKSIZE / sizeof(long)]; + char chrblk[BLOCKSIZE]; } t_logicalblk; + static t_logicalblk logicalblk; #if DEBUG || STATS -static long totpost; +static long totpost; #endif #if STATS -static int zipf[ZIPFSIZE + 1]; +static int zipf[ZIPFSIZE + 1]; #endif -long -invmake(char *invname, char *invpost, FILE *infile) -{ - unsigned char *s; - long num; - int i; - long fileindex = 0; /* initialze, to avoid warning */ - unsigned postsize = POSTINC * sizeof(*POST); - unsigned long *intptr; - char line[TERMMAX]; - long tlong; - PARAM param; - POSTING posting; - char temp[BLOCKSIZE]; +long invmake(char *invname, char *invpost, FILE *infile) { + unsigned char *s; + long num; + int i; + long fileindex = 0; /* initialze, to avoid warning */ + unsigned postsize = POSTINC * sizeof(*POST); + unsigned long *intptr; + char line[TERMMAX]; + long tlong; + PARAM param; + POSTING posting; + char temp[BLOCKSIZE]; #if STATS - int j; - unsigned maxtermlen = 0; + int j; + unsigned maxtermlen = 0; #endif - /* output file */ - if ((outfile = vpfopen(invname, "w+b")) == NULL) { - invcannotopen(invname); - return(0); - } - indexfile = invname; - fseek(outfile, BUFSIZ, SEEK_SET); - - /* posting file */ - if ((fpost = vpfopen(invpost, "wb")) == NULL) { - invcannotopen(invpost); - return(0); - } - postingfile = invpost; - nextpost = 0; - /* get space for the postings list */ - if ((POST = malloc(postsize)) == NULL) { - invcannotalloc(postsize); - return(0); - } - postptr = POST; - /* get space for the superfinger (superindex) */ - if ((SUPFING = malloc(supersize)) == NULL) { - invcannotalloc(supersize); - return(0); - } - supfing = SUPFING; - /* FIXME HBB: magic number alert (40) */ - supintsize = supersize / 40u; - /* also for the superfinger index */ - if ((SUPINT = malloc(supintsize * sizeof(*SUPINT))) == NULL) { - invcannotalloc(supintsize * sizeof(*SUPINT)); - return(0); - } - supint = SUPINT; - supint++; /* leave first term open for a count */ - /* initialize using an empty term */ - strcpy(thisterm, ""); - *supint++ = 0; - *supfing++ = ' '; - *supfing++ = '\0'; - nextsupfing = 2; + /* output file */ + if((outfile = vpfopen(invname, "w+b")) == NULL) { + invcannotopen(invname); + return (0); + } + indexfile = invname; + fseek(outfile, BUFSIZ, SEEK_SET); + + /* posting file */ + if((fpost = vpfopen(invpost, "wb")) == NULL) { + invcannotopen(invpost); + return (0); + } + postingfile = invpost; + nextpost = 0; + /* get space for the postings list */ + if((POST = malloc(postsize)) == NULL) { + invcannotalloc(postsize); + return (0); + } + postptr = POST; + /* get space for the superfinger (superindex) */ + if((SUPFING = malloc(supersize)) == NULL) { + invcannotalloc(supersize); + return (0); + } + supfing = SUPFING; + /* FIXME HBB: magic number alert (40) */ + supintsize = supersize / 40u; + /* also for the superfinger index */ + if((SUPINT = malloc(supintsize * sizeof(*SUPINT))) == NULL) { + invcannotalloc(supintsize * sizeof(*SUPINT)); + return (0); + } + supint = SUPINT; + supint++; /* leave first term open for a count */ + /* initialize using an empty term */ + strcpy(thisterm, ""); + *supint++ = 0; + *supfing++ = ' '; + *supfing++ = '\0'; + nextsupfing = 2; #if DEBUG || STATS - totpost = 0L; + totpost = 0L; #endif - totterm = 0L; - numpost = 1; - - /* set up as though a block had come and gone, i.e., set up for new block */ - /* 3 longs needed for: numinvitems, next block, and previous block */ - amtused = 3 * sizeof(long); - numinvitems = 0; - numlogblk = 0; - lastinblk = sizeof(t_logicalblk); - - /* now loop as long as more to read (till eof) */ - while (fgets(line, TERMMAX, infile) != NULL) { + totterm = 0L; + numpost = 1; + + /* set up as though a block had come and gone, i.e., set up for new block */ + /* 3 longs needed for: numinvitems, next block, and previous block */ + amtused = 3 * sizeof(long); + numinvitems = 0; + numlogblk = 0; + lastinblk = sizeof(t_logicalblk); + + /* now loop as long as more to read (till eof) */ + while(fgets(line, TERMMAX, infile) != NULL) { #if DEBUG || STATS - ++totpost; + ++totpost; #endif - s = strchr(line, SEP); - if (s != NULL) { - *s = '\0'; - } - else { - continue; - } + s = strchr(line, SEP); + if(s != NULL) { + *s = '\0'; + } else { + continue; + } #if STATS - if ((i = strlen(line)) > maxtermlen) { - maxtermlen = i; - } + if((i = strlen(line)) > maxtermlen) { maxtermlen = i; } #endif #if DEBUG - printf("%ld: %s ", totpost, line); - fflush(stdout); + printf("%ld: %s ", totpost, line); + fflush(stdout); #endif - if (strcmp(thisterm, line) == 0) { - if ((postptr + 10) > (POST + (postsize / sizeof(*POST)))) { - i = postptr - POST; - postsize += POSTINC * sizeof(*POST); - if ((POST = realloc(POST, postsize)) == NULL) { - invcannotalloc(postsize); - return(0); - } - postptr = i + POST; + if(strcmp(thisterm, line) == 0) { + if((postptr + 10) > (POST + (postsize / sizeof(*POST)))) { + i = postptr - POST; + postsize += POSTINC * sizeof(*POST); + if((POST = realloc(POST, postsize)) == NULL) { + invcannotalloc(postsize); + return (0); + } + postptr = i + POST; #if DEBUG - printf("reallocated post space to %u, totpost=%ld\n", - postsize, totpost); + printf("reallocated post space to %u, totpost=%ld\n", postsize, totpost); #endif - } - numpost++; - } else { - /* have a new term */ - if (!invnewterm()) { - return(0); - } - strcpy(thisterm, line); - numpost = 1; - postptr = POST; - fileindex = 0; - } - /* get the new posting */ - num = *++s - '!'; - i = 1; - do { - num = BASE * num + *++s - '!'; - } while (++i < PRECISION); - posting.lineoffset = num; - while (++fileindex < nsrcfiles && num > srcoffset[fileindex]) { - ; - } - posting.fileindex = --fileindex; - posting.type = *++s; - ++s; - if (*s != '\n') { - num = *++s - '!'; - while (*++s != '\n') { - num = BASE * num + *s - '!'; - } - posting.fcnoffset = num; - } - else { - posting.fcnoffset = 0; - } - *postptr++ = posting; + } + numpost++; + } else { + /* have a new term */ + if(!invnewterm()) { return (0); } + strcpy(thisterm, line); + numpost = 1; + postptr = POST; + fileindex = 0; + } + /* get the new posting */ + num = *++s - '!'; + i = 1; + do { + num = BASE * num + *++s - '!'; + } while(++i < PRECISION); + posting.lineoffset = num; + while(++fileindex < nsrcfiles && num > srcoffset[fileindex]) { + ; + } + posting.fileindex = --fileindex; + posting.type = *++s; + ++s; + if(*s != '\n') { + num = *++s - '!'; + while(*++s != '\n') { + num = BASE * num + *s - '!'; + } + posting.fcnoffset = num; + } else { + posting.fcnoffset = 0; + } + *postptr++ = posting; #if DEBUG - printf("%ld %ld %ld %ld\n", posting.fileindex, - posting.fcnoffset, posting.lineoffset, posting.type); - fflush(stdout); + printf("%ld %ld %ld %ld\n", + posting.fileindex, + posting.fcnoffset, + posting.lineoffset, + posting.type); + fflush(stdout); #endif - } - if (!invnewterm()) { - return(0); - } - /* now clean up final block */ - logicalblk.invblk[0] = numinvitems; - /* loops pointer around to start */ - logicalblk.invblk[1] = 0; - logicalblk.invblk[2] = numlogblk - 1; - if (fwrite(&logicalblk, sizeof(t_logicalblk), 1, outfile) == 0) { - goto cannotwrite; - } - numlogblk++; - /* write out block to save space. what in it doesn't matter */ - if (fwrite(&logicalblk, sizeof(t_logicalblk), 1, outfile) == 0) { - goto cannotwrite; - } - /* finish up the super finger */ - *SUPINT = numlogblk; - /* add to the offsets the size of the offset pointers */ - intptr = (SUPINT + 1); - i = (char *)supint - (char *)SUPINT; - while (intptr < supint) - *intptr++ += i; - /* write out the offsets (1 for the N at start) and the super finger */ - if (fwrite(SUPINT, sizeof(*SUPINT), numlogblk + 1, outfile) == 0 || - fwrite(SUPFING, 1, supfing - SUPFING, outfile) == 0) { - goto cannotwrite; - } - /* save the size for reference later */ - nextsupfing = sizeof(long) + sizeof(long) * numlogblk + (supfing - SUPFING); - /* make sure the file ends at a logical block boundary. This is - necessary for invinsert to correctly create extended blocks - */ - i = nextsupfing % sizeof(t_logicalblk); - /* write out junk to fill log blk */ - if (fwrite(temp, sizeof(t_logicalblk) - i, 1, outfile) == 0 || - fflush(outfile) == EOF) { /* rewind doesn't check for write failure */ - goto cannotwrite; - } - /* write the control area */ - rewind(outfile); - param.version = FMTVERSION; - param.filestat = 0; - param.sizeblk = sizeof(t_logicalblk); - param.startbyte = (numlogblk + 1) * sizeof(t_logicalblk) + BUFSIZ;; - param.supsize = nextsupfing; - param.cntlsize = BUFSIZ; - param.share = 0; - if (fwrite(¶m, sizeof(param), 1, outfile) == 0) { - goto cannotwrite; - } - for (i = 0; i < 10; i++) /* for future use */ - if (fwrite(&zerolong, sizeof(zerolong), 1, outfile) == 0) { - goto cannotwrite; - } - - /* make first block loop backwards to last block */ - if (fflush(outfile) == EOF) { /* fseek doesn't check for write failure */ - goto cannotwrite; - } - /* get to second word first block */ - fseek(outfile, BUFSIZ + 2 * sizeof(long), SEEK_SET); - tlong = numlogblk - 1; - if (fwrite(&tlong, sizeof(tlong), 1, outfile) == 0 || - fclose(outfile) == EOF) { - cannotwrite: - invcannotwrite(invname); - return(0); - } - if (fclose(fpost) == EOF) { - invcannotwrite(postingfile); - return(0); - } - --totterm; /* don't count null term */ + } + if(!invnewterm()) { return (0); } + /* now clean up final block */ + logicalblk.invblk[0] = numinvitems; + /* loops pointer around to start */ + logicalblk.invblk[1] = 0; + logicalblk.invblk[2] = numlogblk - 1; + if(fwrite(&logicalblk, sizeof(t_logicalblk), 1, outfile) == 0) { goto cannotwrite; } + numlogblk++; + /* write out block to save space. what in it doesn't matter */ + if(fwrite(&logicalblk, sizeof(t_logicalblk), 1, outfile) == 0) { goto cannotwrite; } + /* finish up the super finger */ + *SUPINT = numlogblk; + /* add to the offsets the size of the offset pointers */ + intptr = (SUPINT + 1); + i = (char *)supint - (char *)SUPINT; + while(intptr < supint) + *intptr++ += i; + /* write out the offsets (1 for the N at start) and the super finger */ + if(fwrite(SUPINT, sizeof(*SUPINT), numlogblk + 1, outfile) == 0 || + fwrite(SUPFING, 1, supfing - SUPFING, outfile) == 0) { + goto cannotwrite; + } + /* save the size for reference later */ + nextsupfing = sizeof(long) + sizeof(long) * numlogblk + (supfing - SUPFING); + /* make sure the file ends at a logical block boundary. This is + necessary for invinsert to correctly create extended blocks + */ + i = nextsupfing % sizeof(t_logicalblk); + /* write out junk to fill log blk */ + if(fwrite(temp, sizeof(t_logicalblk) - i, 1, outfile) == 0 || + fflush(outfile) == EOF) { /* rewind doesn't check for write failure */ + goto cannotwrite; + } + /* write the control area */ + rewind(outfile); + param.version = FMTVERSION; + param.filestat = 0; + param.sizeblk = sizeof(t_logicalblk); + param.startbyte = (numlogblk + 1) * sizeof(t_logicalblk) + BUFSIZ; + ; + param.supsize = nextsupfing; + param.cntlsize = BUFSIZ; + param.share = 0; + if(fwrite(¶m, sizeof(param), 1, outfile) == 0) { goto cannotwrite; } + for(i = 0; i < 10; i++) /* for future use */ + if(fwrite(&zerolong, sizeof(zerolong), 1, outfile) == 0) { goto cannotwrite; } + + /* make first block loop backwards to last block */ + if(fflush(outfile) == EOF) { /* fseek doesn't check for write failure */ + goto cannotwrite; + } + /* get to second word first block */ + fseek(outfile, BUFSIZ + 2 * sizeof(long), SEEK_SET); + tlong = numlogblk - 1; + if(fwrite(&tlong, sizeof(tlong), 1, outfile) == 0 || fclose(outfile) == EOF) { + cannotwrite: + invcannotwrite(invname); + return (0); + } + if(fclose(fpost) == EOF) { + invcannotwrite(postingfile); + return (0); + } + --totterm; /* don't count null term */ #if STATS - printf("logical blocks = %d, postings = %ld, terms = %ld, max term length = %d\n", - numlogblk, totpost, totterm, maxtermlen); - if (showzipf) { - printf("\n************* ZIPF curve ****************\n"); - for (j = ZIPFSIZE; j > 1; j--) - if (zipf[j]) - break; - for (i = 1; i < j; ++i) { - printf("%3d -%6d ", i, zipf[i]); - if (i % 6 == 0) putchar('\n'); - } - printf(">%d-%6d\n", ZIPFSIZE, zipf[0]); - } + printf("logical blocks = %d, postings = %ld, terms = %ld, max term length = %d\n", + numlogblk, + totpost, + totterm, + maxtermlen); + if(showzipf) { + printf("\n************* ZIPF curve ****************\n"); + for(j = ZIPFSIZE; j > 1; j--) + if(zipf[j]) break; + for(i = 1; i < j; ++i) { + printf("%3d -%6d ", i, zipf[i]); + if(i % 6 == 0) putchar('\n'); + } + printf(">%d-%6d\n", ZIPFSIZE, zipf[0]); + } #endif - /* free all malloc'd memory */ - free(POST); - free(SUPFING); - free(SUPINT); - return(totterm); + /* free all malloc'd memory */ + free(POST); + free(SUPFING); + free(SUPINT); + return (totterm); } /* add a term to the data base */ -static int -invnewterm(void) -{ - int backupflag, i, j, holditems, gooditems, howfar; - unsigned int maxback, len, numwilluse, wdlen; - char *tptr, *tptr3; +static int invnewterm(void) { + int backupflag, i, j, holditems, gooditems, howfar; + unsigned int maxback, len, numwilluse, wdlen; + char *tptr, *tptr3; - union { - unsigned long packword[2]; - ENTRY e; - } iteminfo; + union { + unsigned long packword[2]; + ENTRY e; + } iteminfo; - gooditems = 0; /* initialize, to avoid warning */ - totterm++; + gooditems = 0; /* initialize, to avoid warning */ + totterm++; #if STATS - /* keep zipfian info on the distribution */ - if (numpost <= ZIPFSIZE) - zipf[numpost]++; - else - zipf[0]++; + /* keep zipfian info on the distribution */ + if(numpost <= ZIPFSIZE) + zipf[numpost]++; + else + zipf[0]++; #endif - len = strlen(thisterm); - /* length of term rounded up to long boundary */ - wdlen = (len + (sizeof(long) - 1)) / sizeof(long); - /* each term needs 2 longs for its iteminfo and - * 1 long for its offset */ - numwilluse = (wdlen + 3) * sizeof(long); - /* new block if at least 1 item in block */ - if (numinvitems && numwilluse + amtused > sizeof(t_logicalblk)) { - /* set up new block */ - if (supfing + 500u > SUPFING + supersize) { - i = supfing - SUPFING; - supersize += 20000u; - if ((SUPFING = realloc(SUPFING, supersize)) == NULL) { - invcannotalloc(supersize); - return(0); - } - supfing = i + SUPFING; + len = strlen(thisterm); + /* length of term rounded up to long boundary */ + wdlen = (len + (sizeof(long) - 1)) / sizeof(long); + /* each term needs 2 longs for its iteminfo and + * 1 long for its offset */ + numwilluse = (wdlen + 3) * sizeof(long); + /* new block if at least 1 item in block */ + if(numinvitems && numwilluse + amtused > sizeof(t_logicalblk)) { + /* set up new block */ + if(supfing + 500u > SUPFING + supersize) { + i = supfing - SUPFING; + supersize += 20000u; + if((SUPFING = realloc(SUPFING, supersize)) == NULL) { + invcannotalloc(supersize); + return (0); + } + supfing = i + SUPFING; #if DEBUG - printf("reallocated superfinger space to %d, totpost=%ld\n", - supersize, totpost); + printf("reallocated superfinger space to %d, totpost=%ld\n", + supersize, + totpost); #endif - } - /* check that room for the offset as well */ - /* FIXME HBB: magic number alert (10) */ - if ((numlogblk + 10) > supintsize) { - i = supint - SUPINT; - supintsize += SUPERINC; - if ((SUPINT = realloc(SUPINT, supintsize * sizeof(*SUPINT))) == NULL) { - invcannotalloc(supintsize * sizeof(*SUPINT)); - return(0); - } - supint = i + SUPINT; + } + /* check that room for the offset as well */ + /* FIXME HBB: magic number alert (10) */ + if((numlogblk + 10) > supintsize) { + i = supint - SUPINT; + supintsize += SUPERINC; + if((SUPINT = realloc(SUPINT, supintsize * sizeof(*SUPINT))) == NULL) { + invcannotalloc(supintsize * sizeof(*SUPINT)); + return (0); + } + supint = i + SUPINT; #if DEBUG - printf("reallocated superfinger offset to %d, totpost = %ld\n", supintsize * sizeof(*SUPINT), totpost); + printf("reallocated superfinger offset to %d, totpost = %ld\n", + supintsize * sizeof(*SUPINT), + totpost); #endif - } - /* See if backup is efficatious */ - backupflag = 0; - maxback = (int) strlen(thisterm) / 10; - holditems = numinvitems; - if (maxback > numinvitems) - maxback = numinvitems - 2; - howfar = 0; - while (maxback-- > 1) { - howfar++; - iteminfo.packword[0] = - logicalblk.invblk[--holditems * 2 + (sizeof(long) - 1)]; - if ((i = iteminfo.e.size / 10) < maxback) { - maxback = i; - backupflag = howfar; - gooditems = holditems; - } - } - /* see if backup will occur */ - if (backupflag) { - numinvitems = gooditems; - } - logicalblk.invblk[0] = numinvitems; - /* set forward pointer pointing to next */ - logicalblk.invblk[1] = numlogblk + 1; - /* set back pointer to last block */ - logicalblk.invblk[2] = numlogblk - 1; - if (fwrite(logicalblk.chrblk, 1, sizeof(t_logicalblk), outfile) == 0) { - invcannotwrite(indexfile); - return(0); - } - /* 3 longs needed for: numinvitems, next block, and previous block */ - amtused = 3 * sizeof(long); - numlogblk++; - /* check if had to back up, if so do it */ - if (backupflag) { - char *tptr2; - - /* find out where the end of the new block is */ - iteminfo.packword[0] = logicalblk.invblk[numinvitems*2+1]; - tptr3 = logicalblk.chrblk + iteminfo.e.offset; - /* move the index for this block */ - for (i = 3; i <= (backupflag * 2 + 2); i++) - logicalblk.invblk[i] = logicalblk.invblk[numinvitems*2+i]; - /* move the word into the super index */ - iteminfo.packword[0] = logicalblk.invblk[3]; - iteminfo.packword[1] = logicalblk.invblk[4]; - tptr2 = logicalblk.chrblk + iteminfo.e.offset; - strncpy(supfing, tptr2, (int) iteminfo.e.size); - *(supfing + iteminfo.e.size) = '\0'; + } + /* See if backup is efficatious */ + backupflag = 0; + maxback = (int)strlen(thisterm) / 10; + holditems = numinvitems; + if(maxback > numinvitems) maxback = numinvitems - 2; + howfar = 0; + while(maxback-- > 1) { + howfar++; + iteminfo.packword[0] = + logicalblk.invblk[--holditems * 2 + (sizeof(long) - 1)]; + if((i = iteminfo.e.size / 10) < maxback) { + maxback = i; + backupflag = howfar; + gooditems = holditems; + } + } + /* see if backup will occur */ + if(backupflag) { numinvitems = gooditems; } + logicalblk.invblk[0] = numinvitems; + /* set forward pointer pointing to next */ + logicalblk.invblk[1] = numlogblk + 1; + /* set back pointer to last block */ + logicalblk.invblk[2] = numlogblk - 1; + if(fwrite(logicalblk.chrblk, 1, sizeof(t_logicalblk), outfile) == 0) { + invcannotwrite(indexfile); + return (0); + } + /* 3 longs needed for: numinvitems, next block, and previous block */ + amtused = 3 * sizeof(long); + numlogblk++; + /* check if had to back up, if so do it */ + if(backupflag) { + char *tptr2; + + /* find out where the end of the new block is */ + iteminfo.packword[0] = logicalblk.invblk[numinvitems * 2 + 1]; + tptr3 = logicalblk.chrblk + iteminfo.e.offset; + /* move the index for this block */ + for(i = 3; i <= (backupflag * 2 + 2); i++) + logicalblk.invblk[i] = logicalblk.invblk[numinvitems * 2 + i]; + /* move the word into the super index */ + iteminfo.packword[0] = logicalblk.invblk[3]; + iteminfo.packword[1] = logicalblk.invblk[4]; + tptr2 = logicalblk.chrblk + iteminfo.e.offset; + strncpy(supfing, tptr2, (int)iteminfo.e.size); + *(supfing + iteminfo.e.size) = '\0'; #if DEBUG - printf("backup %d at term=%s to term=%s\n", - backupflag, thisterm, supfing); + printf("backup %d at term=%s to term=%s\n", backupflag, thisterm, supfing); #endif - *supint++ = nextsupfing; - nextsupfing += strlen(supfing) + 1; - supfing += strlen(supfing) + 1; - /* now fix up the logical block */ - tptr = logicalblk.chrblk + lastinblk; - lastinblk = sizeof(t_logicalblk); - tptr2 = logicalblk.chrblk + lastinblk; - j = tptr3 - tptr; - while (tptr3 > tptr) - *--tptr2 = *--tptr3; - lastinblk -= j; - amtused += ((2 * sizeof(long)) * backupflag + j); - for (i = 3; i < (backupflag * 2 + 2); i += 2) { - iteminfo.packword[0] = logicalblk.invblk[i]; - iteminfo.e.offset += (tptr2 - tptr3); - logicalblk.invblk[i] = iteminfo.packword[0]; - } - numinvitems = backupflag; - } else { /* no backup needed */ - numinvitems = 0; - lastinblk = sizeof(t_logicalblk); - /* add new term to superindex */ - strcpy(supfing, thisterm); - supfing += strlen(thisterm) + 1; - *supint++ = nextsupfing; - nextsupfing += strlen(thisterm) + 1; - } - } - /* HBB 20010501: Fixed bug by replacing magic number '8' by - * what it actually represents. */ - lastinblk -= (numwilluse - 2 * sizeof(long)); - iteminfo.e.offset = lastinblk; - iteminfo.e.size = len; - iteminfo.e.space = 0; - iteminfo.e.post = numpost; - strncpy(logicalblk.chrblk + lastinblk, thisterm, len); - amtused += numwilluse; - logicalblk.invblk[(lastinblk/sizeof(long))+wdlen] = nextpost; - if ((i = postptr - POST) > 0) { - if (fwrite(POST, sizeof(*POST), i, fpost) == 0) { - invcannotwrite(postingfile); - return(0); - } - nextpost += i * sizeof(*POST); - } - logicalblk.invblk[3+2*numinvitems++] = iteminfo.packword[0]; - logicalblk.invblk[2+2*numinvitems] = iteminfo.packword[1]; - return(1); + *supint++ = nextsupfing; + nextsupfing += strlen(supfing) + 1; + supfing += strlen(supfing) + 1; + /* now fix up the logical block */ + tptr = logicalblk.chrblk + lastinblk; + lastinblk = sizeof(t_logicalblk); + tptr2 = logicalblk.chrblk + lastinblk; + j = tptr3 - tptr; + while(tptr3 > tptr) + *--tptr2 = *--tptr3; + lastinblk -= j; + amtused += ((2 * sizeof(long)) * backupflag + j); + for(i = 3; i < (backupflag * 2 + 2); i += 2) { + iteminfo.packword[0] = logicalblk.invblk[i]; + iteminfo.e.offset += (tptr2 - tptr3); + logicalblk.invblk[i] = iteminfo.packword[0]; + } + numinvitems = backupflag; + } else { /* no backup needed */ + numinvitems = 0; + lastinblk = sizeof(t_logicalblk); + /* add new term to superindex */ + strcpy(supfing, thisterm); + supfing += strlen(thisterm) + 1; + *supint++ = nextsupfing; + nextsupfing += strlen(thisterm) + 1; + } + } + /* HBB 20010501: Fixed bug by replacing magic number '8' by + * what it actually represents. */ + lastinblk -= (numwilluse - 2 * sizeof(long)); + iteminfo.e.offset = lastinblk; + iteminfo.e.size = len; + iteminfo.e.space = 0; + iteminfo.e.post = numpost; + strncpy(logicalblk.chrblk + lastinblk, thisterm, len); + amtused += numwilluse; + logicalblk.invblk[(lastinblk / sizeof(long)) + wdlen] = nextpost; + if((i = postptr - POST) > 0) { + if(fwrite(POST, sizeof(*POST), i, fpost) == 0) { + invcannotwrite(postingfile); + return (0); + } + nextpost += i * sizeof(*POST); + } + logicalblk.invblk[3 + 2 * numinvitems++] = iteminfo.packword[0]; + logicalblk.invblk[2 + 2 * numinvitems] = iteminfo.packword[1]; + return (1); } /* @@ -513,29 +498,24 @@ invnewterm(void) * returns 0. Otherwise, returns -1. */ -static int -invflipname(char * invname, const char *from, const char *to) -{ - char *temp, *i = NULL; - - assert(strlen(from) == strlen(to)); - - temp = invname - 1; - while( (temp = strstr(temp + 1, from))) - i = temp; - if (!i || i[strlen(from)] != '\0') - return -1; - while(*to) - *i++ = *to++; - return 0; +static int invflipname(char *invname, const char *from, const char *to) { + char *temp, *i = NULL; + + assert(strlen(from) == strlen(to)); + + temp = invname - 1; + while((temp = strstr(temp + 1, from))) + i = temp; + if(!i || i[strlen(from)] != '\0') return -1; + while(*to) + *i++ = *to++; + return 0; } /* small helper function to centralize handling of binary opening * for reading, and use of the 'stat" flag */ -static FILE * -open_for_reading(char *name, int stat) -{ - return vpfopen(name, ((stat == 0) ? "rb" : "r+b")); +static FILE *open_for_reading(char *name, int stat) { + return vpfopen(name, ((stat == 0) ? "rb" : "r+b")); } /* handle opening of a file under a possibly "flipped" name */ @@ -545,503 +525,475 @@ open_for_reading(char *name, int stat) /* more silliness: if you create the db with '-f cscope', then try to open * it without '-f cscope', you'll fail unless we check for 'cscope.out.in' * here. */ -static FILE * -open_file_with_flipped_name(char *name, const char *flip_in, const char *flip_out, int stat) -{ - if (! invflipname(name, flip_in, flip_out)) { - FILE *fptr = open_for_reading(name, stat); - if (! fptr) - /* flip back for error message */ - invflipname(name, flip_out, flip_in); - return fptr; - }; - return 0; +static FILE *open_file_with_flipped_name(char *name, const char *flip_in, + const char *flip_out, int stat) { + if(!invflipname(name, flip_in, flip_out)) { + FILE *fptr = open_for_reading(name, stat); + if(!fptr) /* flip back for error message */ + invflipname(name, flip_out, flip_in); + return fptr; + }; + return 0; } -static FILE * -open_file_with_possibly_flipped_name(char *name, const char *flip1, const char *flip2, int stat) -{ - FILE *fptr = open_for_reading(name, stat); +static FILE *open_file_with_possibly_flipped_name(char *name, const char *flip1, + const char *flip2, int stat) { + FILE *fptr = open_for_reading(name, stat); - if (! fptr) - fptr = open_file_with_flipped_name(name, flip2, flip1, stat); - if (! fptr) - fptr = open_file_with_flipped_name(name, flip1, flip2, stat); - return fptr; + if(!fptr) fptr = open_file_with_flipped_name(name, flip2, flip1, stat); + if(!fptr) fptr = open_file_with_flipped_name(name, flip1, flip2, stat); + return fptr; } -int -invopen(INVCONTROL *invcntl, char *invname, char *invpost, int stat) -{ - int read_index; - - invcntl->invfile = open_file_with_possibly_flipped_name(invname, INVNAME, INVNAME2, stat); - if (! invcntl->invfile) { - invcannotopen(invname); - return(-1); - } - if (fread(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile) == 0) { - fprintf(stderr, PROGRAM_NAME ": empty inverted file\n"); - fclose(invcntl->invfile); - return(-1); - } - if (invcntl->param.version != FMTVERSION) { - fprintf(stderr, PROGRAM_NAME ": cannot read old index format; use -U option to force database to rebuild\n"); - fclose(invcntl->invfile); - return(-1); - } - assert(invcntl->param.sizeblk == sizeof(t_logicalblk)); - - if (stat == 0 && invcntl->param.filestat == INVALONE) { - fprintf(stderr, PROGRAM_NAME ": inverted file is locked\n"); - fclose(invcntl->invfile); - return(-1); - } - - invcntl->postfile = open_file_with_possibly_flipped_name(invpost, INVPOST, INVPOST2, stat); - if (! invcntl->postfile) { - invcannotopen(invpost); - fclose(invcntl->invfile); - return(-1); - } - - /* allocate core for a logical block */ - if ((invcntl->logblk = malloc((size_t) invcntl->param.sizeblk)) == NULL) { - invcannotalloc((size_t) invcntl->param.sizeblk); - fclose(invcntl->postfile); - fclose(invcntl->invfile); - return(-1); - } - /* allocate for and read in superfinger */ - read_index = 1; - invcntl->iindex = NULL; +int invopen(INVCONTROL *invcntl, char *invname, char *invpost, int stat) { + int read_index; + + invcntl->invfile = + open_file_with_possibly_flipped_name(invname, INVNAME, INVNAME2, stat); + if(!invcntl->invfile) { + invcannotopen(invname); + return (-1); + } + if(fread(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile) == 0) { + fprintf(stderr, PROGRAM_NAME ": empty inverted file\n"); + fclose(invcntl->invfile); + return (-1); + } + if(invcntl->param.version != FMTVERSION) { + fprintf(stderr, + PROGRAM_NAME + ": cannot read old index format; use -U option to force database to rebuild\n"); + fclose(invcntl->invfile); + return (-1); + } + assert(invcntl->param.sizeblk == sizeof(t_logicalblk)); + + if(stat == 0 && invcntl->param.filestat == INVALONE) { + fprintf(stderr, PROGRAM_NAME ": inverted file is locked\n"); + fclose(invcntl->invfile); + return (-1); + } + + invcntl->postfile = + open_file_with_possibly_flipped_name(invpost, INVPOST, INVPOST2, stat); + if(!invcntl->postfile) { + invcannotopen(invpost); + fclose(invcntl->invfile); + return (-1); + } + + /* allocate core for a logical block */ + if((invcntl->logblk = malloc((size_t)invcntl->param.sizeblk)) == NULL) { + invcannotalloc((size_t)invcntl->param.sizeblk); + fclose(invcntl->postfile); + fclose(invcntl->invfile); + return (-1); + } + /* allocate for and read in superfinger */ + read_index = 1; + invcntl->iindex = NULL; #if SHARE - if (invcntl->param.share == 1) { - key_t shm_key; - struct shmid_ds shm_buf; - int shm_id; - - /* see if the shared segment exists */ - shm_key = ftok(invname, 2); - shm_id = shmget(shm_key, 0, 0); - /* Failure simply means (hopefully) that segment doesn't exists */ - if (shm_id == -1) { - /* Have to give general write permission due to AMdahl not having protected segments */ - shm_id = shmget(shm_key, invcntl->param.supsize + sizeof(long), IPC_CREAT | 0666); - if (shm_id == -1) - perror("Could not create shared memory segment"); - } else - read_index = 0; - - if (shm_id != -1) { - invcntl->iindex = shmat(shm_id, 0, ((read_index) ? 0 : SHM_RDONLY)); - if (invcntl->iindex == (char *)ERR) { - fprintf(stderr, PROGRAM_NAME ": shared memory link failed\n"); - invcntl->iindex = NULL; - read_index = 1; - } - } - } + if(invcntl->param.share == 1) { + key_t shm_key; + struct shmid_ds shm_buf; + int shm_id; + + /* see if the shared segment exists */ + shm_key = ftok(invname, 2); + shm_id = shmget(shm_key, 0, 0); + /* Failure simply means (hopefully) that segment doesn't exists */ + if(shm_id == -1) { + /* Have to give general write permission due to AMdahl not having protected + * segments */ + shm_id = + shmget(shm_key, invcntl->param.supsize + sizeof(long), IPC_CREAT | 0666); + if(shm_id == -1) perror("Could not create shared memory segment"); + } else + read_index = 0; + + if(shm_id != -1) { + invcntl->iindex = shmat(shm_id, 0, ((read_index) ? 0 : SHM_RDONLY)); + if(invcntl->iindex == (char *)ERR) { + fprintf(stderr, PROGRAM_NAME ": shared memory link failed\n"); + invcntl->iindex = NULL; + read_index = 1; + } + } + } #endif - if (invcntl->iindex == NULL) - /* FIXME HBB: magic number alert (4, sizeof(long)) */ - invcntl->iindex = malloc((size_t) invcntl->param.supsize + 4 *sizeof(long)); - if (invcntl->iindex == NULL) { - invcannotalloc((size_t) invcntl->param.supsize); - free(invcntl->logblk); - fclose(invcntl->postfile); - fclose(invcntl->invfile); - return(-1); - } - if (read_index) { - fseek(invcntl->invfile, invcntl->param.startbyte, SEEK_SET); - fread(invcntl->iindex, (int) invcntl->param.supsize, 1, - invcntl->invfile); - } - invcntl->numblk = -1; - if (boolready() == -1) { - fclose(invcntl->postfile); - fclose(invcntl->invfile); - return(-1); - } - /* write back out the control block if anything changed */ - invcntl->param.filestat = stat; - if (stat > invcntl->param.filestat ) { - rewind(invcntl->invfile); - fwrite(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile); - } - return(1); + if(invcntl->iindex == NULL) /* FIXME HBB: magic number alert (4, sizeof(long)) */ + invcntl->iindex = malloc((size_t)invcntl->param.supsize + 4 * sizeof(long)); + if(invcntl->iindex == NULL) { + invcannotalloc((size_t)invcntl->param.supsize); + free(invcntl->logblk); + fclose(invcntl->postfile); + fclose(invcntl->invfile); + return (-1); + } + if(read_index) { + fseek(invcntl->invfile, invcntl->param.startbyte, SEEK_SET); + fread(invcntl->iindex, (int)invcntl->param.supsize, 1, invcntl->invfile); + } + invcntl->numblk = -1; + if(boolready() == -1) { + fclose(invcntl->postfile); + fclose(invcntl->invfile); + return (-1); + } + /* write back out the control block if anything changed */ + invcntl->param.filestat = stat; + if(stat > invcntl->param.filestat) { + rewind(invcntl->invfile); + fwrite(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile); + } + return (1); } /** invclose must be called to wrap things up and deallocate core **/ -void -invclose(INVCONTROL *invcntl) -{ - /* write out the control block in case anything changed */ - if (invcntl->param.filestat > 0) { - invcntl->param.filestat = 0; - rewind(invcntl->invfile); - fwrite(&invcntl->param, 1, - sizeof(invcntl->param), invcntl->invfile); - } - if (invcntl->param.filestat == INVALONE) { - /* write out the super finger */ - fseek(invcntl->invfile, invcntl->param.startbyte, SEEK_SET); - fwrite(invcntl->iindex, 1, - (int) invcntl->param.supsize, invcntl->invfile); - } - fclose(invcntl->invfile); - fclose(invcntl->postfile); +void invclose(INVCONTROL *invcntl) { + /* write out the control block in case anything changed */ + if(invcntl->param.filestat > 0) { + invcntl->param.filestat = 0; + rewind(invcntl->invfile); + fwrite(&invcntl->param, 1, sizeof(invcntl->param), invcntl->invfile); + } + if(invcntl->param.filestat == INVALONE) { + /* write out the super finger */ + fseek(invcntl->invfile, invcntl->param.startbyte, SEEK_SET); + fwrite(invcntl->iindex, 1, (int)invcntl->param.supsize, invcntl->invfile); + } + fclose(invcntl->invfile); + fclose(invcntl->postfile); #if SHARE - if (invcntl->param.share > 0) { - shmdt(invcntl->iindex); - invcntl->iindex = NULL; - } + if(invcntl->param.share > 0) { + shmdt(invcntl->iindex); + invcntl->iindex = NULL; + } #endif - if (invcntl->iindex != NULL) - free(invcntl->iindex); - free(invcntl->logblk); + if(invcntl->iindex != NULL) free(invcntl->iindex); + free(invcntl->logblk); } /** invstep steps the inverted file forward one item **/ -static void -invstep(INVCONTROL *invcntl) -{ - if (invcntl->keypnt < (invcntl->logblk->invblk[0] - 1)) { - invcntl->keypnt++; - return; - } - - /* move forward a block else wrap */ - invcntl->numblk = invcntl->logblk->invblk[1]; /* was: *(int *)(invcntl->logblk + sizeof(long))*/ - - /* now read in the block */ - fseek(invcntl->invfile, - invcntl->numblk*invcntl->param.sizeblk + invcntl->param.cntlsize, - SEEK_SET); - fread(invcntl->logblk, (int) invcntl->param.sizeblk, 1, - invcntl->invfile); - invcntl->keypnt = 0; +static void invstep(INVCONTROL *invcntl) { + if(invcntl->keypnt < (invcntl->logblk->invblk[0] - 1)) { + invcntl->keypnt++; + return; + } + + /* move forward a block else wrap */ + invcntl->numblk = + invcntl->logblk->invblk[1]; /* was: *(int *)(invcntl->logblk + sizeof(long))*/ + + /* now read in the block */ + fseek(invcntl->invfile, + invcntl->numblk * invcntl->param.sizeblk + invcntl->param.cntlsize, + SEEK_SET); + fread(invcntl->logblk, (int)invcntl->param.sizeblk, 1, invcntl->invfile); + invcntl->keypnt = 0; } /** invforward moves forward one term in the inverted file **/ -int -invforward(INVCONTROL *invcntl) -{ - invstep(invcntl); - /* skip things with 0 postings */ - /* FIXME HBB: magic number alert! (3) */ - while (((ENTRY * )(invcntl->logblk->invblk + 3) + invcntl->keypnt)->post == 0) { - invstep(invcntl); - } - /* Check for having wrapped - reached start of inverted file! */ - if ((invcntl->numblk == 0) && (invcntl->keypnt == 0)) - return(0); - return(1); +int invforward(INVCONTROL *invcntl) { + invstep(invcntl); + /* skip things with 0 postings */ + /* FIXME HBB: magic number alert! (3) */ + while(((ENTRY *)(invcntl->logblk->invblk + 3) + invcntl->keypnt)->post == 0) { + invstep(invcntl); + } + /* Check for having wrapped - reached start of inverted file! */ + if((invcntl->numblk == 0) && (invcntl->keypnt == 0)) return (0); + return (1); } /** invterm gets the present term from the present logical block **/ -long -invterm(INVCONTROL *invcntl, char *term) -{ - ENTRY * entryptr; - - /* FIXME HBB: magic number alert! (3) */ - entryptr = (ENTRY *)(invcntl->logblk->invblk + 3) + invcntl->keypnt; - strncpy(term, invcntl->logblk->chrblk + entryptr->offset, - (int) entryptr->size); - *(term + entryptr->size) = '\0'; - return(entryptr->post); +long invterm(INVCONTROL *invcntl, char *term) { + ENTRY *entryptr; + + /* FIXME HBB: magic number alert! (3) */ + entryptr = (ENTRY *)(invcntl->logblk->invblk + 3) + invcntl->keypnt; + strncpy(term, invcntl->logblk->chrblk + entryptr->offset, (int)entryptr->size); + *(term + entryptr->size) = '\0'; + return (entryptr->post); } /** invfind searches for an individual item in the inverted file **/ -long -invfind(INVCONTROL *invcntl, char *searchterm) /* term being searched for */ +long invfind(INVCONTROL *invcntl, char *searchterm) /* term being searched for */ { - int imid, ilow, ihigh; - long num; - int i; - unsigned long *intptr, *intptr2; - ENTRY *entryptr; - - /* make sure it is initialized via invready */ - if (invcntl->invfile == 0) - return(-1L); - - /* now search for the appropriate finger block */ - intptr = (unsigned long *)invcntl->iindex; - - ilow = 0; - ihigh = *intptr++ - 1; - while (ilow <= ihigh) { - imid = (ilow + ihigh) / 2; - intptr2 = intptr + imid; - i = strcmp(searchterm, (invcntl->iindex + *intptr2)); - if (i < 0) - ihigh = imid - 1; - else if (i > 0) - ilow = ++imid; - else { - ilow = imid + 1; - break; - } - } - /* be careful about case where searchterm is after last in this block */ - imid = (ilow) ? ilow - 1 : 0; - - /* fetch the appropriate logical block if not in core */ - /* note always fetch it if the file is busy */ - if ((imid != invcntl->numblk) || (invcntl->param.filestat >= INVBUSY)) { - fseek(invcntl->invfile, - (imid*invcntl->param.sizeblk) + invcntl->param.cntlsize, - SEEK_SET); - invcntl->numblk = imid; - fread(invcntl->logblk, (int)invcntl->param.sizeblk, 1, - invcntl->invfile); - } + int imid, ilow, ihigh; + long num; + int i; + unsigned long *intptr, *intptr2; + ENTRY *entryptr; + + /* make sure it is initialized via invready */ + if(invcntl->invfile == 0) return (-1L); + + /* now search for the appropriate finger block */ + intptr = (unsigned long *)invcntl->iindex; + + ilow = 0; + ihigh = *intptr++ - 1; + while(ilow <= ihigh) { + imid = (ilow + ihigh) / 2; + intptr2 = intptr + imid; + i = strcmp(searchterm, (invcntl->iindex + *intptr2)); + if(i < 0) + ihigh = imid - 1; + else if(i > 0) + ilow = ++imid; + else { + ilow = imid + 1; + break; + } + } + /* be careful about case where searchterm is after last in this block */ + imid = (ilow) ? ilow - 1 : 0; + + /* fetch the appropriate logical block if not in core */ + /* note always fetch it if the file is busy */ + if((imid != invcntl->numblk) || (invcntl->param.filestat >= INVBUSY)) { + fseek(invcntl->invfile, + (imid * invcntl->param.sizeblk) + invcntl->param.cntlsize, + SEEK_SET); + invcntl->numblk = imid; + fread(invcntl->logblk, (int)invcntl->param.sizeblk, 1, invcntl->invfile); + } srch_ext: - /* now find the term in this block. tricky this */ - intptr = (unsigned long *) invcntl->logblk->invblk; - - ilow = 0; - ihigh = *intptr - 1; - intptr += 3; - num = 0; - while (ilow <= ihigh) { - imid = (ilow + ihigh) / 2; - entryptr = (ENTRY *)intptr + imid; - i = strncmp(searchterm, invcntl->logblk->chrblk + entryptr->offset, - (int) entryptr->size ); - if (i == 0) - i = strlen(searchterm) - entryptr->size; - if (i < 0) - ihigh = imid - 1; - else if (i > 0) - ilow = ++imid; - else { - num = entryptr->post; - break; - } - } - /* be careful about case where searchterm is after last in this block */ - if (imid >= invcntl->logblk->invblk[0]) { - invcntl->keypnt = invcntl->logblk->invblk[0]; - invstep(invcntl); - /* note if this happens the term could be in extended block */ - if (invcntl->param.startbyte < invcntl->numblk * invcntl->param.sizeblk) - goto srch_ext; - } else - invcntl->keypnt = imid; - return(num); + /* now find the term in this block. tricky this */ + intptr = (unsigned long *)invcntl->logblk->invblk; + + ilow = 0; + ihigh = *intptr - 1; + intptr += 3; + num = 0; + while(ilow <= ihigh) { + imid = (ilow + ihigh) / 2; + entryptr = (ENTRY *)intptr + imid; + i = strncmp(searchterm, + invcntl->logblk->chrblk + entryptr->offset, + (int)entryptr->size); + if(i == 0) i = strlen(searchterm) - entryptr->size; + if(i < 0) + ihigh = imid - 1; + else if(i > 0) + ilow = ++imid; + else { + num = entryptr->post; + break; + } + } + /* be careful about case where searchterm is after last in this block */ + if(imid >= invcntl->logblk->invblk[0]) { + invcntl->keypnt = invcntl->logblk->invblk[0]; + invstep(invcntl); + /* note if this happens the term could be in extended block */ + if(invcntl->param.startbyte < invcntl->numblk * invcntl->param.sizeblk) + goto srch_ext; + } else + invcntl->keypnt = imid; + return (num); } #if DEBUG /** invdump dumps the block the term parameter is in **/ -void -invdump(INVCONTROL *invcntl, char *term) -{ - long i, j, n, *longptr; - ENTRY * entryptr; - char temp[512], *ptr; - - /* dump superindex if term is "-" */ - if (*term == '-') { - j = atoi(term + 1); - longptr = (long *)invcntl->iindex; - n = *longptr++; - printf("Superindex dump, num blocks=%ld\n", n); - longptr += j; - while ((longptr <= ((long *)invcntl->iindex) + n) && invbreak == 0) { - printf("%2ld %6ld %s\n", j++, *longptr, invcntl->iindex + *longptr); - longptr++; - } - return; - } else if (*term == '#') { - j = atoi(term + 1); - /* fetch the appropriate logical block */ - invcntl->numblk = j; - fseek(invcntl->invfile, - (j * invcntl->param.sizeblk) + invcntl->param.cntlsize, - SEEK_SET); - fread(invcntl->logblk, (int) invcntl->param.sizeblk, 1, - invcntl->invfile); - } else - i = abs((int) invfind(invcntl, term)); - longptr = invcntl->logblk->invblk; - n = *longptr++; - printf("Entry term to invdump=%s, postings=%ld, forwrd ptr=%ld, back ptr=%ld\n" - , term, i, *(longptr), *(longptr + 1)); - /* FIXME HBB: magic number alert! (3) */ - entryptr = (ENTRY *) (invcntl->logblk->invblk + 3); - printf("%ld terms in this block, block=%ld\n", n, invcntl->numblk); - printf("\tterm\t\t\tposts\tsize\toffset\tspace\t1st word\n"); - for (j = 0; j < n && invbreak == 0; j++) { - ptr = invcntl->logblk->chrblk + entryptr->offset; - strncpy(temp, ptr, (int) entryptr->size); - temp[entryptr->size] = '\0'; - ptr += (sizeof(long) * (long)((entryptr->size + (sizeof(long) - 1)) / sizeof(long))); - printf("%2ld %-24s\t%5ld\t%3d\t%d\t%d\t%ld\n", j, temp, entryptr->post, - entryptr->size, entryptr->offset, entryptr->space, - *(long *)ptr); - entryptr++; - } +void invdump(INVCONTROL *invcntl, char *term) { + long i, j, n, *longptr; + ENTRY *entryptr; + char temp[512], *ptr; + + /* dump superindex if term is "-" */ + if(*term == '-') { + j = atoi(term + 1); + longptr = (long *)invcntl->iindex; + n = *longptr++; + printf("Superindex dump, num blocks=%ld\n", n); + longptr += j; + while((longptr <= ((long *)invcntl->iindex) + n) && invbreak == 0) { + printf("%2ld %6ld %s\n", j++, *longptr, invcntl->iindex + *longptr); + longptr++; + } + return; + } else if(*term == '#') { + j = atoi(term + 1); + /* fetch the appropriate logical block */ + invcntl->numblk = j; + fseek(invcntl->invfile, + (j * invcntl->param.sizeblk) + invcntl->param.cntlsize, + SEEK_SET); + fread(invcntl->logblk, (int)invcntl->param.sizeblk, 1, invcntl->invfile); + } else + i = abs((int)invfind(invcntl, term)); + longptr = invcntl->logblk->invblk; + n = *longptr++; + printf("Entry term to invdump=%s, postings=%ld, forwrd ptr=%ld, back ptr=%ld\n", + term, + i, + *(longptr), + *(longptr + 1)); + /* FIXME HBB: magic number alert! (3) */ + entryptr = (ENTRY *)(invcntl->logblk->invblk + 3); + printf("%ld terms in this block, block=%ld\n", n, invcntl->numblk); + printf("\tterm\t\t\tposts\tsize\toffset\tspace\t1st word\n"); + for(j = 0; j < n && invbreak == 0; j++) { + ptr = invcntl->logblk->chrblk + entryptr->offset; + strncpy(temp, ptr, (int)entryptr->size); + temp[entryptr->size] = '\0'; + ptr += + (sizeof(long) * (long)((entryptr->size + (sizeof(long) - 1)) / sizeof(long))); + printf("%2ld %-24s\t%5ld\t%3d\t%d\t%d\t%ld\n", + j, + temp, + entryptr->post, + entryptr->size, + entryptr->offset, + entryptr->space, + *(long *)ptr); + entryptr++; + } } #endif -static int -boolready(void) -{ - numitems = 0; - if (item1 != NULL) - free(item1); - setsize1 = SETINC; - if ((item1 = malloc(SETINC * sizeof(*item1))) == NULL) { - invcannotalloc(SETINC); - return(-1); - } - if (item2 != NULL) - free(item2); - setsize2 = SETINC; - if ((item2 = malloc(SETINC * sizeof(*item2))) == NULL) { - invcannotalloc(SETINC); - return(-1); - } - item = item1; - enditem = item; - return(0); +static int boolready(void) { + numitems = 0; + if(item1 != NULL) free(item1); + setsize1 = SETINC; + if((item1 = malloc(SETINC * sizeof(*item1))) == NULL) { + invcannotalloc(SETINC); + return (-1); + } + if(item2 != NULL) free(item2); + setsize2 = SETINC; + if((item2 = malloc(SETINC * sizeof(*item2))) == NULL) { + invcannotalloc(SETINC); + return (-1); + } + item = item1; + enditem = item; + return (0); } -void -boolclear(void) -{ - numitems = 0; - item = item1; - enditem = item; +void boolclear(void) { + numitems = 0; + item = item1; + enditem = item; } -POSTING * -boolfile(INVCONTROL *invcntl, long *num, int boolarg) -{ - ENTRY *entryptr; - FILE *file; - void *ptr; - unsigned long *ptr2; - POSTING *newitem = NULL; /* initialize, to avoid warning */ - POSTING posting; - unsigned u; - POSTING *newsetp = NULL, *set1p; - long newsetc, set1c, set2c; - - /* FIXME HBB: magic number alert! (3) */ - entryptr = (ENTRY *) (invcntl->logblk->invblk + 3) + invcntl->keypnt; - ptr = invcntl->logblk->chrblk + entryptr->offset; - ptr2 = ((unsigned long *) ptr) + (entryptr->size + (sizeof(long) - 1)) / sizeof(long); - *num = entryptr->post; - switch (boolarg) { - case bool_OR: - case falseT: - if (*num == 0) { - *num = numitems; - return(item); - } - } - /* make room for the new set */ - u = 0; - switch (boolarg) { - case AND: - case falseT: - newsetp = item; - break; - - case bool_OR: - u = enditem - item; - /* FALLTHROUGH */ - case REVERSEfalseT: - u += *num; - if (item == item2) { - if (u > setsize1) { - u += SETINC; - if ((item1 = realloc(item1, u * sizeof(*item1))) == NULL) { - invcannotalloc(u * sizeof(*item1)); - boolready(); - *num = -1; - return(NULL); - } - setsize1 = u; - } - newitem = item1; - } - else { - if (u > setsize2) { - u += SETINC; - if ((item2 = realloc(item2, u * sizeof(*item2))) == NULL) { - invcannotalloc(u * sizeof(*item2)); - boolready(); - *num = -1; - return(NULL); - } - setsize2 = u; - } - newitem = item2; - } +POSTING *boolfile(INVCONTROL *invcntl, long *num, int boolarg) { + ENTRY *entryptr; + FILE *file; + void *ptr; + unsigned long *ptr2; + POSTING *newitem = NULL; /* initialize, to avoid warning */ + POSTING posting; + unsigned u; + POSTING *newsetp = NULL, *set1p; + long newsetc, set1c, set2c; + + /* FIXME HBB: magic number alert! (3) */ + entryptr = (ENTRY *)(invcntl->logblk->invblk + 3) + invcntl->keypnt; + ptr = invcntl->logblk->chrblk + entryptr->offset; + ptr2 = ((unsigned long *)ptr) + (entryptr->size + (sizeof(long) - 1)) / sizeof(long); + *num = entryptr->post; + switch(boolarg) { + case bool_OR: + case falseT: + if(*num == 0) { + *num = numitems; + return (item); + } + } + /* make room for the new set */ + u = 0; + switch(boolarg) { + case AND: + case falseT: + newsetp = item; + break; + + case bool_OR: + u = enditem - item; + /* FALLTHROUGH */ + case REVERSEfalseT: + u += *num; + if(item == item2) { + if(u > setsize1) { + u += SETINC; + if((item1 = realloc(item1, u * sizeof(*item1))) == NULL) { + invcannotalloc(u * sizeof(*item1)); + boolready(); + *num = -1; + return (NULL); + } + setsize1 = u; + } + newitem = item1; + } else { + if(u > setsize2) { + u += SETINC; + if((item2 = realloc(item2, u * sizeof(*item2))) == NULL) { + invcannotalloc(u * sizeof(*item2)); + boolready(); + *num = -1; + return (NULL); + } + setsize2 = u; + } + newitem = item2; + } #if 0 /* this write is only need by commented-out code later */ set1p = item; #endif - newsetp = newitem; - } - file = invcntl->postfile; - fseek(file, *ptr2, SEEK_SET); - fread(&posting, sizeof(posting), 1, file); - newsetc = 0; - switch (boolarg) { - case bool_OR: - /* while something in both sets */ - set1p = item; - newsetp = newitem; - for (set1c = 0, set2c = 0; - set1c < numitems && set2c < *num; newsetc++) { - if (set1p->lineoffset < posting.lineoffset) { - *newsetp++ = *set1p++; - set1c++; - } - else if (set1p->lineoffset > posting.lineoffset) { - *newsetp++ = posting; - fread(&posting, (int) sizeof(posting), 1, file); - set2c++; - } - else if (set1p->type < posting.type) { - *newsetp++ = *set1p++; - set1c++; - } - else if (set1p->type > posting.type) { - *newsetp++ = posting; - fread(&posting, (int) sizeof(posting), 1, file); - set2c++; - } - else { /* identical postings */ - *newsetp++ = *set1p++; - set1c++; - fread(&posting, (int) sizeof(posting), 1, file); - set2c++; - } - } - /* find out what ran out and move the rest in */ - if (set1c < numitems) { - newsetc += numitems - set1c; - while (set1c++ < numitems) { - *newsetp++ = *set1p++; - } - } else { - while (set2c++ < *num) { - *newsetp++ = posting; - newsetc++; - fread(&posting, (int) sizeof(posting), 1, file); - } - } - item = newitem; - break; /* end of bool_OR */ + newsetp = newitem; + } + file = invcntl->postfile; + fseek(file, *ptr2, SEEK_SET); + fread(&posting, sizeof(posting), 1, file); + newsetc = 0; + switch(boolarg) { + case bool_OR: + /* while something in both sets */ + set1p = item; + newsetp = newitem; + for(set1c = 0, set2c = 0; set1c < numitems && set2c < *num; newsetc++) { + if(set1p->lineoffset < posting.lineoffset) { + *newsetp++ = *set1p++; + set1c++; + } else if(set1p->lineoffset > posting.lineoffset) { + *newsetp++ = posting; + fread(&posting, (int)sizeof(posting), 1, file); + set2c++; + } else if(set1p->type < posting.type) { + *newsetp++ = *set1p++; + set1c++; + } else if(set1p->type > posting.type) { + *newsetp++ = posting; + fread(&posting, (int)sizeof(posting), 1, file); + set2c++; + } else { /* identical postings */ + *newsetp++ = *set1p++; + set1c++; + fread(&posting, (int)sizeof(posting), 1, file); + set2c++; + } + } + /* find out what ran out and move the rest in */ + if(set1c < numitems) { + newsetc += numitems - set1c; + while(set1c++ < numitems) { + *newsetp++ = *set1p++; + } + } else { + while(set2c++ < *num) { + *newsetp++ = posting; + newsetc++; + fread(&posting, (int)sizeof(posting), 1, file); + } + } + item = newitem; + break; /* end of bool_OR */ #if 0 case AND: for (set1c = 0, set2c = 0; set1c < numitems && set2c < *num; ) { @@ -1139,11 +1091,11 @@ boolfile(INVCONTROL *invcntl, long *num, int boolarg) item = newitem; break; /* end of REVERSEfalseT */ #endif - } - numitems = newsetc; - *num = newsetc; - enditem = (POSTING *) newsetp; - return((POSTING *) item); + } + numitems = newsetc; + *num = newsetc; + enditem = (POSTING *)newsetp; + return ((POSTING *)item); } #if 0 @@ -1184,21 +1136,15 @@ boolsave(int clear) /* flag about whether to clear core */ } #endif -static void -invcannotalloc(unsigned n) -{ - fprintf(stderr, PROGRAM_NAME ": cannot allocate %u bytes\n", n); +static void invcannotalloc(unsigned n) { + fprintf(stderr, PROGRAM_NAME ": cannot allocate %u bytes\n", n); } -static void -invcannotopen(char *file) -{ - fprintf(stderr, PROGRAM_NAME "%s: cannot open file %s\n", file); +static void invcannotopen(char *file) { + fprintf(stderr, PROGRAM_NAME "%s: cannot open file %s\n", file); } -static void -invcannotwrite(char *file) -{ - perror(PROGRAM_NAME); /* must be first to preserve errno */ - fprintf(stderr, PROGRAM_NAME ": write to file %s failed\n", file); +static void invcannotwrite(char *file) { + perror(PROGRAM_NAME); /* must be first to preserve errno */ + fprintf(stderr, PROGRAM_NAME ": write to file %s failed\n", file); } diff --git a/src/invlib.h b/src/invlib.h index 3522971..9f3e858 100644 --- a/src/invlib.h +++ b/src/invlib.h @@ -33,82 +33,82 @@ #ifndef CSCOPE_INVLIB_H #define CSCOPE_INVLIB_H -#include /* need definition of FILE* */ -#include /* need definition of CHAR_MAX */ +#include /* need definition of FILE* */ +#include /* need definition of CHAR_MAX */ /* inverted index definitions */ /* postings temporary file long number coding into characters */ -#if CHAR_MAX==255 -# define BASE 223 /* 255 - ' ' */ -# define PRECISION 4 /* maximum digits after converting a long */ +#if CHAR_MAX == 255 +# define BASE 223 /* 255 - ' ' */ +# define PRECISION 4 /* maximum digits after converting a long */ #else -# if CHAR_MAX==127 /* assume sign-extension of a char when converted to an int */ -# define BASE 95 /* 127 - ' ' */ -# define PRECISION 5 /* maximum digits after converting a long */ +# if CHAR_MAX == 127 /* assume sign-extension of a char when converted to an int */ +# define BASE 95 /* 127 - ' ' */ +# define PRECISION 5 /* maximum digits after converting a long */ # else - #error Need a platform with 8 bits in a char value +# error Need a platform with 8 bits in a char value # endif #endif /* inverted index access parameters */ -#define INVAVAIL 0 -#define INVBUSY 1 -#define INVALONE 2 +#define INVAVAIL 0 +#define INVBUSY 1 +#define INVALONE 2 /* boolean set operations */ -#define bool_OR 3 -#define AND 4 -#define falseT 5 -#define REVERSEfalseT 6 +#define bool_OR 3 +#define AND 4 +#define falseT 5 +#define REVERSEfalseT 6 /* note that the entire first block is for parameters */ -typedef struct { - long version; /* inverted index format version */ - long filestat; /* file status word */ - long sizeblk; /* size of logical block in bytes */ - long startbyte; /* first byte of superfinger */ - long supsize; /* size of superfinger in bytes */ - long cntlsize; /* size of max cntl space (should be a multiple of BUFSIZ) */ - long share; /* flag whether to use shared memory */ +typedef struct { + long version; /* inverted index format version */ + long filestat; /* file status word */ + long sizeblk; /* size of logical block in bytes */ + long startbyte; /* first byte of superfinger */ + long supsize; /* size of superfinger in bytes */ + long cntlsize; /* size of max cntl space (should be a multiple of BUFSIZ) */ + long share; /* flag whether to use shared memory */ } PARAM; -typedef struct { - FILE *invfile; /* the inverted file ptr */ - FILE *postfile; /* posting file ptr */ - PARAM param; /* control parameters for the file */ - char *iindex; /* ptr to space for superindex */ - union logicalblk *logblk; /* ptr to space for a logical block */ - long numblk; /* number of block presently at *logblk */ - long keypnt; /* number item in present block found */ +typedef struct { + FILE *invfile; /* the inverted file ptr */ + FILE *postfile; /* posting file ptr */ + PARAM param; /* control parameters for the file */ + char *iindex; /* ptr to space for superindex */ + union logicalblk *logblk; /* ptr to space for a logical block */ + long numblk; /* number of block presently at *logblk */ + long keypnt; /* number item in present block found */ } INVCONTROL; -typedef struct { - short offset; /* offset in this logical block */ - unsigned char size; /* size of term */ - unsigned char space; /* number of longs of growth space */ - long post; /* number of postings for this entry */ +typedef struct { + short offset; /* offset in this logical block */ + unsigned char size; /* size of term */ + unsigned char space; /* number of longs of growth space */ + long post; /* number of postings for this entry */ } ENTRY; -typedef struct { - long lineoffset; /* source line database offset */ - long fcnoffset; /* function name database offset */ - long fileindex : 24; /* source file name index */ - long type : 8; /* reference type (mark character) */ +typedef struct { + long lineoffset; /* source line database offset */ + long fcnoffset; /* function name database offset */ + long fileindex : 24; /* source file name index */ + long type : 8; /* reference type (mark character) */ } POSTING; -extern long *srcoffset; /* source file name database offsets */ -extern int nsrcoffset; /* number of file name database offsets */ +extern long *srcoffset; /* source file name database offsets */ +extern int nsrcoffset; /* number of file name database offsets */ -void boolclear(void); -POSTING *boolfile(INVCONTROL *invcntl, long *num, int boolarg); -void invclose(INVCONTROL *invcntl); -void invdump(INVCONTROL *invcntl, char *term); -long invfind(INVCONTROL *invcntl, char *searchterm); -int invforward(INVCONTROL *invcntl); -int invopen(INVCONTROL *invcntl, char *invname, char *invpost, int status); -long invmake(char *invname, char *invpost, FILE *infile); -long invterm(INVCONTROL *invcntl, char *term); +void boolclear(void); +POSTING *boolfile(INVCONTROL *invcntl, long *num, int boolarg); +void invclose(INVCONTROL *invcntl); +void invdump(INVCONTROL *invcntl, char *term); +long invfind(INVCONTROL *invcntl, char *searchterm); +int invforward(INVCONTROL *invcntl); +int invopen(INVCONTROL *invcntl, char *invname, char *invpost, int status); +long invmake(char *invname, char *invpost, FILE *infile); +long invterm(INVCONTROL *invcntl, char *term); #endif /* CSCOPE_INVLIB_H */ diff --git a/src/keys.h b/src/keys.h index 6ea2ec6..3556aa0 100644 --- a/src/keys.h +++ b/src/keys.h @@ -12,48 +12,48 @@ #define KEY_UNDEF_BASE 0 #ifndef KEY_DOWN -# define KEY_DOWN KEY_UNDEF_BASE-1 +# define KEY_DOWN KEY_UNDEF_BASE - 1 #endif #ifndef KEY_UP -# define KEY_UP KEY_UNDEF_BASE-2 +# define KEY_UP KEY_UNDEF_BASE - 2 #endif #ifndef KEY_LEFT -# define KEY_LEFT KEY_UNDEF_BASE-3 +# define KEY_LEFT KEY_UNDEF_BASE - 3 #endif #ifndef KEY_RIGHT -# define KEY_RIGHT KEY_UNDEF_BASE-4 +# define KEY_RIGHT KEY_UNDEF_BASE - 4 #endif #ifndef KEY_HOME -# define KEY_HOME _KEY_UNDEF_BASE-5 +# define KEY_HOME _KEY_UNDEF_BASE - 5 #endif #ifndef KEY_LL -# define KEY_LL KEY_UNDEF_BASE-6 +# define KEY_LL KEY_UNDEF_BASE - 6 #endif #ifndef KEY_PPAGE -# define KEY_PPAGE KEY_UNDEF_BASE-7 +# define KEY_PPAGE KEY_UNDEF_BASE - 7 #endif #ifndef KEY_NPAGE -# define KEY_NPAGE KEY_UNDEF_BASE-8 +# define KEY_NPAGE KEY_UNDEF_BASE - 8 #endif #ifndef KEY_ENTER -# define KEY_ENTER KEY_UNDEF_BASE-9 +# define KEY_ENTER KEY_UNDEF_BASE - 9 #endif #ifndef KEY_CLEAR -# define KEY_CLEAR KEY_UNDEF_BASE-10 +# define KEY_CLEAR KEY_UNDEF_BASE - 10 #endif #ifndef KEY_RESIZE -# define KEY_RESIZE KEY_UNDEF_BASE-11 +# define KEY_RESIZE KEY_UNDEF_BASE - 11 #endif #ifndef KEY_END -# define KEY_END KEY_UNDEF_BASE-12 +# define KEY_END KEY_UNDEF_BASE - 12 #endif /* Always define these keys */ #ifndef ESC -# define ESC '\033' /* escape character */ +# define ESC '\033' /* escape character */ #endif #ifndef DEL -# define DEL '\177' /* delete character */ +# define DEL '\177' /* delete character */ #endif diff --git a/src/library.h b/src/library.h index 4116c1b..e3ff5c2 100644 --- a/src/library.h +++ b/src/library.h @@ -33,19 +33,19 @@ #ifndef CSCOPE_LIBRARY_H #define CSCOPE_LIBRARY_H -#include /* need FILE* type def. */ +#include /* need FILE* type def. */ /* private library */ -char *compath(char *pathname); -char *egrepinit(const char *egreppat); -char *logdir(char *name); -const char *basename(const char *path); -FILE *myfopen(char *path, char *mode); -char *mygetenv(char *variable, char *deflt); -int myopen(char *path, int flag, int mode); -FILE *mypopen(char *cmd, char *mode); -int mypclose(FILE *ptr); -FILE *vpfopen(char *filename, char *type); -void egrepcaseless(int i); +char *compath(char *pathname); +char *egrepinit(const char *egreppat); +char *logdir(char *name); +const char *basename(const char *path); +FILE *myfopen(char *path, char *mode); +char *mygetenv(char *variable, char *deflt); +int myopen(char *path, int flag, int mode); +FILE *mypopen(char *cmd, char *mode); +int mypclose(FILE *ptr); +FILE *vpfopen(char *filename, char *type); +void egrepcaseless(int i); #endif /* CSCOPE_LIBRARY_H */ diff --git a/src/logdir.c b/src/logdir.c index 068d0d4..34a7213 100644 --- a/src/logdir.c +++ b/src/logdir.c @@ -43,58 +43,50 @@ #include #include "global.h" -#define OURBUFSIZ 160 /* renamed: avoid conflict with */ +#define OURBUFSIZ 160 /* renamed: avoid conflict with */ -static char line[OURBUFSIZ+1]; +static char line[OURBUFSIZ + 1]; /* Internal prototypes: */ -static char *nextfield(char *p); +static char *nextfield(char *p); - -static char * -nextfield(char *p) -{ - while (*p && *p != ':') - ++p; - if (*p) *p++ = 0; - return(p); +static char *nextfield(char *p) { + while(*p && *p != ':') + ++p; + if(*p) *p++ = 0; + return (p); } -char * -logdir(char *name) -{ - char *p; - int i, j; - int pwf; - - /* attempt to open the password file */ - if ((pwf = myopen("/etc/passwd", 0, 0)) == -1) - return(0); - - /* find the matching password entry */ - do { - /* get the next line in the password file */ - i = read(pwf, line, OURBUFSIZ); - for (j = 0; j < i; j++) - if (line[j] == '\n') - break; - /* return a null pointer if the whole file has been read */ - if (j >= i) - return(0); - line[++j] = 0; /* terminate the line */ - (void) lseek(pwf, (long) (j - i), 1); /* point at the next line */ - p = nextfield(line); /* get the logname */ - } while (*name != *line || /* fast pretest */ - strcmp(name, line) != 0); - (void) close(pwf); - - /* skip the intervening fields */ - p = nextfield(p); - p = nextfield(p); - p = nextfield(p); - p = nextfield(p); - - /* return the login directory */ - (void) nextfield(p); - return(p); +char *logdir(char *name) { + char *p; + int i, j; + int pwf; + + /* attempt to open the password file */ + if((pwf = myopen("/etc/passwd", 0, 0)) == -1) return (0); + + /* find the matching password entry */ + do { + /* get the next line in the password file */ + i = read(pwf, line, OURBUFSIZ); + for(j = 0; j < i; j++) + if(line[j] == '\n') break; + /* return a null pointer if the whole file has been read */ + if(j >= i) return (0); + line[++j] = 0; /* terminate the line */ + (void)lseek(pwf, (long)(j - i), 1); /* point at the next line */ + p = nextfield(line); /* get the logname */ + } while(*name != *line || /* fast pretest */ + strcmp(name, line) != 0); + (void)close(pwf); + + /* skip the intervening fields */ + p = nextfield(p); + p = nextfield(p); + p = nextfield(p); + p = nextfield(p); + + /* return the login directory */ + (void)nextfield(p); + return (p); } diff --git a/src/lookup.c b/src/lookup.c index e22418b..ee2ab93 100644 --- a/src/lookup.c +++ b/src/lookup.c @@ -39,11 +39,11 @@ #include "lookup.h" /* keyword text for fast testing of keywords in the scanner */ -char enumtext[] = "enum"; -char externtext[] = "extern"; -char structtext[] = "struct"; -char typedeftext[] = "typedef"; -char uniontext[] = "union"; +char enumtext[] = "enum"; +char externtext[] = "extern"; +char structtext[] = "struct"; +char typedeftext[] = "typedef"; +char uniontext[] = "union"; /* This keyword table is also used for keyword text compression. Keywords * with an index less than the numeric value of a space are replaced with the @@ -51,99 +51,93 @@ char uniontext[] = "union"; * without changing the database file version and adding compatibility code * for old databases. */ -struct keystruct keyword[] = { - {"", '\0', NULL}, /* dummy entry */ - {"#define", ' ', NULL}, /* must be table entry 1 */ - {"#include", ' ', NULL}, /* must be table entry 2 */ - {"break", '\0', NULL}, /* rarely in cross-reference */ - {"case", ' ', NULL}, - {"char", ' ', NULL}, - {"continue", '\0', NULL}, /* rarely in cross-reference */ - {"default", '\0', NULL}, /* rarely in cross-reference */ - {"double", ' ', NULL}, - {"\t", '\0', NULL}, /* must be the table entry 9 */ - {"\n", '\0', NULL}, /* must be the table entry 10 */ - {"else", ' ', NULL}, - {enumtext, ' ', NULL}, - {externtext, ' ', NULL}, - {"float", ' ', NULL}, - {"for", '(', NULL}, - {"goto", ' ', NULL}, - {"if", '(', NULL}, - {"int", ' ', NULL}, - {"long", ' ', NULL}, - {"register", ' ', NULL}, - {"return", '\0', NULL}, - {"short", ' ', NULL}, - {"sizeof", '\0', NULL}, - {"static", ' ', NULL}, - {structtext, ' ', NULL}, - {"switch", '(', NULL}, - {typedeftext, ' ', NULL}, - {uniontext, ' ', NULL}, - {"unsigned", ' ', NULL}, - {"void", ' ', NULL}, - {"while", '(', NULL}, - - /* these keywords are not compressed */ - {"do", '\0', NULL}, - {"auto", ' ', NULL}, - {"fortran", ' ', NULL}, - {"const", ' ', NULL}, - {"signed", ' ', NULL}, - {"volatile", ' ', NULL}, +struct keystruct keyword[] = { + {"", '\0', NULL}, /* dummy entry */ + {"#define", ' ', NULL}, /* must be table entry 1 */ + {"#include", ' ', NULL}, /* must be table entry 2 */ + {"break", '\0', NULL}, /* rarely in cross-reference */ + {"case", ' ', NULL}, + {"char", ' ', NULL}, + {"continue", '\0', NULL}, /* rarely in cross-reference */ + {"default", '\0', NULL}, /* rarely in cross-reference */ + {"double", ' ', NULL}, + {"\t", '\0', NULL}, /* must be the table entry 9 */ + {"\n", '\0', NULL}, /* must be the table entry 10 */ + {"else", ' ', NULL}, + {enumtext, ' ', NULL}, + {externtext, ' ', NULL}, + {"float", ' ', NULL}, + {"for", '(', NULL}, + {"goto", ' ', NULL}, + {"if", '(', NULL}, + {"int", ' ', NULL}, + {"long", ' ', NULL}, + {"register", ' ', NULL}, + {"return", '\0', NULL}, + {"short", ' ', NULL}, + {"sizeof", '\0', NULL}, + {"static", ' ', NULL}, + {structtext, ' ', NULL}, + {"switch", '(', NULL}, + {typedeftext, ' ', NULL}, + {uniontext, ' ', NULL}, + {"unsigned", ' ', NULL}, + {"void", ' ', NULL}, + {"while", '(', NULL}, + + /* these keywords are not compressed */ + {"do", '\0', NULL}, + {"auto", ' ', NULL}, + {"fortran", ' ', NULL}, + {"const", ' ', NULL}, + {"signed", ' ', NULL}, + {"volatile", ' ', NULL}, }; -#define KEYWORDS (sizeof(keyword) / sizeof(keyword[0])) +#define KEYWORDS (sizeof(keyword) / sizeof(keyword[0])) -#define HASHMOD (KEYWORDS * 2 + 1) +#define HASHMOD (KEYWORDS * 2 + 1) -static struct keystruct *hashtab[HASHMOD]; /* pointer table */ +static struct keystruct *hashtab[HASHMOD]; /* pointer table */ /* put the keywords into the symbol table */ -void -initsymtab(void) -{ - unsigned int i, j; - struct keystruct *p; - - for (i = 1; i < KEYWORDS; ++i) { - p = keyword + i; - j = hash(p->text) % HASHMOD; - p->next = hashtab[j]; - hashtab[j] = p; - } +void initsymtab(void) { + unsigned int i, j; + struct keystruct *p; + + for(i = 1; i < KEYWORDS; ++i) { + p = keyword + i; + j = hash(p->text) % HASHMOD; + p->next = hashtab[j]; + hashtab[j] = p; + } } /* see if this identifier is a keyword */ -char * -lookup(char *ident) -{ - struct keystruct *p; - int c; - - /* look up the identifier in the keyword table */ - for (p = hashtab[hash(ident) % HASHMOD]; p != NULL; p = p->next) { - if (strequal(ident, p->text)) { - if (compress == true && (c = p - keyword) < ' ') { - ident[0] = c; /* compress the keyword */ - } - return(p->text); - } - } - /* this is an identifier */ - return(NULL); +char *lookup(char *ident) { + struct keystruct *p; + int c; + + /* look up the identifier in the keyword table */ + for(p = hashtab[hash(ident) % HASHMOD]; p != NULL; p = p->next) { + if(strequal(ident, p->text)) { + if(compress == true && (c = p - keyword) < ' ') { + ident[0] = c; /* compress the keyword */ + } + return (p->text); + } + } + /* this is an identifier */ + return (NULL); } /* form hash value for string */ -int -hash(char *ss) -{ - int i; - unsigned char *s = (unsigned char *)ss; - - for (i = 0; *s != '\0'; ) - i += *s++; /* += is faster than <<= for cscope */ - return(i); +int hash(char *ss) { + int i; + unsigned char *s = (unsigned char *)ss; + + for(i = 0; *s != '\0';) + i += *s++; /* += is faster than <<= for cscope */ + return (i); } diff --git a/src/lookup.h b/src/lookup.h index 4766ba1..37dfd51 100644 --- a/src/lookup.h +++ b/src/lookup.h @@ -36,10 +36,10 @@ /* declarations for objects defined in lookup.c */ /* keyword text for fast testing of keywords in the scanner */ -extern char enumtext[]; -extern char externtext[]; -extern char structtext[]; -extern char typedeftext[]; -extern char uniontext[]; +extern char enumtext[]; +extern char externtext[]; +extern char structtext[]; +extern char typedeftext[]; +extern char uniontext[]; #endif /* CSCOPE_LOOKUP_H */ diff --git a/src/main.c b/src/main.c index 8e49e40..f65e033 100644 --- a/src/main.c +++ b/src/main.c @@ -40,10 +40,10 @@ #include "build.h" #include "vp.h" -#include "version.h" /* FILEVERSION and FIXVERSION */ +#include "version.h" /* FILEVERSION and FIXVERSION */ #include "scanner.h" -#include /* atoi */ +#include /* atoi */ #include #include /* needed by stat.h */ #include /* stat */ @@ -51,591 +51,547 @@ #include /* defaults for unset environment variables */ -#define EDITOR "vi" -#define HOME "/" /* no $HOME --> use root directory */ -#define SHELL "sh" -#define LINEFLAG "+%s" /* default: used by vi and emacs */ -#define TMPDIR "/tmp" +#define EDITOR "vi" +#define HOME "/" /* no $HOME --> use root directory */ +#define SHELL "sh" +#define LINEFLAG "+%s" /* default: used by vi and emacs */ +#define TMPDIR "/tmp" /* note: these digraph character frequencies were calculated from possible printable digraphs in the cross-reference for the C compiler */ -char dichar1[] = " teisaprnl(of)=c"; /* 16 most frequent first chars */ -char dichar2[] = " tnerpla"; /* 8 most frequent second chars - using the above as first chars */ -char dicode1[256]; /* digraph first character code */ -char dicode2[256]; /* digraph second character code */ - -char *editor, *shell, *lineflag; /* environment variables */ -char *home; /* Home directory */ -bool lineflagafterfile; -char *argv0; /* command name */ -bool compress = true; /* compress the characters in the crossref */ -bool dbtruncated; /* database symbols are truncated to 8 chars */ -int dispcomponents = 1; /* file path components to display */ -bool editallprompt = true; /* prompt between editing files */ -unsigned int fileargc; /* file argument count */ -char **fileargv; /* file argument values */ -int fileversion; /* cross-reference file version */ -bool incurses = false; /* in curses */ -bool invertedindex; /* the database has an inverted index */ -bool isuptodate; /* consider the crossref up-to-date */ -bool kernelmode; /* don't use DFLT_INCDIR - bad for kernels */ -bool linemode = false; /* use line oriented user interface */ -bool verbosemode = false; /* print extra information on line mode */ -bool recurse_dir = false; /* recurse dirs when searching for src files */ -char *namefile; /* file of file names */ -bool ogs = false; /* display OGS book and subsystem names */ -char *prependpath; /* prepend path to file names */ -FILE *refsfound; /* references found file */ -char temp1[PATHLEN + 1]; /* temporary file name */ -char temp2[PATHLEN + 1]; /* temporary file name */ -char tempdirpv[PATHLEN + 1]; /* private temp directory */ -long totalterms; /* total inverted index terms */ -bool trun_syms; /* truncate symbols to 8 characters */ -char tempstring[TEMPSTRING_LEN + 1]; /* use this as a buffer, instead of 'yytext', - * which had better be left alone */ -char *tmpdir; /* temporary directory */ - -static char path[PATHLEN + 1]; /* file path */ +char dichar1[] = " teisaprnl(of)=c"; /* 16 most frequent first chars */ +char dichar2[] = " tnerpla"; /* 8 most frequent second chars + using the above as first chars */ +char dicode1[256]; /* digraph first character code */ +char dicode2[256]; /* digraph second character code */ + +char *editor, *shell, *lineflag; /* environment variables */ +char *home; /* Home directory */ +bool lineflagafterfile; +char *argv0; /* command name */ +bool compress = true; /* compress the characters in the crossref */ +bool dbtruncated; /* database symbols are truncated to 8 chars */ +int dispcomponents = 1; /* file path components to display */ +bool editallprompt = true; /* prompt between editing files */ +unsigned int fileargc; /* file argument count */ +char **fileargv; /* file argument values */ +int fileversion; /* cross-reference file version */ +bool incurses = false; /* in curses */ +bool invertedindex; /* the database has an inverted index */ +bool isuptodate; /* consider the crossref up-to-date */ +bool kernelmode; /* don't use DFLT_INCDIR - bad for kernels */ +bool linemode = false; /* use line oriented user interface */ +bool verbosemode = false; /* print extra information on line mode */ +bool recurse_dir = false; /* recurse dirs when searching for src files */ +char *namefile; /* file of file names */ +bool ogs = false; /* display OGS book and subsystem names */ +char *prependpath; /* prepend path to file names */ +FILE *refsfound; /* references found file */ +char temp1[PATHLEN + 1]; /* temporary file name */ +char temp2[PATHLEN + 1]; /* temporary file name */ +char tempdirpv[PATHLEN + 1]; /* private temp directory */ +long totalterms; /* total inverted index terms */ +bool trun_syms; /* truncate symbols to 8 characters */ +char tempstring[TEMPSTRING_LEN + 1]; /* use this as a buffer, instead of 'yytext', + * which had better be left alone */ +char *tmpdir; /* temporary directory */ + +static char path[PATHLEN + 1]; /* file path */ /* Internal prototypes: */ -static void skiplist(FILE *oldrefs); -static void initcompress(void); -static inline void readenv(void); -static inline void linemode_event_loop(void); -static inline void screenmode_event_loop(void); +static void skiplist(FILE *oldrefs); +static void initcompress(void); +static inline void readenv(void); +static inline void linemode_event_loop(void); +static inline void screenmode_event_loop(void); #if defined(KEY_RESIZE) && !defined(__DJGPP__) -void -sigwinch_handler(int sig, siginfo_t *info, void *unused) -{ +void sigwinch_handler(int sig, siginfo_t *info, void *unused) { UNUSED(sig); UNUSED(info); UNUSED(unused); - if(incurses == true){ - ungetch(KEY_RESIZE); - } + if(incurses == true) { ungetch(KEY_RESIZE); } } #endif -static -inline -void -siginit(void){ - /* if running in the foreground */ - if (signal(SIGINT, SIG_IGN) != SIG_IGN) { +static inline void siginit(void) { + /* if running in the foreground */ + if(signal(SIGINT, SIG_IGN) != SIG_IGN) { /* cleanup on the interrupt and quit signals */ signal(SIGINT, myexit); signal(SIGQUIT, myexit); - } - /* cleanup on the hangup signal */ - signal(SIGHUP, myexit); - - /* ditto the TERM signal */ - signal(SIGTERM, myexit); - - /* ignore PIPE signal, so myexit() will have a chance to clean up in - * linemode, while in curses mode the "|" command can cause a pipe signal - * too - */ - signal(SIGPIPE, SIG_IGN); - - if (linemode == false) { - signal(SIGWINCH, sigwinch_handler); - } + } + /* cleanup on the hangup signal */ + signal(SIGHUP, myexit); + + /* ditto the TERM signal */ + signal(SIGTERM, myexit); + + /* ignore PIPE signal, so myexit() will have a chance to clean up in + * linemode, while in curses mode the "|" command can cause a pipe signal + * too + */ + signal(SIGPIPE, SIG_IGN); + + if(linemode == false) { signal(SIGWINCH, sigwinch_handler); } } -void -cannotopen(const char *const file) -{ - posterr("Cannot open file %s", file); +void cannotopen(const char *const file) { + posterr("Cannot open file %s", file); } /* FIXME MTE - should use postfatal here */ -void -cannotwrite(const char *const file) -{ - char msg[MSGLEN + 1]; +void cannotwrite(const char *const file) { + char msg[MSGLEN + 1]; - snprintf(msg, sizeof(msg), "Removed file %s because write failed", file); + snprintf(msg, sizeof(msg), "Removed file %s because write failed", file); - myperror(msg); /* display the reason */ + myperror(msg); /* display the reason */ - unlink(file); - myexit(1); /* calls exit(2), which closes files */ + unlink(file); + myexit(1); /* calls exit(2), which closes files */ } - /* set up the digraph character tables for text compression */ -static void -initcompress(void) -{ - int i; - - if (compress == true) { - for (i = 0; i < 16; ++i) { - dicode1[(unsigned char) (dichar1[i])] = i * 8 + 1; - } - for (i = 0; i < 8; ++i) { - dicode2[(unsigned char) (dichar2[i])] = i + 1; - } - } +static void initcompress(void) { + int i; + + if(compress == true) { + for(i = 0; i < 16; ++i) { + dicode1[(unsigned char)(dichar1[i])] = i * 8 + 1; + } + for(i = 0; i < 8; ++i) { + dicode2[(unsigned char)(dichar2[i])] = i + 1; + } + } } /* skip the list in the cross-reference file */ -static void -skiplist(FILE *oldrefs) -{ - int i; - - if (fscanf(oldrefs, "%d", &i) != 1) { - postfatal(PROGRAM_NAME ": cannot read list size from file %s\n", reffile); - /* NOTREACHED */ - } - while (--i >= 0) { - if (fscanf(oldrefs, "%*s") != 0) { - postfatal(PROGRAM_NAME ": cannot read list name from file %s\n", reffile); - /* NOTREACHED */ - } - } +static void skiplist(FILE *oldrefs) { + int i; + + if(fscanf(oldrefs, "%d", &i) != 1) { + postfatal(PROGRAM_NAME ": cannot read list size from file %s\n", reffile); + /* NOTREACHED */ + } + while(--i >= 0) { + if(fscanf(oldrefs, "%*s") != 0) { + postfatal(PROGRAM_NAME ": cannot read list name from file %s\n", reffile); + /* NOTREACHED */ + } + } } /* cleanup and exit */ -void -myexit(int sig) -{ - /* Close file before unlinking it. DOS absolutely needs it */ - if (refsfound != NULL){ - fclose(refsfound); - } - - /* remove any temporary files */ - if (temp1[0] != '\0') { - unlink(temp1); - unlink(temp2); - rmdir(tempdirpv); - } - /* restore the terminal to its original mode */ - if (incurses == true) { - exitcurses(); - } - /* dump core for debugging on the quit signal */ - if (sig == SIGQUIT) { - abort(); - } - /* HBB 20000421: be nice: free allocated data */ - freefilelist(); - freeinclist(); - freesrclist(); - freecrossref(); - free_newbuildfiles(); - - if( remove_symfile_onexit == true ) { - unlink( reffile ); - unlink( invname ); - unlink( invpost ); - } - - exit(sig); +void myexit(int sig) { + /* Close file before unlinking it. DOS absolutely needs it */ + if(refsfound != NULL) { fclose(refsfound); } + + /* remove any temporary files */ + if(temp1[0] != '\0') { + unlink(temp1); + unlink(temp2); + rmdir(tempdirpv); + } + /* restore the terminal to its original mode */ + if(incurses == true) { exitcurses(); } + /* dump core for debugging on the quit signal */ + if(sig == SIGQUIT) { abort(); } + /* HBB 20000421: be nice: free allocated data */ + freefilelist(); + freeinclist(); + freesrclist(); + freecrossref(); + free_newbuildfiles(); + + if(remove_symfile_onexit == true) { + unlink(reffile); + unlink(invname); + unlink(invpost); + } + + exit(sig); } -static inline void readenv(void){ - editor = mygetenv("EDITOR", EDITOR); - editor = mygetenv("VIEWER", editor); /* use viewer if set */ - editor = mygetenv("CSCOPE_EDITOR", editor); /* has last word */ - home = mygetenv("HOME", HOME); - shell = mygetenv("SHELL", SHELL); - lineflag = mygetenv("CSCOPE_LINEFLAG", LINEFLAG); - lineflagafterfile = getenv("CSCOPE_LINEFLAG_AFTER_FILE") ? 1 : 0; - tmpdir = mygetenv("TMPDIR", TMPDIR); +static inline void readenv(void) { + editor = mygetenv("EDITOR", EDITOR); + editor = mygetenv("VIEWER", editor); /* use viewer if set */ + editor = mygetenv("CSCOPE_EDITOR", editor); /* has last word */ + home = mygetenv("HOME", HOME); + shell = mygetenv("SHELL", SHELL); + lineflag = mygetenv("CSCOPE_LINEFLAG", LINEFLAG); + lineflagafterfile = getenv("CSCOPE_LINEFLAG_AFTER_FILE") ? 1 : 0; + tmpdir = mygetenv("TMPDIR", TMPDIR); } -static inline void linemode_event_loop(void){ - int c; - - if (*input_line != '\0') { /* do any optional search */ - if (search(input_line) == true) { - /* print the total number of lines in - * verbose mode */ - if (verbosemode == true) - printf(PROGRAM_NAME ": %d lines\n", - totallines); - - while ((c = getc(refsfound)) != EOF) - putchar(c); - } - } - if (onesearch == true) { - myexit(0); - /* NOTREACHED */ - } - - for (char *s;;) { - char buf[PATLEN + 2]; - - printf(">> "); - fflush(stdout); - if (fgets(buf, sizeof(buf), stdin) == NULL) { - myexit(0); - } - /* remove any trailing newline character */ - if (*(s = buf + strlen(buf) - 1) == '\n') { - *s = '\0'; - } - switch (*buf) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': /* samuel only */ - field = *buf - '0'; - strcpy(input_line, buf + 1); - if (search(input_line) == false) { - printf("Unable to search database\n"); - } else { - printf("cscope: %d lines\n", totallines); - while ((c = getc(refsfound)) != EOF) { - putchar(c); - } - } - break; - - case 'c': /* toggle caseless mode */ - case ctrl('C'): - if (caseless == false) { - caseless = true; - } else { - caseless = false; - } - egrepcaseless(caseless); - break; - - case 'r': /* rebuild database cscope style */ - case ctrl('R'): - freefilelist(); - makefilelist(); - /* FALLTHROUGH */ - - case 'R': /* rebuild database samuel style */ - rebuild(); - putchar('\n'); - break; - - case 'C': /* clear file names */ - freefilelist(); - putchar('\n'); - break; - - case 'F': /* add a file name */ - strcpy(path, buf + 1); - if (infilelist(path) == false && - (s = inviewpath(path)) != NULL) { - addsrcfile(s); - } - putchar('\n'); - break; - - case 'q': /* quit */ - case ctrl('D'): - case ctrl('Z'): - myexit(0); - /* NOTREACHED */ - break; - default: - fprintf(stderr, PROGRAM_NAME ": unknown command '%s'\n", buf); - break; - } - } +static inline void linemode_event_loop(void) { + int c; + + if(*input_line != '\0') { /* do any optional search */ + if(search(input_line) == true) { + /* print the total number of lines in + * verbose mode */ + if(verbosemode == true) printf(PROGRAM_NAME ": %d lines\n", totallines); + + while((c = getc(refsfound)) != EOF) + putchar(c); + } + } + if(onesearch == true) { + myexit(0); + /* NOTREACHED */ + } + + for(char *s;;) { + char buf[PATLEN + 2]; + + printf(">> "); + fflush(stdout); + if(fgets(buf, sizeof(buf), stdin) == NULL) { myexit(0); } + /* remove any trailing newline character */ + if(*(s = buf + strlen(buf) - 1) == '\n') { *s = '\0'; } + switch(*buf) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': /* samuel only */ + field = *buf - '0'; + strcpy(input_line, buf + 1); + if(search(input_line) == false) { + printf("Unable to search database\n"); + } else { + printf("cscope: %d lines\n", totallines); + while((c = getc(refsfound)) != EOF) { + putchar(c); + } + } + break; + + case 'c': /* toggle caseless mode */ + case ctrl('C'): + if(caseless == false) { + caseless = true; + } else { + caseless = false; + } + egrepcaseless(caseless); + break; + + case 'r': /* rebuild database cscope style */ + case ctrl('R'): + freefilelist(); + makefilelist(); + /* FALLTHROUGH */ + + case 'R': /* rebuild database samuel style */ + rebuild(); + putchar('\n'); + break; + + case 'C': /* clear file names */ + freefilelist(); + putchar('\n'); + break; + + case 'F': /* add a file name */ + strcpy(path, buf + 1); + if(infilelist(path) == false && (s = inviewpath(path)) != NULL) { + addsrcfile(s); + } + putchar('\n'); + break; + + case 'q': /* quit */ + case ctrl('D'): + case ctrl('Z'): + myexit(0); + /* NOTREACHED */ + break; + default: + fprintf(stderr, PROGRAM_NAME ": unknown command '%s'\n", buf); + break; + } + } } -static inline void screenmode_event_loop(void){ - for (;;) { - display(); - handle_input(wgetch(stdscr)); // NOTE: getch() does not return key codes - } +static inline void screenmode_event_loop(void) { + for(;;) { + display(); + handle_input(wgetch(stdscr)); // NOTE: getch() does not return key codes + } } -int -main(int argc, char **argv) -{ - FILE *names; /* name file pointer */ - int oldnum; /* number in old cross-ref */ - FILE *oldrefs; /* old cross-reference file */ - char *s; - unsigned int i; - pid_t pid; - struct stat stat_buf; - mode_t orig_umask; - - yyin = stdin; - yyout = stdout; - /* save the command name for messages */ - argv0 = argv[0]; - - /* set the options */ - argv = parse_options(&argc, argv); - - /* read the environment */ - readenv(); - - /* XXX remove if/when clearerr() in dir.c does the right thing. */ - if (namefile && strcmp(namefile, "-") == 0 && !buildonly) { - postfatal(PROGRAM_NAME ": Must use -b if file list comes from stdin\n"); - /* NOTREACHED */ - } - - /* make sure that tmpdir exists */ - if (lstat (tmpdir, &stat_buf)) { - fprintf (stderr, PROGRAM_NAME ": Temporary directory %s does not exist or cannot be accessed\n", - tmpdir); - fprintf (stderr, - PROGRAM_NAME ": Please create the directory or set the environment variable\n" - PROGRAM_NAME ": TMPDIR to a valid directory\n"); - myexit(1); - } - - /* create the temporary file names */ - orig_umask = umask(S_IRWXG|S_IRWXO); - pid = getpid(); - snprintf(tempdirpv, sizeof(tempdirpv), "%s/"PROGRAM_NAME".%d", tmpdir, pid); - if(mkdir(tempdirpv,S_IRWXU)) { - fprintf(stderr, - PROGRAM_NAME ": Could not create private temp dir %s\n", - tempdirpv); - myexit(1); - } - umask(orig_umask); - - snprintf(temp1, sizeof(temp1), "%s/"PROGRAM_NAME".1", tempdirpv); - snprintf(temp2, sizeof(temp2), "%s/"PROGRAM_NAME".2", tempdirpv); - - /* if the database path is relative and it can't be created */ - if (reffile[0] != '/' && access(".", WRITE) != 0) { - - /* put it in the home directory if the database may not be - * up-to-date or doesn't exist in the relative directory, - * so a database in the current directory will be - * used instead of failing to open a non-existant database in - * the home directory - */ - snprintf(path, sizeof(path), "%s/%s", home, reffile); - if (isuptodate == false || access(path, READ) == 0) { - reffile = strdup(path); - snprintf(path, sizeof(path), "%s/%s", home, invname); - invname = strdup(path); - snprintf(path, sizeof(path), "%s/%s", home, invpost); - invpost = strdup(path); - } - } - - siginit(); - - if (linemode == false) { - dispinit(); /* initialize display parameters */ - postmsg(""); /* clear any build progress message */ - display(); /* display the version number and input fields */ - } - - - /* if the cross-reference is to be considered up-to-date */ - if (isuptodate == true) { - if ((oldrefs = vpfopen(reffile, "rb")) == NULL) { - postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile); - /* NOTREACHED */ - } - /* get the crossref file version but skip the current directory */ - if (fscanf(oldrefs, PROGRAM_NAME " %d %*s", &fileversion) != 1) { - postfatal(PROGRAM_NAME ": cannot read file version from file %s\n", - reffile); - /* NOTREACHED */ - } - if (fileversion >= 8) { - - /* override these command line options */ - compress = true; - invertedindex = false; - - /* see if there are options in the database */ - for (int c;;) { - getc(oldrefs); /* skip the blank */ - if ((c = getc(oldrefs)) != '-') { - ungetc(c, oldrefs); - break; - } - switch (getc(oldrefs)) { - case 'c': /* ASCII characters only */ - compress = false; - break; - case 'q': /* quick search */ - invertedindex = true; - fscanf(oldrefs, "%ld", &totalterms); - break; - case 'T': /* truncate symbols to 8 characters */ - dbtruncated = true; - trun_syms = true; - break; - } - } - initcompress(); - seek_to_trailer(oldrefs); - } - /* skip the source and include directory lists */ - skiplist(oldrefs); - skiplist(oldrefs); - - /* get the number of source files */ - if (fscanf(oldrefs, "%lu", &nsrcfiles) != 1) { - postfatal( - PROGRAM_NAME ": cannot read source file size from file %s\n", - reffile); - /* NOTREACHED */ - } - /* get the source file list */ - srcfiles = malloc(nsrcfiles * sizeof(*srcfiles)); - if (fileversion >= 9) { - - /* allocate the string space */ - if (fscanf(oldrefs, "%d", &oldnum) != 1) { - postfatal( - PROGRAM_NAME ": cannot read string space size from file %s\n", - reffile); - /* NOTREACHED */ - } - s = malloc(oldnum); - getc(oldrefs); /* skip the newline */ - - /* read the strings */ - if (fread(s, oldnum, 1, oldrefs) != 1) { - postfatal( - PROGRAM_NAME ": cannot read source file names from file %s\n", - reffile); - /* NOTREACHED */ - } - /* change newlines to nulls */ - for (i = 0; i < nsrcfiles; ++i) { - srcfiles[i] = s; - for (++s; *s != '\n'; ++s) { - ; - } - *s = '\0'; - ++s; - } - /* if there is a file of source file names */ - if ((namefile != NULL && (names = vpfopen(namefile, "r")) != NULL) - || (names = vpfopen(NAMEFILE, "r")) != NULL) { - - /* read any -p option from it */ - while (fgets(path, sizeof(path), names) != NULL && *path == '-') { - i = path[1]; - s = path + 2; /* for "-Ipath" */ - if (*s == '\0') { /* if "-I path" */ - fgets(path, sizeof(path), names); - s = path; - } - switch (i) { - case 'p': /* file path components to display */ - if (*s < '0' || *s > '9') { - posterr(PROGRAM_NAME ": -p option in file %s: missing or invalid numeric value\n", namefile); - - } - dispcomponents = atoi(s); - } - } - fclose(names); - } - } else { - for (i = 0; i < nsrcfiles; ++i) { - if (!fgets(path, sizeof(path), oldrefs) ) { - postfatal( - PROGRAM_NAME ": cannot read source file name from file %s\n", - reffile - ); - /* NOTREACHED */ - } - srcfiles[i] = strdup(path); - } - } - fclose(oldrefs); - } else { - /* save the file arguments */ - fileargc = argc; - fileargv = argv; - - /* get source directories from the environment */ - if ((s = getenv("SOURCEDIRS")) != NULL) { - sourcedir(s); - } - /* make the source file list */ - srcfiles = malloc(msrcfiles * sizeof(*srcfiles)); - makefilelist(); - if (nsrcfiles == 0) { - postfatal(PROGRAM_NAME ": no source files found\n"); - /* NOTREACHED */ - } - /* get include directories from the environment */ - if ((s = getenv("INCLUDEDIRS")) != NULL) { - includedir(s); - } - /* add /usr/include to the #include directory list, - but not in kernelmode... kernels tend not to use it. */ - if (kernelmode == false) { - if (NULL != (s = getenv("INCDIR"))) { - includedir(s); - } else { - includedir(DFLT_INCDIR); - } - } - - /* initialize the C keyword table */ - initsymtab(); - - /* Tell build.c about the filenames to create: */ - setup_build_filenames(reffile); - - /* build the cross-reference */ - initcompress(); - if (linemode == false || verbosemode == true) { /* display if verbose as well */ - postmsg("Building cross-reference..."); - } - build(); - if (linemode == false ) { - postmsg(""); /* clear any build progress message */ - } - if (buildonly == true) { - myexit(0); - /* NOTREACHED */ - } - } - opendatabase(); - - /* if using the line oriented user interface so cscope can be a - subprocess to emacs or samuel */ - if (linemode == true) { - linemode_event_loop(); - } - /* pause before clearing the screen if there have been error messages */ - if (errorsfound == true) { - errorsfound = false; - askforreturn(); - } - /* do any optional search */ - if (*input_line != '\0') { - //command(ctrl('Y')); /* search */ // XXX: fix - } else if (reflines != NULL) { - /* read any symbol reference lines file */ - readrefs(reflines); - } - - screenmode_event_loop(); - /* cleanup and exit */ - myexit(0); - /* NOTREACHED */ - return 0; /* avoid warning... */ +int main(int argc, char **argv) { + FILE *names; /* name file pointer */ + int oldnum; /* number in old cross-ref */ + FILE *oldrefs; /* old cross-reference file */ + char *s; + unsigned int i; + pid_t pid; + struct stat stat_buf; + mode_t orig_umask; + + yyin = stdin; + yyout = stdout; + /* save the command name for messages */ + argv0 = argv[0]; + + /* set the options */ + argv = parse_options(&argc, argv); + + /* read the environment */ + readenv(); + + /* XXX remove if/when clearerr() in dir.c does the right thing. */ + if(namefile && strcmp(namefile, "-") == 0 && !buildonly) { + postfatal(PROGRAM_NAME ": Must use -b if file list comes from stdin\n"); + /* NOTREACHED */ + } + + /* make sure that tmpdir exists */ + if(lstat(tmpdir, &stat_buf)) { + fprintf(stderr, + PROGRAM_NAME + ": Temporary directory %s does not exist or cannot be accessed\n", + tmpdir); + fprintf(stderr, + PROGRAM_NAME + ": Please create the directory or set the environment variable\n" PROGRAM_NAME + ": TMPDIR to a valid directory\n"); + myexit(1); + } + + /* create the temporary file names */ + orig_umask = umask(S_IRWXG | S_IRWXO); + pid = getpid(); + snprintf(tempdirpv, sizeof(tempdirpv), "%s/" PROGRAM_NAME ".%d", tmpdir, pid); + if(mkdir(tempdirpv, S_IRWXU)) { + fprintf(stderr, + PROGRAM_NAME ": Could not create private temp dir %s\n", + tempdirpv); + myexit(1); + } + umask(orig_umask); + + snprintf(temp1, sizeof(temp1), "%s/" PROGRAM_NAME ".1", tempdirpv); + snprintf(temp2, sizeof(temp2), "%s/" PROGRAM_NAME ".2", tempdirpv); + + /* if the database path is relative and it can't be created */ + if(reffile[0] != '/' && access(".", WRITE) != 0) { + + /* put it in the home directory if the database may not be + * up-to-date or doesn't exist in the relative directory, + * so a database in the current directory will be + * used instead of failing to open a non-existant database in + * the home directory + */ + snprintf(path, sizeof(path), "%s/%s", home, reffile); + if(isuptodate == false || access(path, READ) == 0) { + reffile = strdup(path); + snprintf(path, sizeof(path), "%s/%s", home, invname); + invname = strdup(path); + snprintf(path, sizeof(path), "%s/%s", home, invpost); + invpost = strdup(path); + } + } + + siginit(); + + if(linemode == false) { + dispinit(); /* initialize display parameters */ + postmsg(""); /* clear any build progress message */ + display(); /* display the version number and input fields */ + } + + + /* if the cross-reference is to be considered up-to-date */ + if(isuptodate == true) { + if((oldrefs = vpfopen(reffile, "rb")) == NULL) { + postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile); + /* NOTREACHED */ + } + /* get the crossref file version but skip the current directory */ + if(fscanf(oldrefs, PROGRAM_NAME " %d %*s", &fileversion) != 1) { + postfatal(PROGRAM_NAME ": cannot read file version from file %s\n", reffile); + /* NOTREACHED */ + } + if(fileversion >= 8) { + + /* override these command line options */ + compress = true; + invertedindex = false; + + /* see if there are options in the database */ + for(int c;;) { + getc(oldrefs); /* skip the blank */ + if((c = getc(oldrefs)) != '-') { + ungetc(c, oldrefs); + break; + } + switch(getc(oldrefs)) { + case 'c': /* ASCII characters only */ + compress = false; + break; + case 'q': /* quick search */ + invertedindex = true; + fscanf(oldrefs, "%ld", &totalterms); + break; + case 'T': /* truncate symbols to 8 characters */ + dbtruncated = true; + trun_syms = true; + break; + } + } + initcompress(); + seek_to_trailer(oldrefs); + } + /* skip the source and include directory lists */ + skiplist(oldrefs); + skiplist(oldrefs); + + /* get the number of source files */ + if(fscanf(oldrefs, "%lu", &nsrcfiles) != 1) { + postfatal(PROGRAM_NAME ": cannot read source file size from file %s\n", + reffile); + /* NOTREACHED */ + } + /* get the source file list */ + srcfiles = malloc(nsrcfiles * sizeof(*srcfiles)); + if(fileversion >= 9) { + + /* allocate the string space */ + if(fscanf(oldrefs, "%d", &oldnum) != 1) { + postfatal(PROGRAM_NAME ": cannot read string space size from file %s\n", + reffile); + /* NOTREACHED */ + } + s = malloc(oldnum); + getc(oldrefs); /* skip the newline */ + + /* read the strings */ + if(fread(s, oldnum, 1, oldrefs) != 1) { + postfatal(PROGRAM_NAME ": cannot read source file names from file %s\n", + reffile); + /* NOTREACHED */ + } + /* change newlines to nulls */ + for(i = 0; i < nsrcfiles; ++i) { + srcfiles[i] = s; + for(++s; *s != '\n'; ++s) { + ; + } + *s = '\0'; + ++s; + } + /* if there is a file of source file names */ + if((namefile != NULL && (names = vpfopen(namefile, "r")) != NULL) || + (names = vpfopen(NAMEFILE, "r")) != NULL) { + + /* read any -p option from it */ + while(fgets(path, sizeof(path), names) != NULL && *path == '-') { + i = path[1]; + s = path + 2; /* for "-Ipath" */ + if(*s == '\0') { /* if "-I path" */ + fgets(path, sizeof(path), names); + s = path; + } + switch(i) { + case 'p': /* file path components to display */ + if(*s < '0' || *s > '9') { + posterr(PROGRAM_NAME + ": -p option in file %s: missing or invalid numeric value\n", + namefile); + } + dispcomponents = atoi(s); + } + } + fclose(names); + } + } else { + for(i = 0; i < nsrcfiles; ++i) { + if(!fgets(path, sizeof(path), oldrefs)) { + postfatal(PROGRAM_NAME + ": cannot read source file name from file %s\n", + reffile); + /* NOTREACHED */ + } + srcfiles[i] = strdup(path); + } + } + fclose(oldrefs); + } else { + /* save the file arguments */ + fileargc = argc; + fileargv = argv; + + /* get source directories from the environment */ + if((s = getenv("SOURCEDIRS")) != NULL) { sourcedir(s); } + /* make the source file list */ + srcfiles = malloc(msrcfiles * sizeof(*srcfiles)); + makefilelist(); + if(nsrcfiles == 0) { + postfatal(PROGRAM_NAME ": no source files found\n"); + /* NOTREACHED */ + } + /* get include directories from the environment */ + if((s = getenv("INCLUDEDIRS")) != NULL) { includedir(s); } + /* add /usr/include to the #include directory list, + but not in kernelmode... kernels tend not to use it. */ + if(kernelmode == false) { + if(NULL != (s = getenv("INCDIR"))) { + includedir(s); + } else { + includedir(DFLT_INCDIR); + } + } + + /* initialize the C keyword table */ + initsymtab(); + + /* Tell build.c about the filenames to create: */ + setup_build_filenames(reffile); + + /* build the cross-reference */ + initcompress(); + if(linemode == false || verbosemode == true) { /* display if verbose as well */ + postmsg("Building cross-reference..."); + } + build(); + if(linemode == false) { postmsg(""); /* clear any build progress message */ } + if(buildonly == true) { + myexit(0); + /* NOTREACHED */ + } + } + opendatabase(); + + /* if using the line oriented user interface so cscope can be a + subprocess to emacs or samuel */ + if(linemode == true) { linemode_event_loop(); } + /* pause before clearing the screen if there have been error messages */ + if(errorsfound == true) { + errorsfound = false; + askforreturn(); + } + /* do any optional search */ + if(*input_line != '\0') { + // command(ctrl('Y')); /* search */ // XXX: fix + } else if(reflines != NULL) { + /* read any symbol reference lines file */ + readrefs(reflines); + } + + screenmode_event_loop(); + /* cleanup and exit */ + myexit(0); + /* NOTREACHED */ + return 0; /* avoid warning... */ } diff --git a/src/mouse.c b/src/mouse.c index ac1e948..e9f860c 100644 --- a/src/mouse.c +++ b/src/mouse.c @@ -37,439 +37,392 @@ extern int LINES; -#define FLDLINE (LINES - FIELDS - 1 - 1) /* first input field line */ +#define FLDLINE (LINES - FIELDS - 1 - 1) /* first input field line */ #include "global.h" -bool mouse = false; /* mouse interface */ +bool mouse = false; /* mouse interface */ -#ifdef UNIXPC /* build command requires #ifdef instead of #if */ -#include -bool unixpcmouse = false; /* running with a mouse on the Unix PC? */ -static int uw_hs, uw_vs; /* character height and width */ +#ifdef UNIXPC /* build command requires #ifdef instead of #if */ +# include +bool unixpcmouse = false; /* running with a mouse on the Unix PC? */ +static int uw_hs, uw_vs; /* character height and width */ #endif -typedef struct { /* menu */ - char *text; - char *value; +typedef struct { /* menu */ + char *text; + char *value; } MENU; -static MENU mainmenu[] = { /* main menu */ - {"Send", "##\033s##\r"}, - {"Repeat", "\031"}, - {"Edit All", "\05"}, - {"Rebuild", "\022"}, - {"Shell", "!"}, - {"Redraw", "\f"}, - {"Help", "?"}, - {"Exit", "\04"}, - {NULL, NULL} +static MENU mainmenu[] = { + /* main menu */ + {"Send", "##\033s##\r"}, + {"Repeat", "\031" }, + {"Edit All", "\05" }, + {"Rebuild", "\022" }, + {"Shell", "!" }, + {"Redraw", "\f" }, + {"Help", "?" }, + {"Exit", "\04" }, + {NULL, NULL } }; -static MENU changemenu[] = { /* change mode menu */ - {"Mark Screen", "*"}, - {"Mark All", "a"}, - {"Change", "\04"}, - {"No Change", "\033"}, - {"Shell", "!"}, - {"Redraw", "\f"}, - {"Help", "?"}, - {NULL, NULL} +static MENU changemenu[] = { + /* change mode menu */ + {"Mark Screen", "*" }, + {"Mark All", "a" }, + {"Change", "\04" }, + {"No Change", "\033"}, + {"Shell", "!" }, + {"Redraw", "\f" }, + {"Help", "?" }, + {NULL, NULL } }; -static MENU *loaded; /* menu loaded */ -static bool emacsviterm = false; /* terminal type */ +static MENU *loaded; /* menu loaded */ +static bool emacsviterm = false; /* terminal type */ -static void loadmenu(MENU *menu); -static int getcoordinate(void); -static int getpercent(void); +static void loadmenu(MENU *menu); +static int getcoordinate(void); +static int getpercent(void); /* see if there is a mouse interface */ -void -mouseinit(void) -{ - char *term; - - /* see if this is emacsterm or viterm */ - term = mygetenv("TERM", ""); - if (strcmp(term, "emacsterm") == 0 || - strcmp(term, "viterm") == 0) { - emacsviterm = true; - mouse = true; - } - /* the MOUSE enviroment variable is for 5620 terminal programs that have - mouse support but the TERM environment variable is the same as a - terminal without a mouse, such as myx */ - else if (strcmp(mygetenv("MOUSE", ""), "myx") == 0) { - mouse = true; - } +void mouseinit(void) { + char *term; + + /* see if this is emacsterm or viterm */ + term = mygetenv("TERM", ""); + if(strcmp(term, "emacsterm") == 0 || strcmp(term, "viterm") == 0) { + emacsviterm = true; + mouse = true; + } + /* the MOUSE enviroment variable is for 5620 terminal programs that have + mouse support but the TERM environment variable is the same as a + terminal without a mouse, such as myx */ + else if(strcmp(mygetenv("MOUSE", ""), "myx") == 0) { + mouse = true; + } #if UNIXPC - else if (strcmp(term,"s4") == 0 || - strcmp(term,"s120") == 0 || - strcmp(term,"s90") == 0) { - int retval; - struct uwdata uwd; /* Window data structure */ - struct umdata umd; /* Mouse data structure */ - - /* Ask for character size info */ - - retval = ioctl(1,WIOCGETD,&uwd); - if(retval || uwd.uw_hs <= 0 || uwd.uw_vs <= 0) { - /************************************************** - * something wrong with the kernel, so fake it... - **************************************************/ - if(!strcmp(term,"s4")) { - uw_hs = 9; - uw_vs = 12; - } - else { - uw_hs = 6; - uw_vs = 10; - } - } - else { - /* Kernel is working and knows about this font */ - uw_hs = uwd.uw_hs; - uw_vs = uwd.uw_vs; - } - - /************************************************** - * Now turn on mouse reporting so we can actually - * make use of all this stuff. - **************************************************/ - if((retval = ioctl(1,WIOCGETMOUSE,&umd)) != -1) { - umd.um_flags= MSDOWN+MSUP; - ioctl(1,WIOCSETMOUSE,&umd); - } - unixpcmouse = true; - } + else if(strcmp(term, "s4") == 0 || strcmp(term, "s120") == 0 || + strcmp(term, "s90") == 0) { + int retval; + struct uwdata uwd; /* Window data structure */ + struct umdata umd; /* Mouse data structure */ + + /* Ask for character size info */ + + retval = ioctl(1, WIOCGETD, &uwd); + if(retval || uwd.uw_hs <= 0 || uwd.uw_vs <= 0) { + /************************************************** + * something wrong with the kernel, so fake it... + **************************************************/ + if(!strcmp(term, "s4")) { + uw_hs = 9; + uw_vs = 12; + } else { + uw_hs = 6; + uw_vs = 10; + } + } else { + /* Kernel is working and knows about this font */ + uw_hs = uwd.uw_hs; + uw_vs = uwd.uw_vs; + } + + /************************************************** + * Now turn on mouse reporting so we can actually + * make use of all this stuff. + **************************************************/ + if((retval = ioctl(1, WIOCGETMOUSE, &umd)) != -1) { + umd.um_flags = MSDOWN + MSUP; + ioctl(1, WIOCSETMOUSE, &umd); + } + unixpcmouse = true; + } #endif - if (mouse == true) { - loadmenu(mainmenu); - } + if(mouse == true) { loadmenu(mainmenu); } } /* load the correct mouse menu */ -void -mousemenu(void) -{ - if (mouse == true) { - if (input_mode == INPUT_CHANGE) { - loadmenu(changemenu); - } - else { - loadmenu(mainmenu); - } - } +void mousemenu(void) { + if(mouse == true) { + if(input_mode == INPUT_CHANGE) { + loadmenu(changemenu); + } else { + loadmenu(mainmenu); + } + } } /* download a menu */ -static void -loadmenu(MENU *menu) -{ - int i; - - if (emacsviterm == true) { - mousereinit(); - (void) printf("\033V1"); /* display the scrollbar */ - (void) printf("\033M0@%s@%s@", menu[0].text, menu[0].value); - for (i = 1; menu[i].text != NULL; ++i) { - (void) printf("\033M@%s@%s@", menu[i].text, menu[i].value); - } - } - else { /* myx */ - int len; - - mousecleanup(); - (void) printf("\033[6;1X\033[9;1X"); - for (i = 0; menu[i].text != NULL; ++i) { - len = strlen(menu[i].text); - (void) printf("\033[%d;%dx%s%s", len, - (int) (len + strlen(menu[i].value)), - menu[i].text, menu[i].value); - } - loaded = menu; - } - (void) fflush(stdout); +static void loadmenu(MENU *menu) { + int i; + + if(emacsviterm == true) { + mousereinit(); + (void)printf("\033V1"); /* display the scrollbar */ + (void)printf("\033M0@%s@%s@", menu[0].text, menu[0].value); + for(i = 1; menu[i].text != NULL; ++i) { + (void)printf("\033M@%s@%s@", menu[i].text, menu[i].value); + } + } else { /* myx */ + int len; + + mousecleanup(); + (void)printf("\033[6;1X\033[9;1X"); + for(i = 0; menu[i].text != NULL; ++i) { + len = strlen(menu[i].text); + (void)printf("\033[%d;%dx%s%s", + len, + (int)(len + strlen(menu[i].value)), + menu[i].text, + menu[i].value); + } + loaded = menu; + } + (void)fflush(stdout); } /* reinitialize the mouse in case curses changed the attributes */ -void -mousereinit(void) -{ - if (emacsviterm == true) { +void mousereinit(void) { + if(emacsviterm == true) { - /* enable the mouse click and sweep coordinate control sequence */ - /* and switch to menu 2 */ - (void) printf("\033{2\033#2"); - (void) fflush(stdout); - } + /* enable the mouse click and sweep coordinate control sequence */ + /* and switch to menu 2 */ + (void)printf("\033{2\033#2"); + (void)fflush(stdout); + } } /* restore the mouse attributes */ -void -mousecleanup(void) -{ - int i; +void mousecleanup(void) { + int i; - if (loaded != NULL) { /* only true for myx */ + if(loaded != NULL) { /* only true for myx */ - /* remove the mouse menu */ - (void) printf("\033[6;0X\033[9;0X"); - for (i = 0; loaded[i].text != NULL; ++i) { - (void) printf("\033[0;0x"); - } - loaded = NULL; - } + /* remove the mouse menu */ + (void)printf("\033[6;0X\033[9;0X"); + for(i = 0; loaded[i].text != NULL; ++i) { + (void)printf("\033[0;0x"); + } + loaded = NULL; + } } /* draw the scrollbar */ -void -drawscrollbar(int top, int bot) -{ - int p1, p2; - - if (emacsviterm == true) { - if (bot > top) { - p1 = 16 + (top - 1) * 100 / totallines; - p2 = 16 + (bot - 1) * 100 / totallines; - if (p2 > 116) { - p2 = 116; - } - if (p1 < 16) { - p1 = 16; - } - /* don't send ^S or ^Q because it will hang a layer using cu(1) */ - if (p1 == ctrl('Q') || p1 == ctrl('S')) { - ++p1; - } - if (p2 == ctrl('Q') || p2 == ctrl('S')) { - ++p2; - } - } - else { - p1 = p2 = 16; - } - (void) printf("\033W%c%c", p1, p2); - } +void drawscrollbar(int top, int bot) { + int p1, p2; + + if(emacsviterm == true) { + if(bot > top) { + p1 = 16 + (top - 1) * 100 / totallines; + p2 = 16 + (bot - 1) * 100 / totallines; + if(p2 > 116) { p2 = 116; } + if(p1 < 16) { p1 = 16; } + /* don't send ^S or ^Q because it will hang a layer using cu(1) */ + if(p1 == ctrl('Q') || p1 == ctrl('S')) { ++p1; } + if(p2 == ctrl('Q') || p2 == ctrl('S')) { ++p2; } + } else { + p1 = p2 = 16; + } + (void)printf("\033W%c%c", p1, p2); + } } /* get the mouse information */ -MOUSE * -getmouseaction(char leading_char) -{ - static MOUSE m; +MOUSE *getmouseaction(char leading_char) { + static MOUSE m; #if UNIXPC - if(unixpcmouse == true && leading_char == ESC) { - - /* Called if cscope received an ESC character. See if it is - * a mouse report and if so, decipher it. A mouse report - * looks like: "[?xx;yy;b;rM" - */ - int x = 0, y = 0, button = 0, reason = 0; - int i; - - /* Get a mouse report. The form is: XX;YY;B;RM where - * XX is 1,2, or 3 decimal digits with the X pixel position. - * Similarly for YY. B is a single decimal digit with the - * button number (4 for one, 2 for two, and 1 for three). - * R is the reason for the mouse report. - * - * In general, the input is read until the mouse report has - * been completely read in or we have discovered that this - * escape sequence is falseT a mouse report. In the latter case - * return the last character read to the input stream with - * myungetch(). - */ - - /* Check for "[?" being next 2 chars */ - if(((i = getch()) != '[') || ((i = getch()) != '?')) { - myungetch(i); - return(NULL); - } - - /* Grab the X position (in pixels) */ - while(isdigit(i = getch())) { - x = (x*10) + (i - '0'); - } - if(i != ';') { - myungetch(i); - return(NULL); /* not a mouse report after all */ - } - - /* Grab the Y position (in pixels) */ - while(isdigit(i = getch())) { - y = (y*10) + (i - '0'); - } - if(i != ';') { - myungetch(i); - return(NULL); - } - - /* Get which button */ - if((button = getch()) > '4') { - myungetch(button); - return(NULL); - } - if((i = getch()) != ';') { - myungetch(i); - return(NULL); - } - - /* Get the reason for this mouse report */ - if((reason = getch()) > '8') { - myungetch(reason); - return(NULL); - } - - /* sequence should terminate with an 'M' */ - if((i = getch()) != 'M') { - myungetch(i); - return(NULL); - } - - - /* OK. We get a mouse report whenever a button is depressed - * or released. Let's ignore the report whenever the button - * is depressed until when I am ready to implement sweeping. - */ - if(reason != '2') { - return(NULL); /* '2' means button is released */ - } - - /************************************************************ - * Always indicate button 1 irregardless of which button was - * really pushed. - ************************************************************/ - m.button = 1; - - /************************************************************ - * Convert pixel coordinates to line and column coords. - * The height and width are obtained using an ioctl() call - * in mouseinit(). This assumes that variable width chars - * are not being used ('though it would probably work anyway). - ************************************************************/ - - m.x1 = x/uw_hs; /* pixel/horizontal_spacing */ - m.y1 = y/uw_vs; /* pixel/vertical_spacing */ - - /* "null" out the other fields */ - m.percent = m.x2 = m.y2 = -1; - } - else -#endif /* not UNIXPC */ - - if (mouse == true && leading_char == ctrl('X')) { - - switch (getch()) { - case ctrl('_'): /* click */ - if ((m.button = getch()) == '0') { /* if scrollbar */ - m.percent = getpercent(); - } - else { - m.x1 = getcoordinate(); - m.y1 = getcoordinate(); - m.x2 = m.y2 = -1; - } - break; - - case ctrl(']'): /* sweep */ - m.button = getch(); - m.x1 = getcoordinate(); - m.y1 = getcoordinate(); - m.x2 = getcoordinate(); - m.y2 = getcoordinate(); - break; - default: - return(NULL); - } - } - else return(NULL); - - return(&m); + if(unixpcmouse == true && leading_char == ESC) { + + /* Called if cscope received an ESC character. See if it is + * a mouse report and if so, decipher it. A mouse report + * looks like: "[?xx;yy;b;rM" + */ + int x = 0, y = 0, button = 0, reason = 0; + int i; + + /* Get a mouse report. The form is: XX;YY;B;RM where + * XX is 1,2, or 3 decimal digits with the X pixel position. + * Similarly for YY. B is a single decimal digit with the + * button number (4 for one, 2 for two, and 1 for three). + * R is the reason for the mouse report. + * + * In general, the input is read until the mouse report has + * been completely read in or we have discovered that this + * escape sequence is falseT a mouse report. In the latter case + * return the last character read to the input stream with + * myungetch(). + */ + + /* Check for "[?" being next 2 chars */ + if(((i = getch()) != '[') || ((i = getch()) != '?')) { + myungetch(i); + return (NULL); + } + + /* Grab the X position (in pixels) */ + while(isdigit(i = getch())) { + x = (x * 10) + (i - '0'); + } + if(i != ';') { + myungetch(i); + return (NULL); /* not a mouse report after all */ + } + + /* Grab the Y position (in pixels) */ + while(isdigit(i = getch())) { + y = (y * 10) + (i - '0'); + } + if(i != ';') { + myungetch(i); + return (NULL); + } + + /* Get which button */ + if((button = getch()) > '4') { + myungetch(button); + return (NULL); + } + if((i = getch()) != ';') { + myungetch(i); + return (NULL); + } + + /* Get the reason for this mouse report */ + if((reason = getch()) > '8') { + myungetch(reason); + return (NULL); + } + + /* sequence should terminate with an 'M' */ + if((i = getch()) != 'M') { + myungetch(i); + return (NULL); + } + + + /* OK. We get a mouse report whenever a button is depressed + * or released. Let's ignore the report whenever the button + * is depressed until when I am ready to implement sweeping. + */ + if(reason != '2') { return (NULL); /* '2' means button is released */ } + + /************************************************************ + * Always indicate button 1 irregardless of which button was + * really pushed. + ************************************************************/ + m.button = 1; + + /************************************************************ + * Convert pixel coordinates to line and column coords. + * The height and width are obtained using an ioctl() call + * in mouseinit(). This assumes that variable width chars + * are not being used ('though it would probably work anyway). + ************************************************************/ + + m.x1 = x / uw_hs; /* pixel/horizontal_spacing */ + m.y1 = y / uw_vs; /* pixel/vertical_spacing */ + + /* "null" out the other fields */ + m.percent = m.x2 = m.y2 = -1; + } else +#endif /* not UNIXPC */ + + if(mouse == true && leading_char == ctrl('X')) { + + switch(getch()) { + case ctrl('_'): /* click */ + if((m.button = getch()) == '0') { /* if scrollbar */ + m.percent = getpercent(); + } else { + m.x1 = getcoordinate(); + m.y1 = getcoordinate(); + m.x2 = m.y2 = -1; + } + break; + + case ctrl(']'): /* sweep */ + m.button = getch(); + m.x1 = getcoordinate(); + m.y1 = getcoordinate(); + m.x2 = getcoordinate(); + m.y2 = getcoordinate(); + break; + default: + return (NULL); + } + } else + return (NULL); + + return (&m); } /* get a row or column coordinate from a mouse button click or sweep */ -static int -getcoordinate(void) -{ - int c, next; - - c = getch(); - next = 0; - if (c == ctrl('A')) { - next = 95; - c = getch(); - } - if (c < ' ') { - return (0); - } - return (next + c - ' '); +static int getcoordinate(void) { + int c, next; + + c = getch(); + next = 0; + if(c == ctrl('A')) { + next = 95; + c = getch(); + } + if(c < ' ') { return (0); } + return (next + c - ' '); } /* get a percentage */ -static int -getpercent(void) -{ - int c; - - c = getch(); - if (c < 16) { - return(0); - } - if (c > 120) { - return(100); - } - return(c - 16); +static int getpercent(void) { + int c; + + c = getch(); + if(c < 16) { return (0); } + if(c > 120) { return (100); } + return (c - 16); } -int process_mouse(){ - int i; - MOUSE* p; - if ((p = getmouseaction(DUMMYCHAR)) == NULL) { - return(false); /* unknown control sequence */ - } - /* if the button number is a scrollbar tag */ - if (p->button == '0') { - //scrollbar(p); // XXX - return(false); - } - /* ignore a sweep */ - if (p->x2 >= 0) { - return(false); - } - /* if this is a line selection */ - if (p->y1 > FLDLINE) { - - /* find the selected line */ - /* note: the selection is forced into range */ - for (i = disprefs - 1; i > 0; --i) { - if (p->y1 >= displine[i]) { - return(false); - } - } - /* display it in the file with the editor */ - editref(i); - } else { /* this is an input field selection */ - field = p->y1 - FLDLINE; - /* force it into range */ - if (field >= FIELDS) { - field = FIELDS - 1; - } - resetcmd(); - return(false); - } +int process_mouse() { + int i; + MOUSE *p; + if((p = getmouseaction(DUMMYCHAR)) == NULL) { + return (false); /* unknown control sequence */ + } + /* if the button number is a scrollbar tag */ + if(p->button == '0') { + // scrollbar(p); // XXX + return (false); + } + /* ignore a sweep */ + if(p->x2 >= 0) { return (false); } + /* if this is a line selection */ + if(p->y1 > FLDLINE) { + + /* find the selected line */ + /* note: the selection is forced into range */ + for(i = disprefs - 1; i > 0; --i) { + if(p->y1 >= displine[i]) { return (false); } + } + /* display it in the file with the editor */ + editref(i); + } else { /* this is an input field selection */ + field = p->y1 - FLDLINE; + /* force it into range */ + if(field >= FIELDS) { field = FIELDS - 1; } + resetcmd(); + return (false); + } return false; } diff --git a/src/mygetenv.c b/src/mygetenv.c index 6be0940..2f965c1 100644 --- a/src/mygetenv.c +++ b/src/mygetenv.c @@ -36,14 +36,10 @@ /* return the non-null environment value or the default argument */ -char * -mygetenv(char *variable, char *deflt) -{ - char *value; - - value = getenv(variable); - if (value == NULL || *value == '\0') { - return(deflt); - } - return(value); +char *mygetenv(char *variable, char *deflt) { + char *value; + + value = getenv(variable); + if(value == NULL || *value == '\0') { return (deflt); } + return (value); } diff --git a/src/mypopen.c b/src/mypopen.c index 8c8a655..9034c42 100644 --- a/src/mypopen.c +++ b/src/mypopen.c @@ -35,11 +35,11 @@ #include #include #include -#include "global.h" /* pid_t, shell, and basename() */ +#include "global.h" /* pid_t, shell, and basename() */ -#define tst(a,b) (*mode == 'r'? (b) : (a)) -#define RDR 0 -#define WTR 1 +#define tst(a, b) (*mode == 'r' ? (b) : (a)) +#define RDR 0 +#define WTR 1 /* HBB 20010312: make this a bit safer --- don't blindly assume it's 1 */ #ifdef FD_CLOEXEC @@ -49,132 +49,112 @@ #endif #ifdef HAVE_IO_H -# include /* for setmode() */ +# include /* for setmode() */ #endif static pid_t popen_pid[20]; static void (*tstat)(int); -int -myopen(char *path, int flag, int mode) -{ - /* opens a file descriptor and then sets close-on-exec for the file */ - int fd; +int myopen(char *path, int flag, int mode) { + /* opens a file descriptor and then sets close-on-exec for the file */ + int fd; - /* If file is not explicitly in Binary mode, make - * sure we override silly Cygwin behaviour of automatic binary - * mode for files in "binary mounted" paths */ + /* If file is not explicitly in Binary mode, make + * sure we override silly Cygwin behaviour of automatic binary + * mode for files in "binary mounted" paths */ #if O_BINARY != O_TEXT - if (! (flag | O_BINARY)) - flag |= O_TEXT; + if(!(flag | O_BINARY)) flag |= O_TEXT; #endif - if(mode) - fd = open(path, flag, mode); - else - fd = open(path, flag); - - if(fd != -1 && (fcntl(fd, F_SETFD, CLOSE_ON_EXEC) != -1)) - return(fd); - - else - { - /* Ensure that if the fcntl fails and fd is valid, then - the file is closed properly. In general this should - not happen. */ - if (fd != -1) - { - close (fd); - } - - return(-1); - } + if(mode) + fd = open(path, flag, mode); + else + fd = open(path, flag); + + if(fd != -1 && (fcntl(fd, F_SETFD, CLOSE_ON_EXEC) != -1)) + return (fd); + + else { + /* Ensure that if the fcntl fails and fd is valid, then + the file is closed properly. In general this should + not happen. */ + if(fd != -1) { close(fd); } + + return (-1); + } } -FILE * -myfopen(char *path, char *mode) -{ - /* opens a file pointer and then sets close-on-exec for the file */ - FILE *fp; +FILE *myfopen(char *path, char *mode) { + /* opens a file pointer and then sets close-on-exec for the file */ + FILE *fp; - fp = fopen(path, mode); + fp = fopen(path, mode); #ifdef SETMODE - if (fp && ! strchr(mode, 'b')) { - SETMODE(fileno(fp), O_TEXT); - } + if(fp && !strchr(mode, 'b')) { SETMODE(fileno(fp), O_TEXT); } #endif /* SETMODE */ - if(fp && (fcntl(fileno(fp), F_SETFD, CLOSE_ON_EXEC) != -1)) - return(fp); + if(fp && (fcntl(fileno(fp), F_SETFD, CLOSE_ON_EXEC) != -1)) + return (fp); - else { - if (fp) - fclose(fp); - return(NULL); - } + else { + if(fp) fclose(fp); + return (NULL); + } } -FILE * -mypopen(char *cmd, char *mode) -{ - int p[2]; - pid_t *poptr; - int myside, yourside; - pid_t pid; - - if(pipe(p) < 0) - return(NULL); - myside = tst(p[WTR], p[RDR]); - yourside = tst(p[RDR], p[WTR]); - if((pid = fork()) == 0) { - /* myside and yourside reverse roles in child */ - int stdio; - - /* close all pipes from other popen's */ - for (poptr = popen_pid; poptr < popen_pid+20; poptr++) { - if(*poptr) - (void) close(poptr - popen_pid); - } - stdio = tst(0, 1); - close(myside); - close(stdio); - fcntl(yourside, F_DUPFD, stdio); - close(yourside); - execlp(shell, basename(shell), "-c", cmd, (void *)0); - _exit(1); - } else if (pid > 0) - tstat = signal(SIGTSTP, SIG_DFL); - if(pid == -1) - return(NULL); - popen_pid[myside] = pid; - (void) close(yourside); - return(fdopen(myside, mode)); +FILE *mypopen(char *cmd, char *mode) { + int p[2]; + pid_t *poptr; + int myside, yourside; + pid_t pid; + + if(pipe(p) < 0) return (NULL); + myside = tst(p[WTR], p[RDR]); + yourside = tst(p[RDR], p[WTR]); + if((pid = fork()) == 0) { + /* myside and yourside reverse roles in child */ + int stdio; + + /* close all pipes from other popen's */ + for(poptr = popen_pid; poptr < popen_pid + 20; poptr++) { + if(*poptr) (void)close(poptr - popen_pid); + } + stdio = tst(0, 1); + close(myside); + close(stdio); + fcntl(yourside, F_DUPFD, stdio); + close(yourside); + execlp(shell, basename(shell), "-c", cmd, (void *)0); + _exit(1); + } else if(pid > 0) + tstat = signal(SIGTSTP, SIG_DFL); + if(pid == -1) return (NULL); + popen_pid[myside] = pid; + (void)close(yourside); + return (fdopen(myside, mode)); } /* HBB 20010705: renamed from 'pclose', which would collide with * system-supplied function of same name */ -int -mypclose(FILE *ptr) -{ - int f; - pid_t r; - int status = -1; - sighandler_t hstat, istat, qstat; - - f = fileno(ptr); - (void) fclose(ptr); - istat = signal(SIGINT, SIG_IGN); - qstat = signal(SIGQUIT, SIG_IGN); - hstat = signal(SIGHUP, SIG_IGN); - while((r = wait(&status)) != popen_pid[f] && r != -1) - ; /* nothing */ - if(r == -1) - status = -1; - (void) signal(SIGINT, istat); - (void) signal(SIGQUIT, qstat); - (void) signal(SIGHUP, hstat); - (void) signal(SIGTSTP, tstat); - /* mark this pipe closed */ - popen_pid[f] = 0; - return(status); +int mypclose(FILE *ptr) { + int f; + pid_t r; + int status = -1; + sighandler_t hstat, istat, qstat; + + f = fileno(ptr); + (void)fclose(ptr); + istat = signal(SIGINT, SIG_IGN); + qstat = signal(SIGQUIT, SIG_IGN); + hstat = signal(SIGHUP, SIG_IGN); + while((r = wait(&status)) != popen_pid[f] && r != -1) + ; /* nothing */ + if(r == -1) status = -1; + (void)signal(SIGINT, istat); + (void)signal(SIGQUIT, qstat); + (void)signal(SIGHUP, hstat); + (void)signal(SIGTSTP, tstat); + /* mark this pipe closed */ + popen_pid[f] = 0; + return (status); } diff --git a/src/opt.c b/src/opt.c index edb4874..28c2714 100644 --- a/src/opt.c +++ b/src/opt.c @@ -2,157 +2,159 @@ #include "build.h" #include "vp.h" -#include "version.h" /* FILEVERSION and FIXVERSION */ +#include "version.h" /* FILEVERSION and FIXVERSION */ -#include /* atoi */ +#include /* atoi */ #include -bool remove_symfile_onexit = false; -bool onesearch; /* one search only in line mode */ -char *reflines; /* symbol reference lines file */ +bool remove_symfile_onexit = false; +bool onesearch; /* one search only in line mode */ +char *reflines; /* symbol reference lines file */ -char ** parse_options(int *argc, char **argv) -{ - int opt; - int longind; - char path[PATHLEN + 1]; /* file path */ - char *s; - int argcc = *argc; +char **parse_options(int *argc, char **argv) { + int opt; + int longind; + char path[PATHLEN + 1]; /* file path */ + char *s; + int argcc = *argc; - struct option lopts[] = { - {"help", 0, NULL, 'h'}, - {"version", 0, NULL, 'V'}, - {0, 0, 0, 0} - }; + struct option lopts[] = { + {"help", 0, NULL, 'h'}, + {"version", 0, NULL, 'V'}, + {0, 0, 0, 0 } + }; - while ((opt = getopt_long(argcc, argv, - "hVbcCdeF:f:I:i:kLl0:1:2:3:4:5:6:7:8:9:P:p:qRs:TUuvX", - lopts, &longind)) != -1) { - switch(opt) { + while((opt = getopt_long(argcc, + argv, + "hVbcCdeF:f:I:i:kLl0:1:2:3:4:5:6:7:8:9:P:p:qRs:TUuvX", + lopts, + &longind)) != -1) { + switch(opt) { - case '?': - usage(); - myexit(1); - break; - case 'X': - remove_symfile_onexit = true; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - /* The input fields numbers for line mode operation */ - field = opt - '0'; - if (strlen(optarg) > PATHLEN) { - postfatal("\ + case '?': + usage(); + myexit(1); + break; + case 'X': + remove_symfile_onexit = true; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + /* The input fields numbers for line mode operation */ + field = opt - '0'; + if(strlen(optarg) > PATHLEN) { + postfatal("\ cscope: pattern too long, cannot be > \ - %d characters\n", PATLEN); - } - strcpy(input_line, optarg); - break; - case 'b': /* only build the cross-reference */ - buildonly = true; - linemode = true; - break; - case 'c': /* ASCII characters only in crossref */ - compress = false; - break; - case 'C': /* turn on caseless mode for symbol searches */ - caseless = true; - egrepcaseless(caseless); /* simulate egrep -i flag */ - break; - case 'd': /* consider crossref up-to-date */ - isuptodate = true; - break; - case 'e': /* suppress ^E prompt between files */ - editallprompt = false; - break; - case 'h': - longusage(); - myexit(1); - break; - case 'k': /* ignore DFLT_INCDIR */ - kernelmode = true; - break; - case 'L': - onesearch = true; - /* FALLTHROUGH */ - case 'l': - linemode = true; - break; - case 'v': - verbosemode = true; - break; - case 'V': - fprintf(stderr, PROGRAM_NAME ": version %d%s\n", - FILEVERSION, FIXVERSION); - myexit(0); - break; - case 'q': /* quick search */ - invertedindex = true; - break; - case 'T': /* truncate symbols to 8 characters */ - trun_syms = true; - break; - case 'u': /* unconditionally build the cross-reference */ - unconditional = true; - break; - case 'U': /* assume some files have changed */ - fileschanged = true; - break; - case 'R': - recurse_dir = true; - break; - case 'f': /* alternate cross-reference file */ - reffile = optarg; - if (strlen(reffile) > sizeof(path) - 3) { - postfatal("\ + %d characters\n", + PATLEN); + } + strcpy(input_line, optarg); + break; + case 'b': /* only build the cross-reference */ + buildonly = true; + linemode = true; + break; + case 'c': /* ASCII characters only in crossref */ + compress = false; + break; + case 'C': /* turn on caseless mode for symbol searches */ + caseless = true; + egrepcaseless(caseless); /* simulate egrep -i flag */ + break; + case 'd': /* consider crossref up-to-date */ + isuptodate = true; + break; + case 'e': /* suppress ^E prompt between files */ + editallprompt = false; + break; + case 'h': + longusage(); + myexit(1); + break; + case 'k': /* ignore DFLT_INCDIR */ + kernelmode = true; + break; + case 'L': + onesearch = true; + /* FALLTHROUGH */ + case 'l': + linemode = true; + break; + case 'v': + verbosemode = true; + break; + case 'V': + fprintf(stderr, PROGRAM_NAME ": version %d%s\n", FILEVERSION, FIXVERSION); + myexit(0); + break; + case 'q': /* quick search */ + invertedindex = true; + break; + case 'T': /* truncate symbols to 8 characters */ + trun_syms = true; + break; + case 'u': /* unconditionally build the cross-reference */ + unconditional = true; + break; + case 'U': /* assume some files have changed */ + fileschanged = true; + break; + case 'R': + recurse_dir = true; + break; + case 'f': /* alternate cross-reference file */ + reffile = optarg; + if(strlen(reffile) > sizeof(path) - 3) { + postfatal("\ cscope: reffile too long, cannot \ - be > %d characters\n", sizeof(path) - 3); - /* NOTREACHED */ - } - strcpy(path, reffile); + be > %d characters\n", + sizeof(path) - 3); + /* NOTREACHED */ + } + strcpy(path, reffile); - s = path + strlen(path); - strcpy(s, ".in"); - /*coverity[overwrite_var]*/ - invname = strdup(path); - strcpy(s, ".po"); - /*coverity[overwrite_var]*/ - invpost = strdup(path); - break; + s = path + strlen(path); + strcpy(s, ".in"); + /*coverity[overwrite_var]*/ + invname = strdup(path); + strcpy(s, ".po"); + /*coverity[overwrite_var]*/ + invpost = strdup(path); + break; - case 'F': /* symbol reference lines file */ - reflines = optarg; - break; - case 'i': /* file containing file names */ - namefile = optarg; - break; - case 'I': /* #include file directory */ - includedir(optarg); - break; - case 'p': /* file path components to display */ - dispcomponents = atoi(optarg); - break; - case 'P': /* prepend path to file names */ - prependpath = optarg; - break; - case 's': /* additional source file directory */ - sourcedir(optarg); - break; - } - } - /* - * This adjusts argv so that we only see the remaining - * args. Its ugly, but we need to do it so that the rest - * of the main routine doesn't get all confused - */ - *argc = *argc - optind; - return argv + optind; + case 'F': /* symbol reference lines file */ + reflines = optarg; + break; + case 'i': /* file containing file names */ + namefile = optarg; + break; + case 'I': /* #include file directory */ + includedir(optarg); + break; + case 'p': /* file path components to display */ + dispcomponents = atoi(optarg); + break; + case 'P': /* prepend path to file names */ + prependpath = optarg; + break; + case 's': /* additional source file directory */ + sourcedir(optarg); + break; + } + } + /* + * This adjusts argv so that we only see the remaining + * args. Its ugly, but we need to do it so that the rest + * of the main routine doesn't get all confused + */ + *argc = *argc - optind; + return argv + optind; } diff --git a/src/path.c b/src/path.c index 013768c..0d52813 100644 --- a/src/path.c +++ b/src/path.c @@ -34,37 +34,28 @@ #include "global.h" -const char * -basename(const char *path) -{ - const char *s; +const char *basename(const char *path) { + const char *s; - if ((s = strrchr(path, '/')) != 0) { - return(s + 1); - } - return(path); + if((s = strrchr(path, '/')) != 0) { return (s + 1); } + return (path); } /* get the requested path components */ -char * -pathcomponents(char *path, int components) -{ - int i; - char *s; - - s = path + strlen(path) - 1; - for (i = 0; i < components; ++i) { - while (s > path && *--s != '/') { - ; - } - } - if (s > path && *s == '/') { - ++s; - } - return(s); +char *pathcomponents(char *path, int components) { + int i; + char *s; + + s = path + strlen(path) - 1; + for(i = 0; i < components; ++i) { + while(s > path && *--s != '/') { + ; + } + } + if(s > path && *s == '/') { ++s; } + return (s); } - /* * compath(pathname) * @@ -79,162 +70,150 @@ pathcomponents(char *path, int components) * and stored in global structures. */ -char * -compath(char *pathname) /*FDEF*/ +char *compath(char *pathname) /*FDEF*/ { - char *nextchar; - char *lastchar; - char *sofar; - char *pnend; - - int pnlen; - - /* - * do not change the path if it has no "/" - */ - - if (strchr(pathname, '/') == NULL) - return(pathname); - - /* - * find all strings consisting of more than one '/' - */ - - for (lastchar = pathname + 1; *lastchar != '\0'; lastchar++) - if ((*lastchar == '/') && (*(lastchar - 1) == '/')) - { - - /* - * find the character after the last slash - */ - - nextchar = lastchar; - while (*++lastchar == '/') - { - } - - /* - * eliminate the extra slashes by copying - * everything after the slashes over the slashes - */ - - sofar = nextchar; - while ((*nextchar++ = *lastchar++) != '\0') - ; - lastchar = sofar; - } - - /* - * find all strings of "./" - */ - - for (lastchar = pathname + 1; *lastchar != '\0'; lastchar++) - if ((*lastchar == '/') && (*(lastchar - 1) == '.') && - ((lastchar - 1 == pathname) || (*(lastchar - 2) == '/'))) - { - - /* - * copy everything after the "./" over the "./" - */ - - nextchar = lastchar - 1; - sofar = nextchar; - while ((*nextchar++ = *++lastchar) != '\0') - ; - lastchar = sofar; - } - - /* - * find each occurrence of "/.." - */ - - for (lastchar = pathname + 1; *lastchar != '\0'; lastchar++) - if ((lastchar != pathname) && (*lastchar == '/') && - (*(lastchar + 1) == '.') && (*(lastchar + 2) == '.') && - ((*(lastchar + 3) == '/') || (*(lastchar + 3) == '\0'))) - { - - /* - * find the directory name preceding the "/.." - */ - - nextchar = lastchar - 1; - while ((nextchar != pathname) && - (*(nextchar - 1) != '/')) - --nextchar; - - /* - * make sure the preceding directory's name - * is not "." or ".." - */ - - if ((*nextchar == '.') && - ((*(nextchar + 1) == '/') || - ((*(nextchar + 1) == '.') && (*(nextchar + 2) == '/')))) - /* EMPTY */; - else - { - - /* - * prepare to eliminate either - * "dir_name/../" or "dir_name/.." - */ - - if (*(lastchar + 3) == '/') - lastchar += 4; - else - lastchar += 3; - - /* - * copy everything after the "/.." to - * before the preceding directory name - */ - - sofar = nextchar - 1; - while ((*nextchar++ = *lastchar++) != '\0'); - - lastchar = sofar; - - /* - * if the character before what was taken - * out is '/', set up to check if the - * slash is part of "/.." - */ - - if ((sofar + 1 != pathname) && (*sofar == '/')) - --lastchar; - } - } - - /* - * if the string is more than a character long and ends - * in '/', eliminate the '/'. - */ - - pnlen = strlen(pathname); - pnend = strchr(pathname, '\0') - 1; - - if ((pnlen > 1) && (*pnend == '/')) - { - *pnend-- = '\0'; - pnlen--; - } - - /* - * if the string has more than two characters and ends in - * "/.", remove the "/.". - */ - - if ((pnlen > 2) && (*(pnend - 1) == '/') && (*pnend == '.')) - *--pnend = '\0'; - - /* - * if all characters were deleted, return "."; - * otherwise return pathname - */ - - if (*pathname == '\0') - (void) strcpy(pathname, "."); - - return(pathname); + char *nextchar; + char *lastchar; + char *sofar; + char *pnend; + + int pnlen; + + /* + * do not change the path if it has no "/" + */ + + if(strchr(pathname, '/') == NULL) return (pathname); + + /* + * find all strings consisting of more than one '/' + */ + + for(lastchar = pathname + 1; *lastchar != '\0'; lastchar++) + if((*lastchar == '/') && (*(lastchar - 1) == '/')) { + + /* + * find the character after the last slash + */ + + nextchar = lastchar; + while(*++lastchar == '/') { } + + /* + * eliminate the extra slashes by copying + * everything after the slashes over the slashes + */ + + sofar = nextchar; + while((*nextchar++ = *lastchar++) != '\0') + ; + lastchar = sofar; + } + + /* + * find all strings of "./" + */ + + for(lastchar = pathname + 1; *lastchar != '\0'; lastchar++) + if((*lastchar == '/') && (*(lastchar - 1) == '.') && + ((lastchar - 1 == pathname) || (*(lastchar - 2) == '/'))) { + + /* + * copy everything after the "./" over the "./" + */ + + nextchar = lastchar - 1; + sofar = nextchar; + while((*nextchar++ = *++lastchar) != '\0') + ; + lastchar = sofar; + } + + /* + * find each occurrence of "/.." + */ + + for(lastchar = pathname + 1; *lastchar != '\0'; lastchar++) + if((lastchar != pathname) && (*lastchar == '/') && (*(lastchar + 1) == '.') && + (*(lastchar + 2) == '.') && + ((*(lastchar + 3) == '/') || (*(lastchar + 3) == '\0'))) { + + /* + * find the directory name preceding the "/.." + */ + + nextchar = lastchar - 1; + while((nextchar != pathname) && (*(nextchar - 1) != '/')) + --nextchar; + + /* + * make sure the preceding directory's name + * is not "." or ".." + */ + + if((*nextchar == '.') && + ((*(nextchar + 1) == '/') || + ((*(nextchar + 1) == '.') && (*(nextchar + 2) == '/')))) + /* EMPTY */; + else { + + /* + * prepare to eliminate either + * "dir_name/../" or "dir_name/.." + */ + + if(*(lastchar + 3) == '/') + lastchar += 4; + else + lastchar += 3; + + /* + * copy everything after the "/.." to + * before the preceding directory name + */ + + sofar = nextchar - 1; + while((*nextchar++ = *lastchar++) != '\0') + ; + + lastchar = sofar; + + /* + * if the character before what was taken + * out is '/', set up to check if the + * slash is part of "/.." + */ + + if((sofar + 1 != pathname) && (*sofar == '/')) --lastchar; + } + } + + /* + * if the string is more than a character long and ends + * in '/', eliminate the '/'. + */ + + pnlen = strlen(pathname); + pnend = strchr(pathname, '\0') - 1; + + if((pnlen > 1) && (*pnend == '/')) { + *pnend-- = '\0'; + pnlen--; + } + + /* + * if the string has more than two characters and ends in + * "/.", remove the "/.". + */ + + if((pnlen > 2) && (*(pnend - 1) == '/') && (*pnend == '.')) *--pnend = '\0'; + + /* + * if all characters were deleted, return "."; + * otherwise return pathname + */ + + if(*pathname == '\0') (void)strcpy(pathname, "."); + + return (pathname); } diff --git a/src/readline.c b/src/readline.c index d8c6a0d..cbd47dd 100644 --- a/src/readline.c +++ b/src/readline.c @@ -4,121 +4,122 @@ #include "build.h" #include -static int input_available = 0; +static int input_available = 0; static char input_char; -char input_line[PATLEN + 1]; +char input_line[PATLEN + 1]; -bool interpret(int c){ - input_char = c; - input_available = 1; - rl_callback_read_char(); +bool interpret(int c) { + input_char = c; + input_available = 1; + rl_callback_read_char(); - return 0; + return 0; } -static int getc_function(FILE* ignore){ +static int getc_function(FILE *ignore) { UNUSED(ignore); - input_available = 0; - return (int)input_char; + input_available = 0; + return (int)input_char; } -static int input_available_hook(){ - return input_available; +static int input_available_hook() { + return input_available; } -static void redisplay_function(){ - window_change |= CH_INPUT; +static void redisplay_function() { + window_change |= CH_INPUT; } -static void callback_handler(char* line){ - if(!line){ return; } +static void callback_handler(char *line) { + if(!line) { return; } - switch(input_mode){ + switch(input_mode) { case INPUT_NORMAL: - strncpy(input_line, line, PATLEN); + strncpy(input_line, line, PATLEN); search(input_line); curdispline = 0; PCS_reset(); current_page = 0; break; case INPUT_CHANGE_TO: - strncpy(newpat, line, PATLEN); - change = calloc(totallines, sizeof(*change)); + strncpy(newpat, line, PATLEN); + change = calloc(totallines, sizeof(*change)); input_mode = INPUT_CHANGE; horswp_field(); return; } - switch(field){ + switch(field) { case CHANGE: input_mode = INPUT_CHANGE_TO; break; case DEFINITION: case FILENAME: - if(totallines == 1){ editref(0); } + if(totallines == 1) { editref(0); } break; } } -static int ctrl_z(){ - kill(0, SIGTSTP); +static int ctrl_z() { + kill(0, SIGTSTP); return 0; } -static int toggle_caseless(){ - if (caseless == false) { - caseless = true; - postmsg2("Caseless mode is now ON"); - } else { - caseless = false; - postmsg2("Caseless mode is now OFF"); - } - egrepcaseless(caseless); /* turn on/off -i flag */ +static int toggle_caseless() { + if(caseless == false) { + caseless = true; + postmsg2("Caseless mode is now ON"); + } else { + caseless = false; + postmsg2("Caseless mode is now OFF"); + } + egrepcaseless(caseless); /* turn on/off -i flag */ return 0; } -static int rebuild_reference(){ - if (isuptodate == true) { - postmsg("The -d option prevents rebuilding the symbol database"); - return(false); - } - exitcurses(); - freefilelist(); /* remake the source file list */ - makefilelist(); - rebuild(); - if (errorsfound == true) { - errorsfound = false; - askforreturn(); - } - entercurses(); - postmsg(""); /* clear any previous message */ - totallines = 0; - disprefs = 0; - return(true); +static int rebuild_reference() { + if(isuptodate == true) { + postmsg("The -d option prevents rebuilding the symbol database"); + return (false); + } + exitcurses(); + freefilelist(); /* remake the source file list */ + makefilelist(); + rebuild(); + if(errorsfound == true) { + errorsfound = false; + askforreturn(); + } + entercurses(); + postmsg(""); /* clear any previous message */ + totallines = 0; + disprefs = 0; + return (true); } -void rlinit(){ - rl_catch_signals = 0; - rl_catch_sigwinch = 0; - rl_prep_term_function = NULL; - rl_deprep_term_function = NULL; - rl_change_environment = 0; - - rl_getc_function = getc_function; - rl_input_available_hook = input_available_hook; - rl_redisplay_function = redisplay_function; - rl_callback_handler_install("", callback_handler); - - rl_bind_key(7, rl_rubout); // XXX: 7 is backspace for some reason (on my system anyways?) - rl_bind_key(KEY_BACKSPACE, rl_rubout); - - rl_bind_key(EOF, myexit); - rl_bind_key(ctrl('Z'), ctrl_z); - rl_bind_key(ctrl('Z'), toggle_caseless); - rl_bind_key(ctrl('R'), rebuild_reference); - rl_bind_key(ESC, process_mouse); /* possible unixpc mouse selection */ - rl_bind_key(ctrl('X'), process_mouse); /* mouse selection */ - - //rl_bind_key(ctrl('\\'), /**/); /* bypass bindings */ +void rlinit() { + rl_catch_signals = 0; + rl_catch_sigwinch = 0; + rl_prep_term_function = NULL; + rl_deprep_term_function = NULL; + rl_change_environment = 0; + + rl_getc_function = getc_function; + rl_input_available_hook = input_available_hook; + rl_redisplay_function = redisplay_function; + rl_callback_handler_install("", callback_handler); + + rl_bind_key(7, + rl_rubout); // XXX: 7 is backspace for some reason (on my system anyways?) + rl_bind_key(KEY_BACKSPACE, rl_rubout); + + rl_bind_key(EOF, myexit); + rl_bind_key(ctrl('Z'), ctrl_z); + rl_bind_key(ctrl('Z'), toggle_caseless); + rl_bind_key(ctrl('R'), rebuild_reference); + rl_bind_key(ESC, process_mouse); /* possible unixpc mouse selection */ + rl_bind_key(ctrl('X'), process_mouse); /* mouse selection */ + + // rl_bind_key(ctrl('\\'), /**/); /* bypass bindings */ } diff --git a/src/refsfound.c b/src/refsfound.c index f2dd2c1..4aab52f 100644 --- a/src/refsfound.c +++ b/src/refsfound.c @@ -4,15 +4,15 @@ struct FILE; /* Page cursor stack */ -static FILE** hto_page = &refsfound; +static FILE **hto_page = &refsfound; #define PCS_MAXPAGE 16 static size_t PCS_pos[PCS_MAXPAGE] = {0}; -static size_t PCS_top = 0; +static size_t PCS_top = 0; -long seekpage(const size_t i){ - if(i > PCS_MAXPAGE-1){ return -1; } +long seekpage(const size_t i) { + if(i > PCS_MAXPAGE - 1) { return -1; } - if(i < PCS_top){ + if(i < PCS_top) { fseek(*hto_page, PCS_pos[i], SEEK_SET); return PCS_pos[i]; } @@ -20,62 +20,59 @@ long seekpage(const size_t i){ fseek(*hto_page, PCS_pos[PCS_top], SEEK_SET); size_t lc = 0; - while(PCS_top < i){ + while(PCS_top < i) { const char c = getc(*hto_page); - if(c == '\n'){ ++lc; } - if(c == EOF){ return -1; } - if(lc == mdisprefs){ - PCS_pos[++PCS_top] = ftell(*hto_page); - } + if(c == '\n') { ++lc; } + if(c == EOF) { return -1; } + if(lc == mdisprefs) { PCS_pos[++PCS_top] = ftell(*hto_page); } } return PCS_pos[PCS_top]; } -long seekrelline(unsigned i){ +long seekrelline(unsigned i) { seekpage(current_page); size_t lc = 0; - while(lc < i){ + while(lc < i) { const char c = getc(*hto_page); assert("seekrelline() tried to read past the reference file" && !(c == EOF)); - if(c == '\n'){ ++lc; } + if(c == '\n') { ++lc; } } return ftell(*hto_page); } -void PCS_reset(void){ +void PCS_reset(void) { PCS_top = 0; } ///* position references found file at specified line */ -//void -//seekline(unsigned int line) +// void +// seekline(unsigned int line) //{ -// /* verify that there is a references found file */ -// if (refsfound == NULL) { -// return; -// } -// /* go to the beginning of the file */ -// rewind(refsfound); +// /* verify that there is a references found file */ +// if (refsfound == NULL) { +// return; +// } +// /* go to the beginning of the file */ +// rewind(refsfound); // /**/ // seekrelline(line); -//} +// } // ///* XXX: this is just dodging the problem */ -//void -//seekrelline(unsigned int line){ -// int c; +// void +// seekrelline(unsigned int line){ +// int c; // -// /* verify that there is a references found file */ -// if (refsfound == NULL) { -// return; -// } +// /* verify that there is a references found file */ +// if (refsfound == NULL) { +// return; +// } // -// /* find the requested line */ -// nextline = 1; -// while (nextline < line && (c = getc(refsfound)) != EOF) { -// if (c == '\n') { -// nextline++; -// } -// } -//} - +// /* find the requested line */ +// nextline = 1; +// while (nextline < line && (c = getc(refsfound)) != EOF) { +// if (c == '\n') { +// nextline++; +// } +// } +// } diff --git a/src/scanner.h b/src/scanner.h index 19cabe6..655aa3f 100644 --- a/src/scanner.h +++ b/src/scanner.h @@ -35,60 +35,60 @@ #include -#undef YYLMAX -#define YYLMAX STMTMAX + PATLEN + 1 /* scanner line buffer size */ +#undef YYLMAX +#define YYLMAX STMTMAX + PATLEN + 1 /* scanner line buffer size */ /* cross-reference database mark characters (when new ones are added, * update the cscope.out format description in cscope.1) */ -#define CLASSDEF 'c' -#define DEFINE '#' -#define DEFINEEND ')' -#define ENUMDEF 'e' -#define FCNCALL '`' -#define FCNDEF '$' -#define FCNEND '}' -#define GLOBALDEF 'g' -#define INCLUDE '~' -#define MEMBERDEF 'm' -#define NEWFILE '@' -#define STRUCTDEF 's' -#define TYPEDEF 't' -#define UNIONDEF 'u' +#define CLASSDEF 'c' +#define DEFINE '#' +#define DEFINEEND ')' +#define ENUMDEF 'e' +#define FCNCALL '`' +#define FCNDEF '$' +#define FCNEND '}' +#define GLOBALDEF 'g' +#define INCLUDE '~' +#define MEMBERDEF 'm' +#define NEWFILE '@' +#define STRUCTDEF 's' +#define TYPEDEF 't' +#define UNIONDEF 'u' /* other scanner token types */ -#define LEXEOF 0 -#define LEXERR 1 -#define IDENT 2 -#define NEWLINE 3 +#define LEXEOF 0 +#define LEXERR 1 +#define IDENT 2 +#define NEWLINE 3 /* scanner.l global data */ -extern int first; /* buffer index for first char of symbol */ -extern int last; /* buffer index for last char of symbol */ -extern int lineno; /* symbol line number */ -extern FILE *yyin; /* input file descriptor */ -extern FILE *yyout; /* output file */ -extern int myylineno; /* input line number */ +extern int first; /* buffer index for first char of symbol */ +extern int last; /* buffer index for last char of symbol */ +extern int lineno; /* symbol line number */ +extern FILE *yyin; /* input file descriptor */ +extern FILE *yyout; /* output file */ +extern int myylineno; /* input line number */ #ifdef USING_LEX /* HBB 20010430: if lex is used instead of flex, have to simulate the * private copies of yytext and yytext for the world outside scanner.l: */ /* FIXME: there should be a feature test for this! */ -#if defined(__OSF1__) || defined(__sun) || defined(_AIX) -extern char yytext[]; -#else -extern unsigned char yytext[]; -#endif -extern int yyleng; +# if defined(__OSF1__) || defined(__sun) || defined(_AIX) +extern char yytext[]; +# else +extern unsigned char yytext[]; +# endif +extern int yyleng; # define my_yytext yytext # define my_yyleng yyleng #else -extern char *my_yytext; /* private copy of input line */ -extern size_t my_yyleng; /* ... and current length of it */ +extern char *my_yytext; /* private copy of input line */ +extern size_t my_yyleng; /* ... and current length of it */ #endif /* The master function exported by scanner.l */ -int yylex(void); -void initscanner(char *srcfile); +int yylex(void); +void initscanner(char *srcfile); #endif /* CSCOPE_SCANNER_H ends */ diff --git a/src/version.h b/src/version.h index 98d8285..72c89bd 100644 --- a/src/version.h +++ b/src/version.h @@ -39,7 +39,7 @@ #ifndef CSCOPE_VERSION_H #define CSCOPE_VERSION_H -#define FILEVERSION 15 /* Initial Open Source and Linux Port */ -#define FIXVERSION ".9" /* feature and bug fix version */ +#define FILEVERSION 15 /* Initial Open Source and Linux Port */ +#define FIXVERSION ".9" /* feature and bug fix version */ -#endif /* CSCOPE_VERSION_H */ +#endif /* CSCOPE_VERSION_H */ diff --git a/src/vp.h b/src/vp.h index f9fd5b8..f5d0d2a 100644 --- a/src/vp.h +++ b/src/vp.h @@ -40,31 +40,31 @@ #ifndef CSCOPE_VP_H #define CSCOPE_VP_H -#define MAXPATH 200 /* max length for entire name */ +#define MAXPATH 200 /* max length for entire name */ #ifdef HAVE_CONFIG_H # include "config.h" #else -# define HAVE_FCNTL_H 1 /* in case of doubt, assume it's there */ +# define HAVE_FCNTL_H 1 /* in case of doubt, assume it's there */ #endif #ifdef HAVE_FCNTL_H -# include /* needed for O_... open flags */ +# include /* needed for O_... open flags */ #endif #include #include #if !falseMALLOC -extern char **vpdirs; /* directories (including current) in view path */ +extern char **vpdirs; /* directories (including current) in view path */ #else -#define MAXDIR 25 /* same as libVP */ -#define DIRLEN 80 /* same as libVP */ -extern char vpdirs[MAXDIR][DIRLEN + 1]; +# define MAXDIR 25 /* same as libVP */ +# define DIRLEN 80 /* same as libVP */ +extern char vpdirs[MAXDIR][DIRLEN + 1]; #endif -extern int vpndirs; /* number of directories in view path */ +extern int vpndirs; /* number of directories in view path */ -void vpinit(char *current_dir); -int vpopen(char *path, int oflag); -int vpaccess(char *path, mode_t amode); +void vpinit(char *current_dir); +int vpopen(char *path, int oflag); +int vpaccess(char *path, mode_t amode); #endif /* CSCOPE_VP_H */ diff --git a/src/vpaccess.c b/src/vpaccess.c index 2ce4748..55e33d2 100644 --- a/src/vpaccess.c +++ b/src/vpaccess.c @@ -37,21 +37,17 @@ #include "vp.h" #include -int -vpaccess(char *path, mode_t amode) -{ - char buf[MAXPATH + 1]; - int returncode; - int i; - - if ((returncode = access(path, amode)) == -1 && path[0] != '/') { - vpinit(NULL); - for (i = 1; i < vpndirs; i++) { - (void) snprintf(buf, sizeof(buf), "%s/%s", vpdirs[i], path); - if ((returncode = access(buf, amode)) != -1) { - break; - } - } - } - return(returncode); +int vpaccess(char *path, mode_t amode) { + char buf[MAXPATH + 1]; + int returncode; + int i; + + if((returncode = access(path, amode)) == -1 && path[0] != '/') { + vpinit(NULL); + for(i = 1; i < vpndirs; i++) { + (void)snprintf(buf, sizeof(buf), "%s/%s", vpdirs[i], path); + if((returncode = access(buf, amode)) != -1) { break; } + } + } + return (returncode); } diff --git a/src/vpfopen.c b/src/vpfopen.c index 829adf6..fbc1966 100644 --- a/src/vpfopen.c +++ b/src/vpfopen.c @@ -37,26 +37,20 @@ #include "vp.h" #include "global.h" -FILE * -vpfopen(char *filename, char *type) -{ - char buf[MAXPATH + 1]; - FILE *returncode; - int i; - - if ((returncode = myfopen(filename, type)) == NULL - && filename[0] != '/' - /* && strcmp(type, "r") == 0 */ /* HBB: this breaks if type=="rb" */ - && type[0] == 'r' - ) { - vpinit(NULL); - for (i = 1; i < vpndirs; i++) { - (void) snprintf(buf, sizeof(buf), "%s/%s", vpdirs[i], filename); - if ((returncode = myfopen(buf, type)) != NULL) { - break; - } - - } - } - return(returncode); +FILE *vpfopen(char *filename, char *type) { + char buf[MAXPATH + 1]; + FILE *returncode; + int i; + + if((returncode = myfopen(filename, type)) == NULL && + filename[0] != '/' + /* && strcmp(type, "r") == 0 */ /* HBB: this breaks if type=="rb" */ + && type[0] == 'r') { + vpinit(NULL); + for(i = 1; i < vpndirs; i++) { + (void)snprintf(buf, sizeof(buf), "%s/%s", vpdirs[i], filename); + if((returncode = myfopen(buf, type)) != NULL) { break; } + } + } + return (returncode); } diff --git a/src/vpinit.c b/src/vpinit.c index 35fd910..5a27034 100644 --- a/src/vpinit.c +++ b/src/vpinit.c @@ -32,7 +32,7 @@ /* vpinit - initialize vpdirs or update vpdirs based on currentdir */ -#include /* stderr */ +#include /* stderr */ #include #include #include @@ -43,127 +43,119 @@ #include "constants.h" #if !falseMALLOC -char **vpdirs; /* directories (including current) in view path */ +char **vpdirs; /* directories (including current) in view path */ #else -char vpdirs[MAXDIR][DIRLEN + 1]; -#define MAXVPATH (MAXDIR * (DIRLEN + 1)) +char vpdirs[MAXDIR][DIRLEN + 1]; +# define MAXVPATH (MAXDIR * (DIRLEN + 1)) #endif -int vpndirs; /* number of directories in view path */ - -void -vpinit(char *current_dir) -{ - char *suffix; /* path from view path node */ - char *vpath; /* VPATH environment variable value */ - char buf[MAXPATH + 1]; - int i; - char *s; +int vpndirs; /* number of directories in view path */ + +void vpinit(char *current_dir) { + char *suffix; /* path from view path node */ + char *vpath; /* VPATH environment variable value */ + char buf[MAXPATH + 1]; + int i; + char *s; #if falseMALLOC - char *node; /* view path node */ - char vpathbuf[MAXVPATH + 1]; + char *node; /* view path node */ + char vpathbuf[MAXVPATH + 1]; #endif - /* if an existing directory list is to be updated, free it */ - if (current_dir != NULL && vpndirs > 0) { + /* if an existing directory list is to be updated, free it */ + if(current_dir != NULL && vpndirs > 0) { #if !falseMALLOC - for (i = 0; i < vpndirs; ++i) { - free(vpdirs[i]); - } - free(vpdirs); + for(i = 0; i < vpndirs; ++i) { + free(vpdirs[i]); + } + free(vpdirs); #endif - vpndirs = 0; - } - /* return if the directory list has been computed */ - /* or there isn't a view path environment variable */ - if (vpndirs > 0 || (vpath = getenv("VPATH")) == NULL || - *vpath == '\0') { - return; - } - /* if not given, get the current directory name */ - if (current_dir == NULL && (current_dir = getcwd(buf, MAXPATH)) == NULL) { - fprintf(stderr, PROGRAM_NAME ": cannot get current directory name\n"); - return; - } - /* see if this directory is in the first view path node */ - for (i = 0; vpath[i] == current_dir[i] && vpath[i] != '\0'; ++i) { - ; - } - if ((vpath[i] != ':' && vpath[i] != '\0') || - (current_dir[i] != '/' && current_dir[i] != '\0')) { - return; - } - suffix = ¤t_dir[i]; + vpndirs = 0; + } + /* return if the directory list has been computed */ + /* or there isn't a view path environment variable */ + if(vpndirs > 0 || (vpath = getenv("VPATH")) == NULL || *vpath == '\0') { return; } + /* if not given, get the current directory name */ + if(current_dir == NULL && (current_dir = getcwd(buf, MAXPATH)) == NULL) { + fprintf(stderr, PROGRAM_NAME ": cannot get current directory name\n"); + return; + } + /* see if this directory is in the first view path node */ + for(i = 0; vpath[i] == current_dir[i] && vpath[i] != '\0'; ++i) { + ; + } + if((vpath[i] != ':' && vpath[i] != '\0') || + (current_dir[i] != '/' && current_dir[i] != '\0')) { + return; + } + suffix = ¤t_dir[i]; #if !falseMALLOC - /* count the nodes in the view path */ - vpndirs = 1; - for (i = 0; vpath[i] != '\0'; ++i) { - if (vpath[i] == ':' && vpath[i + 1]) { - ++vpndirs; - } - } - /* create the source directory list */ - vpdirs = malloc(vpndirs * sizeof(*vpdirs)); - - /* don't change VPATH in the environment */ - vpath = strdup(vpath); - - /* split the view path into nodes */ - for (i = 0, s = vpath; *s != '\0'; ++i) { - vpdirs[i] = s; - while (*s != '\0' && *++s != ':') { - if (*s == '\n') { - *s = '\0'; - } - } - if (*s != '\0') { - *s++ = '\0'; - } - } - /* convert the view path nodes to directories */ - for (i = 0; i < vpndirs; ++i) { - s = malloc(strlen(vpdirs[i]) + strlen(suffix) + 1); - (void) strcpy(s, vpdirs[i]); - (void) strcat(s, suffix); - vpdirs[i] = s; - } - free(vpath); + /* count the nodes in the view path */ + vpndirs = 1; + for(i = 0; vpath[i] != '\0'; ++i) { + if(vpath[i] == ':' && vpath[i + 1]) { ++vpndirs; } + } + /* create the source directory list */ + vpdirs = malloc(vpndirs * sizeof(*vpdirs)); + + /* don't change VPATH in the environment */ + vpath = strdup(vpath); + + /* split the view path into nodes */ + for(i = 0, s = vpath; *s != '\0'; ++i) { + vpdirs[i] = s; + while(*s != '\0' && *++s != ':') { + if(*s == '\n') { *s = '\0'; } + } + if(*s != '\0') { *s++ = '\0'; } + } + /* convert the view path nodes to directories */ + for(i = 0; i < vpndirs; ++i) { + s = malloc(strlen(vpdirs[i]) + strlen(suffix) + 1); + (void)strcpy(s, vpdirs[i]); + (void)strcat(s, suffix); + vpdirs[i] = s; + } + free(vpath); #else - /* don't change VPATH in the environment */ - if (strlen(vpath) > MAXVPATH) { - (void) fprintf(stderr, "%s: VPATH is longer than %d characters: %s\n", argv0, MAXVPATH, vpath); - return; - } - (void) strcpy(vpathbuf, vpath); - s = vpathbuf; - - /* convert the view path nodes to directories */ - while (*s != '\0') { - - /* get the next node */ - node = s; - while (*s != '\0' && *++s != ':') { - if (*s == '\n') { - *s = '\0'; - } - } - if (*s != '\0') { - *s++ = '\0'; - } - /* ignore a directory that is too long */ - if (strlen(node) + strlen(suffix) > DIRLEN) { - (void) fprintf(stderr, "%s: VPATH directory is longer than %d characters: %s%s\n", argv0, DIRLEN, node, suffix); - } - else if (vpndirs >= MAXDIR) { - (void) fprintf(stderr, "%s: VPATH has more than %d nodes\n", argv0, vpndirs); - return; - } - else { - /* create the view path directory */ - (void) strcpy(vpdirs[vpndirs], node); - (void) strcat(vpdirs[vpndirs], suffix); - ++vpndirs; - } - } + /* don't change VPATH in the environment */ + if(strlen(vpath) > MAXVPATH) { + (void)fprintf(stderr, + "%s: VPATH is longer than %d characters: %s\n", + argv0, + MAXVPATH, + vpath); + return; + } + (void)strcpy(vpathbuf, vpath); + s = vpathbuf; + + /* convert the view path nodes to directories */ + while(*s != '\0') { + + /* get the next node */ + node = s; + while(*s != '\0' && *++s != ':') { + if(*s == '\n') { *s = '\0'; } + } + if(*s != '\0') { *s++ = '\0'; } + /* ignore a directory that is too long */ + if(strlen(node) + strlen(suffix) > DIRLEN) { + (void)fprintf(stderr, + "%s: VPATH directory is longer than %d characters: %s%s\n", + argv0, + DIRLEN, + node, + suffix); + } else if(vpndirs >= MAXDIR) { + (void)fprintf(stderr, "%s: VPATH has more than %d nodes\n", argv0, vpndirs); + return; + } else { + /* create the view path directory */ + (void)strcpy(vpdirs[vpndirs], node); + (void)strcat(vpdirs[vpndirs], suffix); + ++vpndirs; + } + } #endif } diff --git a/src/vpopen.c b/src/vpopen.c index fd61103..63cf042 100644 --- a/src/vpopen.c +++ b/src/vpopen.c @@ -37,24 +37,20 @@ #include "global.h" #include "vp.h" -#define OPENFLAG_READ 0 - -int -vpopen(char *path, int oflag) -{ - char buf[MAXPATH + 1]; - int returncode; - int i; - - if ((returncode = myopen(path, oflag, 0666)) == -1 && path[0] != '/' && - oflag == OPENFLAG_READ) { - vpinit(NULL); - for (i = 1; i < vpndirs; i++) { - (void) snprintf(buf, sizeof(buf), "%s/%s", vpdirs[i], path); - if ((returncode = myopen(buf, oflag, 0666)) != -1) { - break; - } - } - } - return(returncode); +#define OPENFLAG_READ 0 + +int vpopen(char *path, int oflag) { + char buf[MAXPATH + 1]; + int returncode; + int i; + + if((returncode = myopen(path, oflag, 0666)) == -1 && path[0] != '/' && + oflag == OPENFLAG_READ) { + vpinit(NULL); + for(i = 1; i < vpndirs; i++) { + (void)snprintf(buf, sizeof(buf), "%s/%s", vpdirs[i], path); + if((returncode = myopen(buf, oflag, 0666)) != -1) { break; } + } + } + return (returncode); }