EString SieveParser::tag() { whitespace(); require( ":" ); return ":" + identifier(); }
static void fetch_hosts (const char *filename) { FILE *file = fopen (filename, "r"); char buffer[256], *name; char *lc_start; char *bi; if (!file) return; while (fgets (buffer, 255, file) != NULL) { /* Skip to first character. */ for (bi = buffer; bi[0] != '\0' && str_isspace (bi); str_next_char (&bi)); /* Ignore comments... */ if (bi[0] == '#') continue; /* Handle $include. */ if (!strncmp (bi, "$include ", 9)) { char *includefile = bi + 9; char *t; /* Find start of filename. */ while (*includefile && whitespace (*includefile)) includefile++; t = includefile; /* Find end of filename. */ while (t[0] != '\0' && !str_isspace (t)) str_next_char (&t); *t = '\0'; fetch_hosts (includefile); continue; } /* Skip IP #s. */ while (bi[0] != '\0' && !str_isspace (bi)) str_next_char (&bi); /* Get the host names separated by white space. */ while (bi[0] != '\0' && bi[0] != '#') { while (bi[0] != '\0' && str_isspace (bi)) str_next_char (&bi); if (bi[0] == '#') continue; for (lc_start = bi; bi[0] != '\0' && !str_isspace (bi); str_next_char (&bi)); if (bi - lc_start == 0) continue; name = g_strndup (lc_start, bi - lc_start); { char **host_p; if (hosts_p - hosts >= hosts_alloclen) { int j = hosts_p - hosts; hosts = g_realloc ((void *) hosts, ((hosts_alloclen += 30) + 1) * sizeof (char *)); hosts_p = hosts + j; } for (host_p = hosts; host_p < hosts_p; host_p++) if (!strcmp (name, *host_p)) break; /* We do not want any duplicates */ if (host_p == hosts_p) { *(hosts_p++) = name; *hosts_p = NULL; } else g_free (name); } } } fclose (file); }
/** * Enter: * src => English text * return null if errors, else phoneme string */ static void text2Phonemes(const char * src){ // int outIndex = 0;// Current offset into phonemes int inIndex = -1; // Starts at -1 so that a leading space is assumed while(inIndex==-1 || src[inIndex]){ // until end of text int maxMatch=0; // Max chars matched on input text // int numOut=0; // Number of characters copied to output stream for the best match int maxWildcardPos = 0; // Start with first vocab entry const char* vocabEntry = s_vocab; // Keep track of best match so far const char* bestEntry = null; int bestWildCardInPos=0; char bestWildCard=0; boolean bestHasWhiteSpace=FALSE; int wildcardInPos; // Get next phoneme, P2 while(getVocab(vocabEntry,0)){ int y; char wildcard=0; // The wildcard character boolean hasWhiteSpace=FALSE; wildcardInPos=0; // The index in the vocab where it occurs for(y=0;;y++){ char nextCharIn,nextVocabChar; // Get next char from user input // Make next char upper case and remove control characters nextCharIn = (y + inIndex == -1) ? ' ' : src[y + inIndex]; if(nextCharIn>='a' && nextCharIn<='z'){ nextCharIn = nextCharIn - 'a' + 'A'; }else if(nextCharIn<' '){ nextCharIn = ' '; } // Get next text char from vocab nextVocabChar = getVocab(vocabEntry,y); if( (nextVocabChar & 0x80)){ nextVocabChar = 0; } // If its a wildcard then save its value and position if(nextVocabChar=='#' && nextCharIn >= 'A' && nextCharIn <= 'Z'){ wildcard = nextCharIn; // The character equivalent to the '#' wildcardInPos=y; continue; } // Check if vocab is looking for end of word if(nextVocabChar=='_'){ // try to match against a white space hasWhiteSpace=TRUE; if(whitespace(nextCharIn)){ continue; } y--; break; } // check for end of either string if(nextVocabChar==0 || nextCharIn==0){ break; } if(nextVocabChar != nextCharIn){ break; } } // See if its the longest complete match so far if(y > maxMatch && ( getVocab(vocabEntry,y) & 0x80) == 0x80){ // This is the longest complete match maxMatch = y; maxWildcardPos = 0; // Point to the start of the phoneme bestEntry = vocabEntry + y; bestWildCardInPos = wildcardInPos; bestWildCard = wildcard; bestHasWhiteSpace = hasWhiteSpace; } // Move to start of next entry while(getVocab(vocabEntry,y++)); // Move to end of phoneme asciiz vocabEntry += y; }// check next phoneme // 15 - end of vocab table //16 if(bestHasWhiteSpace==TRUE){ maxMatch--; } //17 if(maxMatch==0){ loggerP(PSTR("No token for ")); logger(&src[inIndex]); loggerCRLF(); return; } // Copy data for best match { int y; // Copy the matching phrase changing any '#' to the phoneme for the wildcard for(y=0;;y++){ char c = getVocab(bestEntry,y) & 0x7f; // Get the next phoneme character if(c==0){ y++; // move to start of next vocab entry break; } if(c=='#'){ if(getVocab(bestEntry,y+1)==0){ // replacement ends in wild card maxWildcardPos = bestWildCardInPos; }else{ // Copy the phonemes for the wild card character copyToken(bestWildCard); } }else{ rprintfChar(c); // output the phoneme character } } } inIndex += (maxWildcardPos>0) ? maxWildcardPos : maxMatch; } }
// Clear line of length len at position pos void clear_line_buffer(int len, int pos){ back_up_buffer(pos); whitespace(len); back_up_buffer(len); }
/* * Extract the foreground, background and highlight values from an attribute * represented as a string in one of two forms: * * "(foreground,background,highlight)" " "xxxx_color" */ static int str_to_attr(char *str, int *fg, int *bg, int *hl) { int i = 0, get_fg = 1; unsigned j; char tempstr[MAX_LEN + 1], *part; if (str[0] != '(' || lastch(str) != ')') { if ((i = find_color(str)) >= 0) { *fg = dlg_color_table[i].fg; *bg = dlg_color_table[i].bg; *hl = dlg_color_table[i].hilite; return 0; } return -1; /* invalid representation */ } /* remove the parenthesis */ strcpy(tempstr, str + 1); lastch(tempstr) = '\0'; /* get foreground and background */ while (1) { /* skip white space before fg/bg string */ i = skip_whitespace(tempstr, i); if (tempstr[i] == '\0') return -1; /* invalid representation */ part = tempstr + i; /* set 'part' to start of fg/bg string */ /* find end of fg/bg string */ while (!whitespace(tempstr[i]) && tempstr[i] != ',' && tempstr[i] != '\0') i++; if (tempstr[i] == '\0') return -1; /* invalid representation */ else if (whitespace(tempstr[i])) { /* not yet ',' */ tempstr[i++] = '\0'; /* skip white space before ',' */ i = skip_whitespace(tempstr, i); if (tempstr[i] != ',') return -1; /* invalid representation */ } tempstr[i++] = '\0'; /* skip the ',' */ for (j = 0; j < COLOR_COUNT && dlg_strcmp(part, color_names[j].name); j++) ; if (j == COLOR_COUNT) /* invalid color name */ return -1; if (get_fg) { *fg = color_names[j].value; get_fg = 0; /* next we have to get the background */ } else { *bg = color_names[j].value; break; } } /* got foreground and background */ /* get highlight */ /* skip white space before highlight string */ i = skip_whitespace(tempstr, i); if (tempstr[i] == '\0') return -1; /* invalid representation */ part = tempstr + i; /* set 'part' to start of highlight string */ /* trim trailing white space from highlight string */ i = (int) strlen(part) - 1; while (whitespace(part[i]) && i > 0) i--; part[i + 1] = '\0'; if (!dlg_strcmp(part, "ON")) *hl = TRUE; else if (!dlg_strcmp(part, "OFF")) *hl = FALSE; else return -1; /* invalid highlight value */ return 0; }
QC_Array(QC_Token) qc_tokenize(const char* src, int src_size) { const char *cur; const char *tok_begin; QC_Tokenize_Ctx t = {0}; cur = src; tok_begin = src; t.end = src + src_size; t.cur_line = 1; t.tokens = qc_create_array(QC_Token)(src_size/4); /* Estimate token count */ while (cur <= t.end && tok_begin < t.end) { char ch = cur < t.end ? *cur : '\n'; switch (t.state) { case Tok_State_none: if (single_char_tokentype(ch) != QC_Token_unknown) { t.state = Tok_State_maybe_single_char; } else if (ch >= '0' && ch <= '9') { t.state = Tok_State_number; } else if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '_')) { t.state = Tok_State_name; } else if (ch == '\"' || ch == '@') { /* @todo Remove temp hack of @ */ t.string_begin_char = ch; t.state = Tok_State_str; } else if (linebreak(ch)) { on_linebreak(&t); } tok_begin = cur; break; case Tok_State_maybe_single_char: { QC_Token_Type type = double_char_tokentype(*tok_begin, ch); if (type == QC_Token_unknown) { commit_token(&t, tok_begin, cur, single_char_tokentype(*tok_begin)); --cur; } else { if (type == QC_Token_line_comment) { t.state = Tok_State_line_comment; tok_begin += 2; } else if (type == QC_Token_block_comment) { t.state = Tok_State_block_comment; t.block_comment_depth = 1; tok_begin += 2; } else { commit_token(&t, tok_begin, cur + 1, type); } } } break; case Tok_State_number_after_dot: case Tok_State_number: if ((ch < '0' || ch > '9') && ch != '.') { QC_Token_Type type = QC_Token_int; if (t.state == Tok_State_number_after_dot) type = QC_Token_float; commit_token(&t, tok_begin, cur, type); --cur; break; } if (ch == '.') t.state = Tok_State_number_after_dot; else if (t.state != Tok_State_number_after_dot) t.state = Tok_State_number; break; case Tok_State_name: if ( whitespace(ch) || single_char_tokentype(ch) != QC_Token_unknown) { commit_token(&t, tok_begin, cur, QC_Token_name); --cur; } break; case Tok_State_str: if (ch == t.string_begin_char) commit_token(&t, tok_begin + 1, cur, QC_Token_string); break; case Tok_State_line_comment: if (linebreak(ch)) { commit_token(&t, tok_begin, cur, QC_Token_line_comment); on_linebreak(&t); } case Tok_State_block_comment: { char a = *(cur - 1); char b = *(cur); if (double_char_tokentype(a, b) == QC_Token_block_comment) { ++t.block_comment_depth; } else if (a == '*' && b == '/') { --t.block_comment_depth; if (t.block_comment_depth <= 0) commit_token(&t, tok_begin, cur - 1, QC_Token_block_comment); } } break; default:; } ++cur; } { /* Append eof */ QC_Token eof = {0}; eof.text.buf = "eof"; eof.text.len = strlen(eof.text.buf); eof.line = t.cur_line; eof.last_on_line = QC_true; qc_push_array(QC_Token)(&t.tokens, eof); } return t.tokens; }
static void read_in_messages(FILE *fd, char *buffer) { /** Read the specified messages into the open file. If the first character of "buffer" is 'm' then prefix it, other- wise just stream it in straight...Since we're using the pipe to 'readmsg' we can also allow the user to specify patterns and such too... **/ FILE *myfd; char local_buffer[SLEN], *arg; int add_prefix=0, mindex; int n; int lines = 0, nchars = 0; add_prefix = tolower(buffer[0]) == 'm'; /* strip whitespace to get argument */ for(arg = &buffer[1]; whitespace(*arg); arg++) ; /* a couple of quick checks */ if(curr_folder.num_mssgs < 1) { PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmNoMessageReadContinue, "(No messages to read in! Continue.)\n\r")); return; } if (isdigit(*arg)) { if((mindex = atoi(arg)) < 1 || mindex > curr_folder.num_mssgs) { sprintf(local_buffer, catgets(elm_msg_cat, ElmSet, ElmValidNumbersBetween, "(Valid message numbers are between 1 and %d. Continue.)\n\r"), curr_folder.num_mssgs); PutLine(-1, -1, local_buffer); return; } } /* dump state information for "readmsg" to use */ if (create_folder_state_file() != 0) return; /* go run readmsg and get output */ sprintf(local_buffer, "%s -- %s", readmsg, arg); if ((myfd = popen(local_buffer, "r")) == NULL) { PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmCantFindReadmsg, "(Can't find 'readmsg' command! Continue.)\n\r")); (void) remove_folder_state_file(); return; } dprint(5, (debugfile, "** readmsg call: \"%s\" **\n", local_buffer)); while ((n = mail_gets(local_buffer, SLEN, myfd))) { nchars += n; if (local_buffer[n-1] == '\n') lines++; if (add_prefix) fprintf(fd, "%s", prefixchars); fwrite(local_buffer, 1, n, fd); } pclose(myfd); (void) remove_folder_state_file(); if (lines == 0) { PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmEditmsgCouldntAdd, "(Couldn't add the requested message. Continue.)\n\r")); return; } if (lines == 1) PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedLine, "\n\r(Added 1 line [")); else PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedLinePlural, "\n\r(Added %d lines ["), lines); if (nchars == 1) PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedChar, "1 char] ")); else PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedCharPlural, "%d chars] "), nchars); PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedToMessage, "to message. Continue.)\n\r")); return; }
// Check if a string is only whitespace bool a::whitespace(const string &s) { for (unsigned i=0; i<s.length(); i++) if (!whitespace(s[i])) return false; return true; }
int cue2desc(const char *cue_file, const char *desc_file) { cue2desc_error_t ret = e_ok; FILE *fp = fopen(cue_file, "r"); if (!fp) { error("Could not open specified cue file"); return e_no_cue_file; } cur_filesize = cur_track = cur_secsize = 0; cur_fileindex = open_seg = -1; nseg = 0; segments = calloc(1, sizeof(segment_t)); n_filenames = 0; filenames = calloc(1, sizeof(char*)); char buf[512]; char *line; while ((line = fgets(buf, sizeof(buf), fp))) { // Trim whitespace at front while (*line && whitespace(*line)) line++; if (!*line) continue; // Trim whitespace at end char *eol = line + strlen(line) - 1; while (eol > line && whitespace(*eol)) *eol-- = '\0'; // Find command word char *space = strchr(line, ' '); if (!space) { error("No space in line"); ret = e_bad_cue_file; goto out; } *space = '\0'; char *params = space + 1; if (!strcmp(line, "CATALOG") || !strcmp(line, "CDTEXTFILE") || !strcmp(line, "FLAGS") || !strcmp(line, "ISRC") || !strcmp(line, "PERFORMER") || !strcmp(line, "POSTGAP") || !strcmp(line, "REM") || !strcmp(line, "SONGWRITER") || !strcmp(line, "TITLE")) continue; // recognised, but unsupported if (!strcmp(line, "FILE")) ret = handle_file(params); else if (!strcmp(line, "TRACK")) ret = handle_track(params); else if (!strcmp(line, "INDEX")) ret = handle_index(params); else if (!strcmp(line, "PREGAP")) ret = handle_pregap(params); else ret = e_bad_cue_file; if (ret != e_ok) goto out; } handle_end_of_track_file(); uint32_t disc_fad = 150; for (int i=0; i<nseg; i++) { segments[i].start = disc_fad; disc_fad += segments[i].length; } ret = write_desc_file(desc_file, segments, nseg); out: for (int i=0; i<n_filenames; i++) free(filenames[i]); free(filenames); free(segments); fclose(fp); return ret; }
int spawnve(int mode, const char *name, char * const argv[], char * const envp[]) { int i, j, l, n, prefix_len = 0; char *ext, *tmp, *arg1, *execname, *p_arg, *p_env, *prefix = NULL; char runtype, freeexec = 0, hswValid = 0, quoteargs = 1; ULONG appflags; const char * const *p; unsigned int runflags = 0; int retcode = -1; char errbuf[MAXNAMLEN + 1], queue[MAXNAMLEN + 1]; SWCNTRL swc; HSWITCH vioHSW; errno = ENOENT; /* EMX crashes on very long filenames... */ if (strlen (name) > MAXNAMLEN - 4) { errno = ENAMETOOLONG; return -1; } /* Find extension ordinal in exec_ext array */ ext = _getext2(name); for (i = 0; i < EXEC_EXT_COUNT; i++) { if (strcmp(ext, exec_ext[i]) == 0) goto found; } if (access(name, F_OK) == 0) errno = ENOEXEC; return -1; found: { PTIB tb; PPIB pb; /* Determine our session type */ if ((DosGetInfoBlocks(&tb, &pb) == NO_ERROR) && (vioHSW = WinQuerySwitchHandle(NULLHANDLE, pb->pib_ulpid)) && (WinQuerySwitchEntry(vioHSW, &swc) == NO_ERROR)) hswValid = 1; } switch (mode & 0xFF) { case P_WAIT: runflags |= spawn_WAIT; break; case P_PM: runflags |= spawn_SESSION | spawn_TYPE_PM; break; case P_OVERLAY: runflags |= spawn_WAIT | spawn_OVERLAY; break; case P_DETACH: runflags |= spawn_DETACH; break; } if (((runtype = exec_run[i]) == 0) && (DosQueryAppType((PSZ)name, &appflags) == NO_ERROR) && ((runflags & spawn_DETACH) == 0) && (hswValid)) { /* Compare to application type */ switch (appflags & 7) { case FAPPTYP_NOTSPEC: /* Methinks its a DOS proggy */ { if (appflags & FAPPTYP_DOS) if (swc.bProgType == PROG_FULLSCREEN) runflags |= (spawn_SESSION | spawn_TYPE_VDM); else runflags |= (spawn_SESSION | spawn_TYPE_WINDOWEDVDM); else runflags |= (spawn_SESSION | spawn_TYPE_DEFAULT); break; } case FAPPTYP_NOTWINDOWCOMPAT: { if (swc.bProgType != PROG_FULLSCREEN) runflags |= (spawn_SESSION | spawn_TYPE_FULLSCREEN); break; } case FAPPTYP_WINDOWCOMPAT: { /* That'll do it */ break; } case FAPPTYP_WINDOWAPI: { runflags |= (spawn_SESSION | spawn_TYPE_PM); break; } default: { runtype = 1; /* Let $COMSPEC decide what to do */ break; } } } fallback: switch (runtype) { case 0: directrun: if ((runflags & spawn_SESSION) && (((runflags & spawn_TYPE) == spawn_TYPE_VDM) || ((runflags & spawn_TYPE) == spawn_TYPE_WINDOWEDVDM))) { /* DOS command interpreter does not understand '/'s */ execname = savestring((char *)name); freeexec = 1; for (tmp = execname; *tmp; tmp++) if (*tmp == '/') *tmp = '\\'; } else execname = (char *)name; break; case 1: execname = get_string_value ("COMSPEC"); if (!execname) { internal_error("COMSPEC variable not defined"); errno = EACCES; return -1; } prefix_len = strlen(execname) + 1; prefix = alloca(prefix_len + 2 + 1 + strlen(name) + 1); strcpy(prefix, execname); emx_deunixify(prefix); strcpy((char *)&prefix[prefix_len - 1], " /c "); prefix_len += 2 + 1; strcpy((char *)&prefix[prefix_len], name); prefix_len += strlen(name) + 1; break; case 2: default: { /* We must define HAVE_HASH_BANG_EXEC since we`re processing #! here */ FILE *f; char line[MAXNAMLEN + 3]; line[0] = 0; if (!(f = fopen(name, "rt"))) { errno = ENOENT; return -1; }; fgets((char *)&line, sizeof(line), f); fclose(f); if (line[0] != '#') /* Try to run as regular executable */ goto directrun; if (line[1] != '!') { /* Run script using current shell */ strcpy((char *)&line, "#! "); strcat((char *)&line, shell_name); } n = strlen(line); while ((n > 0) && ((line[n - 1] < ' ') || (whitespace(line[n])))) n--; for (i = 2; whitespace(line[i]) && i < n; i++) ; for (j = i; (!whitespace(line[j])) && j < n; j++) ; l = i; j++; tmp = xmalloc(j - i); _strncpy(tmp, (char *)&line[i], j - i); execname = find_user_command(tmp); free(tmp); freeexec = 1; prefix_len = n - l + 1 + 1 + strlen(name); prefix = alloca(prefix_len + 1); _strncpy(prefix, (char *)&line[l], n - l + 1); strcat(prefix, " "); strcat(prefix, name); break; } } if ((execname == NULL) || (access(execname, F_OK) != 0)) { if (execname == NULL) { errno = ENOEXEC; return -1; } execname = savestring(execname); freeexec = 1; if ((ext_file_status(&execname) & FS_EXISTS) == 0) { free(execname); errno = ENOENT; return -1; } } { char *qlist = get_string_value ("BASH_NOQUOTEARGS"); char *tmp, *name = _getname (execname); int namelen; tmp = _getext (name); namelen = (tmp ? (int) (tmp - name) : strlen (name)); while (qlist) { tmp = strchr (qlist, ';'); if (!(j = tmp ? (int) (tmp - qlist) : strlen (qlist))) break; if ((namelen == j) && (memicmp (qlist, name, namelen) == 0)) { quoteargs = 0; break; } qlist += j; while (qlist[0] == ';') qlist++; } } /* Prepare command-line string */ j = prefix_len + 2; for (i = 0; i <= 1; i++) { for (p = (const char **)argv; *p != NULL; ++p) { if (p != (const char **)argv) if (i == 0) // Add a space before args starting from 1 j++; else strcat(p_arg, " "); else if (prefix_len) continue; // Prefix already contains argv[0] // If argv[i] contains a space or tab, we should put it in quotes if (strchr(*p, ' ') || strchr(*p, '\t')) if (i == 0) j += 1 + (quoteargs ? q_strlen(*p) : strlen(*p)) + 1; else { strcat(p_arg, "\""); if (quoteargs) q_strcat (p_arg, *p); else strcat (p_arg, *p); strcat(p_arg, "\""); } else // If we`re running a EMX program, we should backquote all '"'s in argv[i] if (i == 0) j += (quoteargs ? q_strlen(*p) : strlen(*p)); else if (quoteargs) q_strcat(p_arg, *p); else strcat(p_arg, *p); } if (i == 0) { p_arg = alloca(j); if (prefix_len) { memcpy(p_arg, prefix, prefix_len); p_arg[prefix_len] = ' '; p_arg[prefix_len + 1] = 0; } else *p_arg = 0; } } p_arg[strlen(p_arg) + 1] = 0; #if 0 printf("quoteargs = %d\n", quoteargs); printf("exec{%s}\n", execname); printf("args{%s}\n", p_arg); #endif for (arg1 = p_arg; !whitespace(*arg1) && *arg1; arg1++) ; *arg1++ = 0; /* Prepare environment */ j = 1; for (p = (const char * const *)envp; *p != NULL; ++p) j += strlen (*p) + 1; p_env = tmp = alloca(j); for (p = (const char * const *)envp; *p != NULL; ++p) { i = strlen (*p); memcpy(tmp, *p, i+1); tmp += i+1; } *tmp = 0; if (runflags & spawn_SESSION) /* Use DosStartSession */ { HQUEUE hq; /* Termination queue management */ sprintf((char *)&queue, "\\QUEUES\\bash%d", getpid()); if (DosCreateQueue(&hq, QUE_FIFO | QUE_CONVERT_ADDRESS, (PSZ)queue) == NO_ERROR) { STARTDATA sd; ULONG sid,pid; APIRET r; memset(&sd, 0, sizeof(sd)); sd.Length = sizeof(sd); sd.Related = (runflags & spawn_WAIT ? SSF_RELATED_CHILD : SSF_RELATED_INDEPENDENT); sd.FgBg = SSF_FGBG_FORE; sd.PgmName = execname; sd.PgmInputs = arg1; sd.TermQ = (PBYTE)&queue; sd.Environment = p_env; sd.InheritOpt = SSF_INHERTOPT_PARENT; sd.SessionType = (runflags & spawn_TYPE) >> 16; sd.ObjectBuffer = (PSZ)&errbuf; sd.ObjectBuffLen = sizeof(errbuf); #if 0 sd.PgmControl = SSF_CONTROL_NOAUTOCLOSE; #endif r = DosStartSession(&sd, &sid, &pid); if (r == NO_ERROR || r == ERROR_SMG_START_IN_BACKGROUND) { if (runflags & spawn_WAIT) { REQUESTDATA rd; ULONG Length; PUSHORT Info = NULL; BYTE Priority; ULONG oldVis, oldJump; SWP oldpos; if (hswValid) { /* Exclude session from task list */ oldVis = swc.uchVisibility; swc.uchVisibility = SWL_INVISIBLE; oldJump = swc.fbJump; swc.fbJump = SWL_NOTJUMPABLE; WinChangeSwitchEntry(vioHSW, &swc); /* Minimize session */ WinQueryWindowPos(swc.hwnd, &oldpos); if ((oldpos.fl & SWP_MINIMIZE) == 0) WinPostMsg(swc.hwnd, WM_SYSCOMMAND, (MPARAM)SC_MINIMIZE, MPFROM2SHORT(CMDSRC_MENU, FALSE)); } DosReadQueue(hq, &rd, &Length, (PPVOID)&Info, 0, DCWW_WAIT, &Priority, 0); if (hswValid) { /* Restore jumpable & visible status */ swc.uchVisibility = oldVis; swc.fbJump = oldJump; WinChangeSwitchEntry(vioHSW, &swc); /* Restore session */ if ((oldpos.fl & SWP_MINIMIZE) == 0) { WinPostMsg(swc.hwnd, WM_SYSCOMMAND, (MPARAM)SC_RESTORE, MPFROM2SHORT(CMDSRC_MENU, FALSE)); WinSetWindowPos(swc.hwnd, oldpos.hwndInsertBehind, oldpos.x, oldpos.y, oldpos.cx, oldpos.cy, oldpos.fl); } } retcode = Info[1]; } else retcode = pid; } else internal_error("Execution failed because of module \"%s\"", (char *)&errbuf); DosCloseQueue(hq); } else
int main(int argc, char** argv) { // between ok(between('a','z','c'), "c is between a and z"); fail(between('a','z','C'), "C is not between a and z"); // num ok(num('0'), "0 is a number"); ok(num('9'), "9 is a number"); fail(num('/'), "/ is not a number"); fail(num(':'), "0 is not a number"); // alpha ok(alpha('a'), "a is a letter"); ok(alpha('z'), "z is a letter"); ok(alpha('A'), "A is a letter"); ok(alpha('Z'), "Z is a letter"); fail(alpha('@'), "@ is not a letter"); fail(alpha('['), "[ is not a letter"); fail(alpha('`'), "` is not a letter"); fail(alpha('{'), "{ is not a letter"); // alphanum ok(alphanum('a'), "a is alphanum"); ok(alphanum('z'), "z is alphanum"); ok(alphanum('A'), "A is alphanum"); ok(alphanum('Z'), "Z is alphanum"); ok(alphanum('0'), "0 is alphanum"); ok(alphanum('9'), "9 is alphanum"); fail(alpha('@'), "@ is not alphanum "); fail(alpha('['), "[ is not alphanum"); fail(alpha('`'), "` is not alphanum"); fail(alpha('{'), "{ is not alphanum"); // space ok(space(' '), "space is space"); fail(space('\n'), "new line is not space"); fail(space('\r'), "cr is not space"); fail(space('\t'), "tab is not space"); // tab ok(tab('\t'), "tab is tab"); fail(tab(' '), "space is not tab"); fail(tab('\n'), "new line is not tab"); fail(tab('\r'), "cr is not tab"); // nl ok(nl('\n'), "new line is new line"); fail(nl('\t'), "tab is not new line"); fail(nl(' '), "space is not new line"); fail(nl('\r'), "cr is not new line"); // cr fail(cr('\n'), "new line is not cr"); fail(cr('\t'), "tab is not cr"); fail(cr(' '), "space is not cr"); ok(cr('\r'), "cr is cr"); // whitespace ok(whitespace('\n'), "new line is whitespace"); ok(whitespace('\t'), "tab is whitespace"); ok(whitespace(' '), "space is whitespace"); ok(whitespace('\r'), "cr is whitespace"); fail(whitespace('\b'), "backspace is not whitespace"); // colon ok(colon(':'), "colon is colon"); fail(colon(';'), "semicolon is not colon"); // semi fail(semi(':'), "colon is not semicolon"); ok(semi(';'), "semicolon is semicolon"); // slash fail(slash('\\'), "\\ is not /"); ok(slash('/'), "/ is /"); // dot fail(dot('*'), "* is not ."); ok(dot('.'), ". is ."); // star ok(star('*'), "* is *"); fail(star('.'), ". is not *"); // question ok(question('?'), "? is ?"); // hex ok(hex('a'), "a is hex"); ok(hex('f'), "f is hex"); ok(hex('A'), "A is hex"); ok(hex('F'), "F is hex"); ok(hex('0'), "0 is hex"); ok(hex('9'), "9 is hex"); fail(hex('g'), "g is not hex"); fail(hex('G'), "G is not hex"); // decimal ok(decimal('0'), "0 is decimal"); ok(decimal('9'), "9 is decimal"); ok(decimal('.'), ". is decimal"); fail(decimal('a'), "a is not decimal"); // ctrl ok(ctrl('\b'), "Backspace is ctrl"); ok(ctrl('\a'), "Bell is ctrl"); ok(ctrl(127), "Del is ctrl"); fail(ctrl('a'), "a is not ctrl"); // any value(3,any(alpha,"abc123"), "three letters at abc123"); value(0,any(num,"abc123"), "no numbers at abc123"); value(6,any(alphanum,"abc123"), "six alphanum in abc123"); // until value(5,until(space,"hello world!"), "5 letters until space"); value(11,until(question,"hello world?"), "11 letters until question"); value(12,until(ctrl,"hello world?"), "12 chacters till end"); // crlf, eol, and upto value(6, upto(eol, "line 1\r\nline 1\r\n"), "6 chars upto crlf"); value(0, upto(eol, "\r\n\r\n"), "0 characters to end of line"); value(12, upto(eol, "hello world!"), "12 characters to eol"); // all test value(5, all(dot, ".....\r\n"), "there are 5 dots"); return done("test_parse"); }
static void adddir (const char *bp, int mandatory) { int i; struct dirs *dlp; while (whitespace(*bp)) bp++; if (*bp == 0) gripe (PARSE_ERROR_IN_CONFIG); dlp = &cfdirlist; while (dlp->nxt) dlp = dlp->nxt; dlp->nxt = (struct dirs *) my_malloc (sizeof(struct dirs)); dlp = dlp->nxt; dlp->mandatory = mandatory; dlp->nxt = 0; if (!mandatory) { i = 0; while (*bp && !whitespace(*bp)) { if (i < MAXPATHLEN - 1) dlp->bindir[i++] = *bp; bp++; } dlp->bindir[i] = 0; while (whitespace(*bp)) bp++; } else { dlp->bindir[0] = 0; } i = 0; while (*bp && !whitespace(*bp)) { if (i < MAXPATHLEN - 1) dlp->mandir[i++] = *bp; bp++; } dlp->mandir[i] = 0; while (whitespace(*bp)) bp++; i = 0; while (*bp && !whitespace(*bp)) { if (i < MAXPATHLEN - 1) dlp->catdir[i++] = *bp; bp++; } dlp->catdir[i] = 0; if (debug) { if (dlp->mandatory) gripe (FOUND_MANDIR, dlp->mandir); else gripe (FOUND_MAP, dlp->bindir, dlp->mandir); if (dlp->catdir[0]) gripe (FOUND_CATDIR, dlp->catdir); } }
void read_config_file (const char *cf) { char *bp; char *p; char buf[BUFSIZE]; FILE *config = NULL; if (cf) { /* User explicitly specified a config file */ if ((config = fopen (cf, "r")) == NULL) { perror (cf); gripe (CONFIG_OPEN_ERROR, cf); return; } } else { /* Try some things - unfortunately we cannot lookup the config file to use in the config file :-). */ int i; for(i=0; i < SIZE(default_config_files); i++) { cf = default_config_files[i]; if ((config = fopen (cf, "r")) != NULL) break; } if (config == NULL) { gripe (CONFIG_OPEN_ERROR, CONFIG_FILE); return; } } if (debug) fprintf(stderr, "Reading config file %s\n", cf); configuration_file = cf; while ((bp = fgets (buf, BUFSIZE, config)) != NULL) { while (whitespace(*bp)) bp++; for (p = bp; *p && *p != '#' && *p != '\n'; p++) ; if (!*p) { gripe (LINE_TOO_LONG); gripe (BAD_CONFIG_FILE, cf); return; } while (p > bp && whitespace(p[-1])) p--; *p = 0; if (*bp == 0) continue; if (!strncmp ("MANPATH_MAP", bp, 11)) adddir (bp+11, 0); else if (!strncmp ("MANPATH", bp, 7)) addglobdir (bp+7, 1); else if(!strncmp ("MANDATORY_MANPATH", bp, 17))/* backwards compatible */ adddir (bp+17, 1); else if (!strncmp ("FHS", bp, 3)) fhs = 1; else if (!strncmp ("FSSTND", bp, 6)) fsstnd = 1; else if (!strncmp ("NOAUTOPATH", bp, 10)) noautopath = 1; else if (!strncmp ("NOCACHE", bp, 7)) nocache = 1; else if (*bp == '.') addext (bp); else addval (bp); } }
void skip_whitespace(std::string & directive_str) { while (whitespace(directive_str[0])) directive_str = directive_str.substr(1); }
/* Execute a command line. */ int execute_line(char *line) { int i; Command *command; char *word; /* Isolate the command word. */ i = 0; while (line[i] && whitespace(line[i])) i++; word = line + i; while (line[i] && !whitespace(line[i])) i++; if (line[i]) line[i++] = '\0'; command = find_command(word); if (!command) { fprintf(stderr, "%s: No such command for AMIT cli.\n", word); return (-1); } /* Get argument to command, if any. */ while (whitespace(line[i])) i++; word = line + i; char *arg = word; const char *token[PARA_SIZE]; int t=0; i=0; while(arg[i]) { while (arg[i] && whitespace(arg[i])) i++; token[t++] = arg + i; while (arg[i] && !whitespace(arg[i])) i++; if (arg[i]) arg[i++] = '\0'; if (t >= PARA_SIZE) { printf("exceed MAX parameters: %d\n", PARA_SIZE); break; } } #if 0 for (i=0 ; i < t ; ++i) printf("token[%d]: %s\n", i, token[i]); #endif /* Call the function. */ return ((*(command->func)) (token, t)); }
void info_parse_node (char *string, int flag) { register int i = 0; /* Default the answer. */ save_filename (NULL); save_nodename (NULL); /* Special case of nothing passed. Return nothing. */ if (!string || !*string) return; string += skip_whitespace (string); /* Check for (FILENAME)NODENAME. */ if (*string == '(') { int bcnt; int bfirst; i = 0; /* Advance past the opening paren. */ string++; /* Find the closing paren. Handle nested parens correctly. */ for (bcnt = 0, bfirst = -1; string[i]; i++) { if (string[i] == ')') { if (bcnt == 0) { bfirst = -1; break; } else if (!bfirst) bfirst = i; bcnt--; } else if (string[i] == '(') bcnt++; } if (bfirst >= 0) i = bfirst; /* Remember parsed filename. */ saven_filename (string, i); /* Point directly at the nodename. */ string += i; if (*string) string++; } /* Parse out nodename. */ i = skip_node_characters (string, flag); saven_nodename (string, i); canonicalize_whitespace (info_parsed_nodename); if (info_parsed_nodename && !*info_parsed_nodename) { free (info_parsed_nodename); info_parsed_nodename = NULL; } /* Parse ``(line ...)'' part of menus, if any. */ { char *rest = string + i; /* Advance only if it's not already at end of string. */ if (*rest) rest++; /* Skip any whitespace first, and then a newline in case the item was so long to contain the ``(line ...)'' string in the same physical line. */ while (whitespace(*rest)) rest++; if (*rest == '\n') { rest++; while (whitespace(*rest)) rest++; } /* Are we looking at an opening parenthesis? That can only mean we have a winner. :) */ if (strncmp (rest, "(line ", strlen ("(line ")) == 0) { rest += strlen ("(line "); info_parsed_line_number = strtol (rest, NULL, 0); } else info_parsed_line_number = 0; } }
static char * cleanup_html_whitespace (char *string, int len, int beautify_p) { register int src, dst; char *result = (char *)xmalloc (1 + len); int quoted = 0; int brace_level = 0; int in_pre = 0; int in_textarea = 0; int in_script = 0; int accum = 0, newlines = 0; src = dst = 0; while (src < len) { if (!quoted && !in_pre && !in_textarea && !in_script) { if (newline (string[src])) newlines++; else if (whitespace (string[src])) accum++; else { if (newlines) { if (string[src] != '>') { result[dst++] = '\n'; if (beautify_p && (newlines > 1)) result[dst++] = '\n'; } newlines = 0; accum = 0; } else if (accum) { accum = 0; if (string[src] != '>') result[dst++] = ' '; } result[dst++] = string[src]; } } else { result[dst++] = string[src]; } if (string[src] == '"') quoted = !quoted; if (!quoted) { if (string[src] == '<') { brace_level++; /* Check for <TEXTAREA .... Do NOT check for "<TEXTAREA>" as that is handled below. */ if ((string[src + 1] == 'T' || string[src + 1] == 't') && (string[src + 2] == 'E' || string[src + 2] == 'e') && (string[src + 3] == 'X' || string[src + 3] == 'x') && (string[src + 4] == 'T' || string[src + 4] == 't') && (string[src + 5] == 'A' || string[src + 5] == 'a') && (string[src + 6] == 'R' || string[src + 6] == 'r') && (string[src + 7] == 'E' || string[src + 7] == 'e') && (string[src + 8] == 'A' || string[src + 8] == 'a') && (whitespace (string[src + 9]) || (newline (string[src + 9])))) in_textarea++; else if ((string[src + 1] == 'S' || string[src + 1] == 's') && (string[src + 2] == 'C' || string[src + 2] == 'c') && (string[src + 3] == 'R' || string[src + 3] == 'r') && (string[src + 4] == 'I' || string[src + 4] == 'i') && (string[src + 5] == 'P' || string[src + 5] == 'p') && (string[src + 6] == 'T' || string[src + 6] == 't') && (whitespace (string[src + 7]) || (newline (string[src + 7])))) in_script++; } else if (string[src] == '>') { brace_level--; if (src > 3) { /* Check explicitly for <pre> and </pre> */ if ((string[src - 1] == 'E' || string[src - 1] == 'e') && (string[src - 2] == 'R' || string[src - 2] == 'r') && (string[src - 3] == 'P' || string[src - 3] == 'p')) { if (string[src - 4] == '<') in_pre++; else if (in_pre && (string[src - 4] == '/' && string[src - 5] == '<')) in_pre--; } if (src > 6) { /* Check explicitly for <script> and </script>. */ if ((string[src - 1] == 'T' || string[src - 1] == 't') && (string[src - 2] == 'P' || string[src - 2] == 'p') && (string[src - 3] == 'I' || string[src - 3] == 'i') && (string[src - 4] == 'R' || string[src - 4] == 'r') && (string[src - 5] == 'C' || string[src - 5] == 'c') && (string[src - 6] == 'S' || string[src - 6] == 's')) { if (string[src - 7] == '<') in_script++; else if (in_script && (string[src - 7] == '/' && (src > 7) && string[src - 8] == '<')) in_script--; } } if (src > 8) { /* Check explicitly for </textarea>. */ if ((string[src - 1] == 'A' || string[src - 1] == 'a') && (string[src - 2] == 'E' || string[src - 2] == 'e') && (string[src - 3] == 'R' || string[src - 3] == 'r') && (string[src - 4] == 'A' || string[src - 4] == 'a') && (string[src - 5] == 'T' || string[src - 5] == 't') && (string[src - 6] == 'X' || string[src - 6] == 'x') && (string[src - 7] == 'E' || string[src - 7] == 'e') && (string[src - 8] == 'T' || string[src - 8] == 't')) { if (string[src - 9] == '<') in_textarea++; else if (in_textarea && (string[src - 9] == '/' && (src > 9) && string[src - 10] == '<')) in_textarea--; } } } } } src++; } result[dst] = '\0'; return (result); }
bool alphanumeric(char c) { return !whitespace(c) && !parenthenesis(c); }
static void read_in_file(FILE *fd, const char *filename, int show_user_filename) { /** Open the specified file and stream it in to the already opened file descriptor given to us. When we're done output the number of lines and characters we added, if any... **/ FILE *myfd; char exp_fname[SLEN], buffer[SLEN]; int n; int lines = 0, nchars = 0; while (whitespace(*filename)) ++filename; /** expand any shell variables or leading '~' **/ (void) expand_env(exp_fname, filename, sizeof(exp_fname)); if (exp_fname[0] == '\0') { PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmNoFilenameSpecified, "\n\r(No filename specified for file read! Continue.)\n\r")); return; } if ((myfd = fopen(exp_fname,"r")) == NULL) { PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmCouldntReadFile, "\n\r(Couldn't read file '%s'! Continue.)\n\r"), exp_fname); return; } while ((n = mail_gets(buffer, SLEN, myfd))) { if (buffer[n-1] == '\n') lines++; nchars += n; fwrite(buffer, 1, n, fd); } fflush(fd); fclose(myfd); if (lines == 1) PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedLine, "\n\r(Added 1 line [")); else PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedLinePlural, "\n\r(Added %d lines ["), lines); if (nchars == 1) PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedChar, "1 char] ")); else PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedCharPlural, "%d chars] "), nchars); if (show_user_filename) PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedFromFile, "from file %s. Continue.)\n\r"), exp_fname); else PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmAddedToMessage, "to message. Continue.)\n\r")); return; }
std::shared_ptr< Expression> parse(std::istream& input, int& line_no, bool topLevel) { std::string buffer(""); char c; while (input.good()) { input.get(c); if (whitespace(c)) { if (c == '\n') { line_no++; } if (buffer.empty()) { ;//nothing to do } else { if (digit(buffer[0])) { return std::make_shared<Float>(buffer); } else if (doubleQuote(buffer[0])) { buffer += c; } else if (colon(buffer[0])) { return std::make_shared<Atom>(buffer.substr(1)); } else if (alphanumeric(buffer[0])) { return std::make_shared<Identifier>(buffer); //} else { // return new Identifier(buffer); } } } else if (digit(c)) { buffer += c; } else if (dot(c)) { if (buffer.empty()) { buffer += c; } else { if (digit(buffer[0])) { if (!dotIn(buffer)) { buffer += c; } else { SYNTAX_ERROR(line_no, "Second dot found in Float literal " << buffer + c ); } } else { buffer += c; } } } else if (colon(c)) { if (buffer.empty()) { buffer += c; } else { SYNTAX_ERROR(line_no, "Colon found in the middle of token " << buffer + c ); } } else if (doubleQuote(c)) { if (buffer.empty()) { buffer += c; } else { if (doubleQuote(buffer[0])) { buffer += c; return std::make_shared<String>(buffer); } else { SYNTAX_ERROR(line_no, "Double-quote found in the middle of token " << buffer + c ); } } } else if (parenthenesis(c)) { //BEWARE - THE TRICKY PART //TODO refactor to smaller functions if (buffer.empty()) { if (openParenthenesis(c)) { std::vector< std::shared_ptr<Expression>> list; char c2; input.get(c2); while (!closeParenthenesis(c2)) { input.unget(); std::shared_ptr<Expression> tmpExp = parse(input, line_no, false); if (tmpExp) { list.push_back(tmpExp); } else { input.unget(); } input.get(c2); } if (!parenMatches(c, c2)) { SYNTAX_ERROR(line_no, "Parenthenesis " << c << " is closed by not matching paren : " << c2); } return std::make_shared<List>(list); } else {//closeParenthenesis(c) if (topLevel) { SYNTAX_ERROR(line_no, "Found unmatched close parenthenesis " << c); } else { return NULL;//oznacza, ze trzeba wyjsc } } } else { //end of some token //return c back to the ctream and return expression as a result //or possibly it was ending paren inside a string and we add it simply if (digit(buffer[0])) { input.unget(); return std::make_shared<Float>(buffer); } else if (doubleQuote(buffer[0])) { buffer += c; //no unget, cause it's inside a string literal } else if (colon(buffer[0])) { input.unget(); return std::make_shared<Atom>(buffer); } else if (alphanumeric(buffer[0])) { input.unget(); return std::make_shared<Identifier>(buffer); } else { SYNTAX_ERROR(line_no, "Situation impossible : buffer == " << buffer); } } } else if (alphanumeric(c)) { if (buffer.empty()) { buffer += c; } else { if (!digit(buffer[0])) { buffer += c; } else { SYNTAX_ERROR(line_no, "Non-digit found in the middle of Float literal " << buffer + c ); } } } else { SYNTAX_ERROR(line_no, "Unrecognised char " << c); } } }
/* Make the defun type insertion. TYPE says which insertion this is. X_P, if nonzero, says not to start a new insertion. */ static void defun_internal (int type, int x_p) { int base_type; char **defun_args, **scan_args; const char *category; char *defined_name; char *type_name = NULL; char *type_name2 = NULL; { char *line; /* The @def.. line is the only place in Texinfo where you are allowed to use unquoted braces that don't delimit arguments of a command or a macro; in any other place it will trigger an error message from the reader loop. The special handling of this case inside `args_from_string' is an extra special hack which allows this. The side effect is that if we try to expand the rest of the line below, the recursive reader loop will signal an error if there are brace-delimited arguments on that line. The best solution to this would be to change the syntax of @def.. commands so that it doesn't violate Texinfo's own rules. But it's probably too late for this now, as it will break a lot of existing manuals. Unfortunately, this means that you can't call macros, use @value, etc. inside @def.. commands, sigh. */ get_rest_of_line (0, &line); /* Basic line continuation. If a line ends with \s*@\s* concatanate the next line. */ { char *next_line, *new_line; int i; line_continuation: i = strlen (line) - 1; if (line[i] == '@' && line[i-1] != '@') { get_rest_of_line (0, &next_line); new_line = (char *) xmalloc (i + strlen (next_line) + 2); strncpy (new_line, line, i); new_line[i] = '\0'; free (line); strcat (new_line, " "); strcat (new_line, next_line); line = xstrdup (new_line); free (next_line); free (new_line); goto line_continuation; } } defun_args = (args_from_string (line)); free (line); } scan_args = defun_args; /* Get base type and category string. */ base_type = get_base_type (type); /* xx all these const strings should be determined upon documentlanguage argument and NOT via gettext (kama). */ switch (type) { case defun: case deftypefun: category = _("Function"); break; case defmac: category = _("Macro"); break; case defspec: category = _("Special Form"); break; case defvar: case deftypevar: category = _("Variable"); break; case defopt: category = _("User Option"); break; case defivar: case deftypeivar: category = _("Instance Variable"); break; case defmethod: case deftypemethod: category = _("Method"); break; default: category = next_nonwhite_defun_arg (&scan_args); break; } /* The class name. */ if ((base_type == deftypecv) || (base_type == deftypefn) || (base_type == deftypevr) || (base_type == defcv) || (base_type == defop) || (base_type == deftypeivar) || (base_type == deftypemethod) || (base_type == deftypeop) ) type_name = next_nonwhite_defun_arg (&scan_args); /* The type name for typed languages. */ if ((base_type == deftypecv) || (base_type == deftypeivar) || (base_type == deftypemethod) || (base_type == deftypeop) ) type_name2 = next_nonwhite_defun_arg (&scan_args); /* The function or whatever that's actually being defined. */ defined_name = next_nonwhite_defun_arg (&scan_args); /* This hack exists solely for the purposes of formatting the Texinfo manual. I couldn't think of a better way. The token might be a simple @@ followed immediately by more text. If this is the case, then the next defun arg is part of this one, and we should concatenate them. */ if (*scan_args && **scan_args && !whitespace (**scan_args) && STREQ (defined_name, "@@")) { char *tem = xmalloc (3 + strlen (scan_args[0])); sprintf (tem, "@@%s", scan_args[0]); free (scan_args[0]); scan_args[0] = tem; scan_args++; defined_name = tem; } /* It's easy to write @defun foo(arg1 arg2), but a following ( is misparsed by texinfo.tex and this is next to impossible to fix. Warn about it. */ if (*scan_args && **scan_args && **scan_args == '(') warning ("`%c' follows defined name `%s' instead of whitespace", **scan_args, defined_name); if (!x_p) begin_insertion (type); /* Write the definition header line. This should start at the normal indentation. */ current_indent -= default_indentation_increment; start_paragraph (); if (!html && !xml) switch (base_type) { case deffn: case defvr: case deftp: execute_string (" --- %s: %s", category, defined_name); break; case deftypefn: case deftypevr: execute_string (" --- %s: %s %s", category, type_name, defined_name); break; case defcv: execute_string (" --- %s %s %s: %s", category, _("of"), type_name, defined_name); break; case deftypecv: case deftypeivar: execute_string (" --- %s %s %s: %s %s", category, _("of"), type_name, type_name2, defined_name); break; case defop: execute_string (" --- %s %s %s: %s", category, _("on"), type_name, defined_name); break; case deftypeop: execute_string (" --- %s %s %s: %s %s", category, _("on"), type_name, type_name2, defined_name); break; case deftypemethod: execute_string (" --- %s %s %s: %s %s", category, _("on"), type_name, type_name2, defined_name); break; } else if (html) { /* If this is not a @def...x version, it could only be a normal version @def.... So start the table here. */ if (!x_p) insert_string ("<div class=\"defun\">\n"); else rollback_empty_tag ("blockquote"); /* xx The single words (on, off) used here, should depend on documentlanguage and NOT on gettext --kama. */ switch (base_type) { case deffn: case defvr: case deftp: case deftypefn: case deftypevr: execute_string ("--- %s: ", category); break; case defcv: case deftypecv: case deftypeivar: execute_string ("--- %s %s %s: ", category, _("of"), type_name); break; case defop: case deftypemethod: case deftypeop: execute_string ("--- %s %s %s: ", category, _("on"), type_name); break; } /* switch (base_type)... */ switch (base_type) { case deffn: case defvr: case deftp: /* <var> is for the following function arguments. */ insert_html_tag (START, "b"); execute_string ("%s", defined_name); insert_html_tag (END, "b"); insert_html_tag (START, "var"); break; case deftypefn: case deftypevr: execute_string ("%s ", type_name); insert_html_tag (START, "b"); execute_string ("%s", defined_name); insert_html_tag (END, "b"); insert_html_tag (START, "var"); break; case defcv: case defop: insert_html_tag (START, "b"); execute_string ("%s", defined_name); insert_html_tag (END, "b"); insert_html_tag (START, "var"); break; case deftypecv: case deftypeivar: case deftypemethod: case deftypeop: execute_string ("%s ", type_name2); insert_html_tag (START, "b"); execute_string ("%s", defined_name); insert_html_tag (END, "b"); insert_html_tag (START, "var"); break; } } else if (xml) xml_begin_def_term (base_type, category, defined_name, type_name, type_name2); current_indent += default_indentation_increment; /* Now process the function arguments, if any. If these carry onto the next line, they should be indented by two increments to distinguish them from the body of the definition, which is indented by one increment. */ current_indent += default_indentation_increment; switch (base_type) { case deffn: case defop: process_defun_args (scan_args, 1); break; /* Through Makeinfo 1.67 we processed remaining args only for deftp, deftypefn, and deftypemethod. But the libc manual, for example, needs to say: @deftypevar {char *} tzname[2] And simply allowing the extra text seems far simpler than trying to invent yet more defn commands. In any case, we should either output it or give an error, not silently ignore it. */ default: process_defun_args (scan_args, 0); break; } current_indent -= default_indentation_increment; if (!html) close_single_paragraph (); /* Make an entry in the appropriate index. (XML and Docbook already got their entries, so skip them.) */ if (!xml) switch (base_type) { case deffn: case deftypefn: execute_string ("@findex %s\n", defined_name); break; case defcv: case deftypecv: case deftypevr: case defvr: execute_string ("@vindex %s\n", defined_name); break; case deftypeivar: execute_string ("@vindex %s %s %s\n", defined_name, _("of"), type_name); break; case defop: case deftypeop: case deftypemethod: execute_string ("@findex %s %s %s\n", defined_name, _("on"), type_name); break; case deftp: execute_string ("@tindex %s\n", defined_name); break; } if (xml) xml_end_def_term (); else if (html) { inhibit_paragraph_indentation = 1; no_indent = 1; insert_html_tag (END, "var"); insert_string ("<br>\n"); /* Indent the definition a bit. */ add_html_block_elt ("<blockquote>"); no_indent = 0; inhibit_paragraph_indentation = 0; paragraph_is_open = 0; } /* Deallocate the token list. */ scan_args = defun_args; while (1) { char * arg = (*scan_args++); if (arg == NULL) break; free (arg); } free (defun_args); }
int rl_vi_domove (int key, int *nextkey) { int c, save; int old_end; rl_mark = rl_point; c = rl_read_key (); *nextkey = c; if (!member (c, vi_motion)) { if (digit_p (c)) { save = rl_numeric_arg; rl_numeric_arg = digit_value (c); rl_digit_loop1 (); rl_numeric_arg *= save; c = rl_read_key (); /* real command */ *nextkey = c; } else if (key == c && (key == 'd' || key == 'y' || key == 'c')) { rl_mark = rl_end; rl_beg_of_line (1, c); _rl_vi_last_motion = c; return (0); } else return (-1); } _rl_vi_last_motion = c; /* Append a blank character temporarily so that the motion routines work right at the end of the line. */ old_end = rl_end; rl_line_buffer[rl_end++] = ' '; rl_line_buffer[rl_end] = '\0'; _rl_dispatch (c, _rl_keymap); /* Remove the blank that we added. */ rl_end = old_end; rl_line_buffer[rl_end] = '\0'; if (rl_point > rl_end) rl_point = rl_end; /* No change in position means the command failed. */ if (rl_mark == rl_point) return (-1); /* rl_vi_f[wW]ord () leaves the cursor on the first character of the next word. If we are not at the end of the line, and we are on a non-whitespace character, move back one (presumably to whitespace). */ if ((to_upper (c) == 'W') && rl_point < rl_end && rl_point > rl_mark && !whitespace (rl_line_buffer[rl_point])) rl_point--; /* If cw or cW, back up to the end of a word, so the behaviour of ce or cE is the actual result. Brute-force, no subtlety. */ if (key == 'c' && rl_point >= rl_mark && (to_upper (c) == 'W')) { /* Don't move farther back than where we started. */ while (rl_point > rl_mark && whitespace (rl_line_buffer[rl_point])) rl_point--; /* Posix.2 says that if cw or cW moves the cursor towards the end of the line, the character under the cursor should be deleted. */ if (rl_point == rl_mark) rl_point++; else { /* Move past the end of the word so that the kill doesn't remove the last letter of the previous word. Only do this if we are not at the end of the line. */ if (rl_point >= 0 && rl_point < (rl_end - 1) && !whitespace (rl_line_buffer[rl_point])) rl_point++; } } if (rl_mark < rl_point) exchange (rl_point, rl_mark); return (0); }
urlT* peek(char clow) { static int state = 0; static char site[128]; static int site_len; static char path[128]; static int path_len; char c; urlT* url; c=toupper(clow); switch (state) { case 0: if (c=='<') state=1; break; // all other characters are ignored case 1: if (whitespace(c)) break; state = (c=='A') ? 2 : 0; break; case 2: if (whitespace(c)) state=3; else state=0; break; case 3: if (whitespace(c)) break; state = (c=='H') ? 4 : 0; break; case 4: state = (c=='R') ? 5 : 0; break; case 5: state = (c=='E') ? 6 : 0; break; case 6: state = (c=='F') ? 7 : 0; break; case 7: if (whitespace(c)) break; state = (c=='=') ? 8 : 0; break; case 8: if (whitespace(c)) break; if (c=='\"') { state=9; site_len=0; path_len=0; } else state = 0; break; case 9: //parsing site name case 10: // parsing path after site name if (c=='\"') { site[site_len]=0; path[path_len]=0; state=0; url = (urlT*)malloc(sizeof(urlT)); url->website = newString(site); url->filename = newString(path); return url; } if (c=='\\') { state=10; return NULL; } if (state==9) { site[site_len++]=clow; } else { path[path_len++]=clow; } break; default: // this case should never arrise unless the memory gets corrupted return NULL; } // switch (state) return NULL; } // void htmlParser::peek(char c)
void whitespace_check::inspect( const string & library_name, const path & full_path, // ex: c:/foo/boost/filesystem/path.hpp const string & contents) // contents of file to be inspected { if (contents.find("hpxinspect:" "endlinewhitespace") != string::npos) return; string whitespace(" \t\f\v\r\n"), total, linenum; long errors = 0, currline = 0; size_t p = 0, extend = 0; vector<string> someline, lineorder; char_separator<char> sep("\n", "", boost::keep_empty_tokens); tokenizer<char_separator<char>> tokens(contents, sep); for (const auto& t : tokens) { size_t rend = t.find_first_of("\r"), size = t.size(); if (rend == size - 1) { someline.push_back(t); } else { char_separator<char> sep2("\r", "", boost::keep_empty_tokens); tokenizer<char_separator<char>> tokens2(t, sep2); for (const auto& u : tokens2) { someline.push_back(u); } } } while (p < someline.size()) { currline++; size_t rend = someline[p].find_last_of("\r"); size_t found = someline[p].find_last_not_of(whitespace); if (rend != string::npos) { extend = 2; } else { extend = 1; } size_t size = someline[p].size(); if (found < size - extend || (found == someline[p].npos && size > 1)) { errors++; linenum = to_string(currline); lineorder.push_back(linenum); } p++; } p = 0; while (p < lineorder.size()) { total += linelink(full_path, lineorder[p]); //linelink is located in function_hyper.hpp if (p < lineorder.size() - 1) { total += ", "; } p++; } if (errors > 0) { string errored = "*Endline Whitespace*: " + total; error(library_name, full_path, errored); ++m_files_with_errors; } }
static void pf_parse_line (PFunArgs) { char *line = mhtml_evaluate_string (get_positional_arg (vars, 0)); if (!empty_string_p (line)) { register int i = 0; BPRINTF_BUFFER *output = bprintf_create_buffer (); bprintf (output, "("); /* Hostname. */ skip_whitespace (line, i); bprintf (output, "(\"host\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); /* Find the domain. It's everything from point back to the most recent period. */ { int dot = i - 1; while (dot > 0 && line[dot] != '.') dot--; if (line[dot] == '.') { char *temp = (char *)xmalloc (i - dot); dot++; strncpy (temp, line + dot, i - dot); temp[i - dot] = '\0'; bprintf (output, "(\"domain\" . \"%s\")", temp); } } /* User. */ skip_whitespace (line, i); bprintf (output, "(\"user\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); /* Auth. */ skip_whitespace (line, i); bprintf (output, "(\"auth\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); /* Date, fully parsed. */ skip_whitespace (line, i); /* Expecting "[". */ if (line[i]) i++; /* Day. */ bprintf (output, "(\"day\" . \""); while (line[i] && line[i] != '/') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Month. */ bprintf (output, "(\"month\" . \""); while (line[i] && line[i] != '/') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Year. */ bprintf (output, "(\"year\" . \""); while (line[i] && line[i] != ':') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Hour. */ bprintf (output, "(\"hour\" . \""); while (line[i] && line[i] != ':') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Minute. */ bprintf (output, "(\"minute\" . \""); while (line[i] && line[i] != ':') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Second. */ bprintf (output, "(\"second\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Zone. */ bprintf (output, "(\"zone\" . \""); while (line[i] && line[i] != ']') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; skip_whitespace (line, i); /* The Request. */ if (line[i]) i++; /* Request Type. */ bprintf (output, "(\"req_type\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); /* Request URL. */ skip_whitespace (line, i); bprintf (output, "(\"req_url\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); /* Request Protocol. */ skip_whitespace (line, i); bprintf (output, "(\"req_protocol\" . \""); while (line[i] && line[i] != '"') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); if (line[i]) i++; /* Result Code. */ skip_whitespace (line, i); bprintf (output, "(\"result_code\" . \""); while (line[i] && line[i] != ' ') bprintf (output, "%c", line[i++]); bprintf (output, "\")"); /* Bytes Transferred. */ skip_whitespace (line, i); bprintf (output, "(\"bytes\" . \""); while (line[i] && !whitespace (line[i])) bprintf (output, "%c", line[i++]); bprintf (output, "\")"); bprintf (output, ")"); bprintf_insert (page, start, "%s", output->buffer); *newstart += strlen (output->buffer); bprintf_free_buffer (output); } }
NitLexer::Token NitLexer::lex() { int tk; while (_ch != CHAR_EOS) { whitespace(); switch (_ch) { case CHAR_EOS: return token(TK_EOS); case '/': next(); switch (_ch) { case '*': next(); blockComment(); continue; case '/': lineComment(); continue; case '=': next(); return token(TK_DIVEQ); default: return token('/'); } break; case '=': next(); if (_ch == '>') { next(); return token(TK_LAMBDA); } if (_ch == '=') { next(); return token(TK_EQ); } return token('='); case '<': next(); if (_ch == '<') { next(); return token(TK_SHIFTL); } if (_ch != '=') return token('<'); next(); if (_ch == '>') { next(); return token(TK_THREEWAYSCMP); } return token(TK_LE); case '>': next(); if (_ch == '=') { next(); return token(TK_GE); } if (_ch != '>') return token('>'); next(); if (_ch == '>') { next(); return token(TK_USHIFTR); } return token(TK_SHIFTR); case '!': next(); if (_ch == '=') { next(); return token(TK_NE); } return token('!'); case '@': next(); if (_ch != '"' && _ch != '\'') return token('@'); if ((tk = readString(_ch, '@')) != -1) return token(tk); return error("error parsing verbatim string"); case '"': case '\'': if (readString(_ch) != -1) return token(TK_STRING_VALUE); return error("error parsing the string"); case '{': case '}': case '(': case ')': case '[': case ']': case ';': case ',': case '?': case '^': case '~': case '$': return token(next()); case '.': next(); if (_ch != '.') return token('.'); next(); if (_ch != '.') return error("invalid token '..'"); next(); return token(TK_VARPARAMS); case '&': next(); if (_ch == '&') { next(); return token(TK_AND); } return token('&'); case '|': next(); if (_ch == '|') { next(); return token(TK_OR); } return token('|'); case ':': next(); if (_ch == '=') { next(); return token(TK_NEWSLOT); } if (_ch == '>') { next(); return token(TK_WITHREF); } if (_ch == ':') { next(); return token(TK_DOUBLE_COLON); } return token(':'); case '*': next(); if (_ch == '=') { next(); return token(TK_MULEQ); } return token('*'); case '%': next(); if (_ch == '=') { next(); return token(TK_MODEQ); } return token('%'); case '-': next(); if (_ch == '=') { next(); return token(TK_MINUSEQ); } if (_ch == '-') { next(); return token(TK_MINUSMINUS); } return token('-'); case '+': next(); if (_ch == '=') { next(); return token(TK_PLUSEQ); } if (_ch == '+') { next(); return token(TK_PLUSPLUS); } return token('+'); default: if (isdigit(_ch)) return token(readNumber()); else if (isId(_ch)) return token(readId()); else return error("unexpected character '%c'", _ch); } } return token(TK_EOS); }
/* return value 0 indicates success */ int uCreateProcess( char *command_line, /* command line string */ bool inherit_handles, /* handle inheritance option (not implem*/ const char *cur_dir, /* current directory name */ UFlag flags, UPHANDLE *process_handle, UTHANDLE *thread_handle, UPID *process_id, UTID *thread_id, USECURITY_ATTRIBUTES* sa, sys_call_error_fun fun ) { #ifdef _WIN32 PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; BOOL res; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); if(CREATE_NEW_CONSOLE == flags) { siStartInfo.dwFlags = STARTF_USESHOWWINDOW; siStartInfo.wShowWindow = SW_HIDE; } res = CreateProcess( NULL, /* name of executable module */ command_line, /* command line string */ sa, /* Security attributes for the new process */ sa, /* Security attributes for the main thread */ inherit_handles ? TRUE : FALSE, /* handle inheritance option */ flags, /* creation flags */ NULL, /* use parent's environment */ cur_dir, /* use parent's current directory */ &siStartInfo, /* STARTUPINFO pointer */ &piProcInfo /* receives PROCESS_INFORMATION */ ); if (res == 0) sys_call_error("CreateProcess"); if (process_handle) *process_handle = piProcInfo.hProcess; else if (CloseHandle(piProcInfo.hProcess) == 0) sys_call_error("CloseHandle"); if (thread_handle) *thread_handle = piProcInfo.hThread; else if (CloseHandle(piProcInfo.hThread) == 0) sys_call_error("CloseHandle"); if (process_id) *process_id = piProcInfo.dwProcessId; if (thread_id) *thread_id = piProcInfo.dwThreadId; if (res == 0) return 1; return 0; #else #define MAX_NUMBER_OF_ARGS 256 #define whitespace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\r') pid_t pid = 0; if ((pid = fork()) == 0) { /* child process */ if (flags == U_DETACHED_PROCESS) { /* close stdout and stderr to avoid output to console */ int null_dev = open("/dev/null", O_RDWR); if (null_dev == -1) { sys_call_error("open"); exit(1); } if (close(STDOUT_FILENO) == -1) { sys_call_error("close"); exit(1); } if (close(STDERR_FILENO) == -1){ sys_call_error("close"); exit(1); } if (close(STDIN_FILENO) == -1) { sys_call_error("close"); exit(1); } if (dup2(null_dev, STDOUT_FILENO) == -1) { sys_call_error("dup2"); exit(1); } if (dup2(null_dev, STDERR_FILENO) == -1) { sys_call_error("dup2"); exit(1); } if (dup2(null_dev, STDIN_FILENO) == -1) { sys_call_error("dup2"); exit(1); } if (close(null_dev) == -1) { sys_call_error("close"); exit(1); } } if (cur_dir != NULL) { /* change current directory to cur_dir */ if (chdir(cur_dir) != 0) { sys_call_error("chdir"); exit(1); } } char *args[MAX_NUMBER_OF_ARGS]; memset(args, '\0', MAX_NUMBER_OF_ARGS * sizeof(char*)); int args_num = 0; char *pred = NULL; char *cur = command_line; while (true) { while (whitespace(*cur)) cur++; pred = cur; while (!(whitespace(*cur) || !*cur)) cur++; if (pred < cur) { args[args_num] = (char*)malloc(cur - pred + 1); args[args_num][cur - pred] = '\0'; memcpy(args[args_num], pred, cur - pred); args_num++; } else break; } args[args_num] = NULL; if (execvp(args[0], args) == -1) { sys_call_error("execvp"); exit(1); } for (args_num = 0; args[args_num] != NULL; args_num++) free(args[args_num]); } else { if (pid == -1) { sys_call_error("fork"); return 1; } if (process_handle) *process_handle = 0; if (thread_handle) *thread_handle = 0; if (process_id) *process_id = pid; if (thread_id) *thread_id = 0; } return 0; #endif }
void INIParser::run() { // read the first char next(); while(peek() != -1) { if (accept('[')) { m_builder.send_section(get_section()); expect(']'); whitespace(); if (accept(';') || accept('#')) eat_rest_of_line(); newline(); } else if (accept(' ') || accept('\t') || accept('\n')) { // eat whitespace } else if (accept(';') || accept('#')) { eat_rest_of_line(); newline(); } else // assume name=value pair { std::string name; std::string value; name = get_ident_or_string(); whitespace(); if (accept(';') || accept('#')) { // "name" eat_rest_of_line(); newline(); } else if (accept('=')) { whitespace(); if (accept(';') || accept('#')) { // "name = # comment" eat_rest_of_line(); newline(); } else { // "name = value" value = get_value_or_string(); whitespace(); if (accept(';') || accept('#')) { // "name = value # comment" eat_rest_of_line(); newline(); } else { newline(); } } } m_builder.send_pair(name, value); } } }
void Parser::whitespace() { i = whitespace( i ); }
/** * Tokenise a command line string for an exec function. * * @param a command line string * @return vector suitable for an exec function */ std::vector<char*> parse(const std::string& cmdline) { std::vector<char*> args; bool inquote = false; bool escaped = false; std::string arg; arg.reserve(cmdline.size()); for (size_t i = 0; i != cmdline.size(); ++i) { char c = cmdline[i]; // Handle escaped characters if (escaped) { arg.push_back(escape(c)); escaped = false; continue; } if (c == '\\') { escaped = true; continue; } // Handle quoted characters if (c == '\"') { if (!inquote) { // start quote inquote = true; continue; } // end quote args.push_back(strdup(arg.c_str())); arg.clear(); inquote = false; continue; } if (inquote) { arg.push_back(c); continue; } // Handle whitespace if (whitespace(c) && !arg.empty()) { args.push_back(strdup(arg.c_str())); arg.clear(); continue; } // Everything else: append to arg arg.push_back(c); } if (!arg.empty()) { args.push_back(strdup(arg.c_str())); arg.clear(); } return args; }