Пример #1
0
int main(int argc, char const *argv[])
{
    int *vals[2];
    int n, m, i, j, k;
    int max;
    n = init();
    
    for (i = 0; i < n; ++i) {
        max = 0;
        m = scan_int();
        if (alloc_two_rows(vals, m) == 1)
            return 1;
        
        for (j = 1; j <= m; ++j) {
            for (k = 1; k <= j; ++k)
                vals[1][k] = scan_int() + MAX(vals[0][k-1], vals[0][k]);
            memcpy(&vals[0][1], &vals[1][1], k * sizeof(int));
        }
        
        for (k = 1; k <= m; ++k) {
            if (vals[1][k] > max)
                max = vals[1][k];
        }
        
        if (printf("%d\n", max) < 0)
            return 1;
    }
        
    return 0;
}
Пример #2
0
/**********************************************************************
 * int_read
 *
 * Read an integer value and save it in a variable structure.
 **********************************************************************/
void int_read(VARIABLE *variable, char *string) {
  char *stripped;
  int integer;

  stripped = strip_line (string);
  /* Add the value */
  if (stripped[0] == '+') {
    scan_int(stripped, integer);
    *((int *) variable->address) += integer;
  }
  else if (stripped[0] == '|') {
    scan_int(stripped, integer);
    *((int *) variable->address) = integer | *((int *) variable->address);
  }                              /* Subtract the value */
  else if (stripped[0] == '_') {
    scan_int(stripped, integer);
    *((int *) variable->address) = (~integer) &
      *((int *) variable->address);
  }
  else {
                                 /* Set the value */
    if (stripped[1] == 'x') {
      sscanf (&stripped[2], "%x", &integer);
    }
    else {
      sscanf (stripped, "%d", &integer);
    }
    *((int *) variable->address) = integer;
  }
}
Пример #3
0
void tex::append_penalty ()
	{
	scan_int();
	tail_append(new_penalty(cur_val));
	if (mode == VMODE) 
		build_page();
	}
Пример #4
0
gboolean
scan_bsd_timestamp(const gchar **buf, gint *left, struct tm *tm)
{
  /* RFC 3164 timestamp, expected format: MMM DD HH:MM:SS ... */
  if (!scan_month_abbrev(buf, left, &tm->tm_mon) ||
      !scan_expect_char(buf, left, ' ') ||
      !scan_int(buf, left, 2, &tm->tm_mday) ||
      !scan_expect_char(buf, left, ' ') ||
      !scan_int(buf, left, 2, &tm->tm_hour) ||
      !scan_expect_char(buf, left, ':') ||
      !scan_int(buf, left, 2, &tm->tm_min) ||
      !scan_expect_char(buf, left, ':') ||
      !scan_int(buf, left, 2, &tm->tm_sec))
    return FALSE;
  return TRUE;
}
Пример #5
0
static void parse_setsockopt_name(const char *optname, const char *optval)
{
	unsigned i;

	for (i = 0; socket_options[i].sockopt_name; i++) {
		if (strcasecmp(optname, socket_options[i].sockopt_name))
			continue;

		switch (socket_options[i].sockopt_type) {
		case SVT_BOOL:
			socket_options[i].value = parse_yesno(optname, optval);
			socket_options[i].user_issue++;
		return;
		case SVT_INT:
			if (scan_int(optval, &socket_options[i].value))
				socket_options[i].user_issue++;
			else
				err_msg("%s: unrecognized optval \"%s\" "
					"(integer argument required);skipped",
							optval, optname);
		return;
		case SVT_STR:
			socket_options[i].value_ptr = optval;
			socket_options[i].user_issue++;
		return;
		default:
			err_msg("WARNING: Internal error: unrecognized "
				"sockopt_type (%s %s) (%s:%u)",
				optval, optname, __FILE__, __LINE__);
			return;
		}
	}
	err_msg("Unrecognized sockopt \"%s\" ignored", optname );
}
Пример #6
0
static int init()
{
    #ifdef LOCAL
    f = fopen("sumtrian.in", "r");
    #endif
    
    return scan_int();
}
Пример #7
0
// Case of \multispan; fully expandable
void Parser::multispan()
{
  Token omit = hash_table.locate("omit");
  Token span = hash_table.locate("span");
  int n = scan_int(cur_tok);
  back_input(omit);
  while(n>1) { back_input(span); back_input(omit); --n; }
}
Пример #8
0
gboolean
scan_pix_timestamp(const gchar **buf, gint *left, struct tm *tm)
{
  /* PIX/ASA timestamp, expected format: MMM DD YYYY HH:MM:SS */
  if (!scan_month_abbrev(buf, left, &tm->tm_mon) ||
      !scan_expect_char(buf, left, ' ') ||
      !scan_int(buf, left, 2, &tm->tm_mday) ||
      !scan_expect_char(buf, left, ' ') ||
      !scan_int(buf, left, 4, &tm->tm_year) ||
      !scan_expect_char(buf, left, ' ') ||
      !scan_int(buf, left, 2, &tm->tm_hour) ||
      !scan_expect_char(buf, left, ':') ||
      !scan_int(buf, left, 2, &tm->tm_min) ||
      !scan_expect_char(buf, left, ':') ||
      !scan_int(buf, left, 2, &tm->tm_sec))
    return FALSE;
  tm->tm_year -= 1900;
  return TRUE;
}
Пример #9
0
static int run_scan_int(lua_State * L)
{
    saved_tex_scanner texstate;
    int v = 0;
    save_tex_scanner(texstate);
    scan_int();
    v = cur_val;
    unsave_tex_scanner(texstate);
    lua_pushinteger(L,(int)v);
    return 1;
}
Пример #10
0
// \\cline{3-4} : put a hrule on cells 3 to 4.
void Parser::T_cline()
{
  Token T = cur_tok;
  TokenList arg = mac_arg();
  back_input(hash_table.space_token);
  back_input(arg);
  int a = scan_int(T);
  get_token(); // should be a dash
  int b = scan_int(T);
  b = b-a;
  if(a>0 && b>=0) {
    Xmlp R = the_stack.top_stack()->last_addr();
    if(R) {
      if(R->ok_to_span(a,b,false)) {
	R->ok_to_span(a,b,true);
	return;
      }
    }
    the_stack.add_border(a,b);
  }
}
Пример #11
0
int
main(int argc, char* argv[]) {
  xmlreader r;
  int ret;
  int c;
  int index = 0;
  struct longopt opts[] = {
      {"help", 0, NULL, 'h'},
      {"single-quote", 0, &quote_char, '\''},
      {"double-quote", 0, &quote_char, '"'},
      {"one-line", 0, NULL, 'o'},
      {"compact", 0, NULL, 'c'},
      {"indent", 0, NULL, 'l'},
      {0},
  };

  errmsg_iam(argv[0]);

  for(;;) {
    c = getopt_long(argc, argv, "hsdol:c", opts, &index);
    if(c == -1)
      break;
    if(c == 0)
      continue;

    switch(c) {
      case 'h': usage(argv[0]); return 0;
      case 's': quote_char = '\''; break;
      case 'd': quote_char = '"'; break;
      case 'o': one_line = 1; break;
      case 'c': compact = 1; break;
      case 'l': scan_int(optarg, &indent); break;
      default: usage(argv[0]); return 1;
    }
  }

  if(argc > 1)
    ret = buffer_mmapprivate(&infile, argv[1]);
  else
    ret = buffer_read_fd(&infile, 0);

  if(ret) {
    errmsg_infosys("input");
    return errno == ENOENT ? 127 : 1;
  }

  xml_reader_init(&r, &infile);
  xml_read_callback(&r, xml_read_function);
  buffer_putnlflush(buffer_1);
  buffer_close(&b);

  return 0;
}
Пример #12
0
static int
any_rw_INT(TBUFF **rp, const char *vp, int *value)
{
    if (rp) {
	render_int(rp, *value);
	return TRUE;
    } else if (vp) {
	*value = scan_int(vp);
	return TRUE;
    } else {
	return FALSE;
    }
}
Пример #13
0
void parse_string(char instruction[ ], int size)
{
	int ind;
	int len;	/* length of parameter argument */

	for(int i=0; i<GCODE_COUNT;i++)
		gc.seen[i] = false;

	len=0;
	/* scan the string for commands and parameters, recording the arguments for each,
	 * and setting the seen flag for each that is seen
	 */
	for (ind=0; ind<size; ind += (1+len))
	{
		len = 0;
		switch (instruction[ind])
		{
			case 'G':
					if(gc.GIndex<kMaxGCommands)
						len = scan_int(&instruction[ind+1], &(gc.G[gc.GIndex++]), gc.seen, GCODE_G);
					else
					{
						sprintf(talkToHost.string(), "Too many G codes per line");
						talkToHost.setFatal();
						talkToHost.sendMessage(true);
					}
					break;
			PARSE_INT('M', &instruction[ind+1], len, gc.M, gc.seen, GCODE_M);
			PARSE_INT('T', &instruction[ind+1], len, gc.T, gc.seen, GCODE_T);
			PARSE_INT('L', &instruction[ind+1], len, gc.L, gc.seen, GCODE_L);
			PARSE_FLOAT('S', &instruction[ind+1], len, gc.S, gc.seen, GCODE_S);
			PARSE_FLOAT('P', &instruction[ind+1], len, gc.P, gc.seen, GCODE_P);
			PARSE_FLOAT('X', &instruction[ind+1], len, gc.X, gc.seen, GCODE_X);
			PARSE_FLOAT('Y', &instruction[ind+1], len, gc.Y, gc.seen, GCODE_Y);
			PARSE_FLOAT('Z', &instruction[ind+1], len, gc.Z, gc.seen, GCODE_Z);
			PARSE_FLOAT('I', &instruction[ind+1], len, gc.I, gc.seen, GCODE_I);
			PARSE_FLOAT('J', &instruction[ind+1], len, gc.J, gc.seen, GCODE_J);
			PARSE_FLOAT('F', &instruction[ind+1], len, gc.F, gc.seen, GCODE_F);
			PARSE_FLOAT('R', &instruction[ind+1], len, gc.R, gc.seen, GCODE_R);
			PARSE_FLOAT('Q', &instruction[ind+1], len, gc.Q, gc.seen, GCODE_Q);
			PARSE_FLOAT('E', &instruction[ind+1], len, gc.A, gc.seen, GCODE_E);
			PARSE_FLOAT('A', &instruction[ind+1], len, gc.A, gc.seen, GCODE_A);
			PARSE_FLOAT('B', &instruction[ind+1], len, gc.B, gc.seen, GCODE_B);
			PARSE_LONG('N', &instruction[ind+1], len, gc.N, gc.seen, GCODE_N);
			PARSE_INT('*', &instruction[ind+1], len, gc.Checksum, gc.seen, GCODE_CHECKSUM);
			default:
				break;
		}
	}
}
Пример #14
0
// This is done when we see a \\.
void Parser::T_cr()
{
  flush_buffer();
  int a = 0;
  if(cur_cmd_chr.get_chr() == crwithargs_code)
    a = scan_int(cur_tok);
  if(!the_stack.is_frame(np_cell)) {
    parse_error("bad \\cr");
    return;
  }
  the_stack.finish_cell(0);
  the_stack.push_pop_cell(pop_only);
  pop_level(false,bt_cell);
  the_stack.pop(np_row);
  start_a_row(a);
}
Пример #15
0
static void new_write_whatsit(int w,int check)
{
new_whatsit(cur_chr);
if(check){

scan_limited_int(last_file_selector,NULL);
}else{

scan_int();
if(cur_val<0)
cur_val= term_only;
else if(cur_val> last_file_selector){
cur_val= term_and_log;
}
}
write_stream(tail)= cur_val;
}
Пример #16
0
void scan_pdfrefximage(PDF pdf)
{
    /*tex One could scan transform as well. */
    int transform = 0;
    /*tex Begin of experiment. */
    int open = 0;
    /*tex End of experiment. */
    image_dict *idict;
    /*tex This scans |<rule spec>| to |alt_rule|. */
    scaled_whd alt_rule, dim;
    alt_rule = scan_alt_rule();
    /*tex Begin of experiment. */
    if (scan_keyword("keepopen")) {
        open = 1;
    }
    /*tex End of experiment. */
    scan_int();
    check_obj_type(pdf, obj_type_ximage, cur_val);
    tail_append(new_rule(image_rule));
    idict = idict_array[obj_data_ptr(pdf, cur_val)];
    /*tex Begin of experiment, */
    if (open) {
        /*tex So we keep the original value when no close is given. */
        idict->keepopen = 1;
    }
    /*tex End of experiment. */
    if (img_state(idict) == DICT_NEW) {
        normal_warning("image","don't rely on the image data to be okay");
        width(tail_par) = 0;
        height(tail_par) = 0;
        depth(tail_par) = 0;
    } else {
        if (alt_rule.wd != null_flag || alt_rule.ht != null_flag || alt_rule.dp != null_flag) {
            dim = scale_img(idict, alt_rule, transform);
        } else {
            dim = scale_img(idict, img_dimen(idict), img_transform(idict));
        }
        width(tail_par) = dim.wd;
        height(tail_par) = dim.ht;
        depth(tail_par) = dim.dp;
        rule_transform(tail_par) = transform;
        rule_index(tail_par) = img_index(idict);
    }
}
Пример #17
0
int
var_CHAR(TBUFF **rp, const char *vp)
{
    int status = FALSE;

    if (rp) {
	if (valid_buffer(curbp) && !is_empty_buf(curbp)) {
	    render_int(rp, CharAtDot());
	} else {
	    tb_scopy(rp, error_val);
	}
	status = TRUE;
    } else if (vp) {
	if ((status = check_editable(curbp)) == TRUE) {
	    int c;
	    mayneedundo();
	    (void) ldel_chars(1L, FALSE);	/* delete 1 char */
	    c = scan_int(vp);
	    if ((status = bputc(c)) == TRUE)
		(void) backchar(FALSE, 1);
	}
    }
    return status;
}
Пример #18
0
/* this function parses the date/time portion of an ISODATE */
gboolean
scan_iso_timestamp(const gchar **buf, gint *left, struct tm *tm)
{
  /* YYYY-MM-DDTHH:MM:SS */
  if (!scan_int(buf, left, 4, &tm->tm_year) ||
      !scan_expect_char(buf, left, '-') ||
      !scan_int(buf, left, 2, &tm->tm_mon) ||
      !scan_expect_char(buf, left, '-') ||
      !scan_int(buf, left, 2, &tm->tm_mday) ||
      !scan_expect_char(buf, left, 'T') ||
      !scan_int(buf, left, 2, &tm->tm_hour) ||
      !scan_expect_char(buf, left, ':') ||
      !scan_int(buf, left, 2, &tm->tm_min) ||
      !scan_expect_char(buf, left, ':') ||
      !scan_int(buf, left, 2, &tm->tm_sec))
    return FALSE;
  tm->tm_year -= 1900;
  tm->tm_mon -= 1;
  return TRUE;
}
Пример #19
0
void fscan_recipy(FILE *fp, struct vs_recipy *vs)
{
	char lb[RECIPY_TEXT + RECSYM_SIZE + 1];
	int ret;
	char *r, *val;

	if (fp == NULL)
		return;

	init_vs_recipy(vs);

	while ((r = fgets(lb, RECIPY_TEXT+16, fp)) != NULL) {
		ret = sym_lookup (lb, res_syms, &val);
		if (ret == -2) // commment, skip
			continue;
		if (ret == -1) {
			info_printf("fscan recipy: bad line: %s\n", lb);
			continue;
		}
		switch (ret) {
		case 1:
			scan_string(vs->objname, val, RECIPY_TEXT);
			break;
		case 2:
			scan_string(vs->chart, val, RECIPY_TEXT);
			break;
		case 3:
			scan_string(vs->frame, val, RECIPY_TEXT);
			break;
		case 4:
			scan_double(&(vs->p.r1), val);
			break;
		case 5:
			scan_double(&(vs->p.r2), val);
			break;
		case 6:
			scan_double(&(vs->p.r3), val);
			break;
		case 7:
			scan_int(&(vs->p.quads), val);
			break;
		case 8:
			scan_int(&(vs->p.sky_method), val);
			break;
		case 9:
			scan_double(&(vs->p.sigmas), val);
			break;
		case 10:
			scan_int(&(vs->p.max_iter), val);
			break;
		case 11:
			scan_int(&(vs->usewcs), val);
			break;
		case 12:
			scan_ra(&(vs->ra), val);
			break;
		case 13:
			scan_dec(&(vs->dec), val);
			break;
		case 14:
			ret = radd_std_star(vs, val);
			break;
		case 15:
			ret = radd_pgm_star(vs, val);
			break;
		case 16:
			scan_double(&(vs->p.sat_limit), val);
			break;
		case 17:
			scan_string(vs->repstar, val, RECIPY_TEXT);
			break;
		case 18:
			scan_string(vs->repinfo, val, RECIPY_TEXT);
			break;
		case 19:
			scan_double(&(vs->scint_factor), val);
			break;
		case 20:
			scan_double(&(vs->aperture), val);
			break;
		case 21:
			scan_double(&(vs->airmass), val);
			break;
		};
	}
}
Пример #20
0
void parse_branch_recurse(char *a, ___ b, int *c) {
    __ d=0, e=0, f=0;
    int g=0, h=0, i=0, j, k=0, l=0;
    char m[127];

    if (*a) {
        if (*a == '(') {
            if (1[a] == ')') {
                out_char(&d, 0);
                g = 2;
            } else {
                parse_re_recurse(a + 1, &d, &g);
                if (!g || *(a + g + 1) != ')') die();
                g += 2;
            }
        } else if (*a == '[') {
            if (a[g+1] == '^') { ++g; i = 1; }
            do127(0, (___)m, (___)i, parse_bracket_callback1);
            if (a[g+1] == ']') { ++g; ']'[m] = !i; }
            parse_bracket_recurse(a + 1, &g, m, i);
            do127(0, (___)m, &d, parse_bracket_callback2);
            if (!g || *(a + g + 1) != ']') die();
            g += 2;
        } else if (*a == '\\') {
            if (! 1[a]) die();
            out_char(&d, *(a+1));
            g = 2;
        } else if (*a == '.') {
            do127(1, &d, 0, parse_atom_callback);
            g = 1;
        } else if (*a != '.' && *a != '[' && *a != '(' && *a != ')'
             && *a != '|' && *a != '?' && *a != '{' && *a != '\\') {
            out_char(&d, *a);
            g = 1;
        }
    }
    a += g;

    if (*a) {
        if (*a == '?') {
            ++a;
            ++l;
            ++h;
        } else if (*a == '{') {
            ++a;
            ++h;

            j = scan_int(a, &k, 0);
            if (j) {
                if (k > 255) die();
                h += j;
                a += j;

                if (*a == ',') {
                    ++h;
                    ++a;
                    j = scan_int(a, &l, 0);
                    if (j) {
                        if (l > 255) die();
                        h += j;
                        a += j;
                        if (*a == '}') {
                            ++h;
                            ++a;
                            if (l < k) die();
                        } else die();
                    } else die();
                } else if (*a == '}') {
                    ++h;
                    ++a;
                    l = k;
                } else die();
            } else die();
        }

        if (h) {
            out_multiplex_recurse(k, l, &d, &f);
            walk(d, &d, 0, 0, out_destroy_callback);
            d = f;
        }
        g += h;
    }

    if (! g) return;

    e = malloc(sizeof(_));
    **e = d;
    1[*e] = 0;

    out_append(b, e);

    d = 0;
    *c += g;

    parse_branch_recurse(a, b, c);
}
Пример #21
0
int scan_int(char *a, int *b, int c) {
    int d;
    if (!c[a] || (d = c[a] - '0') >= 10 || d < 0) return c;
    *b = *b * 10 + d;
    return scan_int(a, b, ++c);
}
Пример #22
0
void tex::conditional ()
	{
	bool	b=false;
	sym	s;
	int	m, n;
	ptr	p, q, r;
	int	this_if;
	ptr	save_cond_ptr;
	int	save_scanner_status;

	push_cond();
	save_cond_ptr = cond_ptr;
	this_if = cur_chr;
	switch (this_if) {
		case IF_CHAR_CODE:
		case IF_CAT_CODE:
			
#define get_x_token_or_active_char() {get_x_token(); \
	if (cur_cmd == RELAX && cur_chr == NO_EXPAND_FLAG) { \
		cur_cmd = ACTIVE_CHAR; \
		cur_chr = tok2sym(cur_tok) - active_base[0]; }}

		get_x_token_or_active_char();
		if (cur_cmd > ACTIVE_CHAR || cur_chr > 255) {
			m = RELAX;
			n = 256;
			} 
		else {
			m = cur_cmd;
			n = cur_chr;
			}
		get_x_token_or_active_char();
		if (cur_cmd > ACTIVE_CHAR || cur_chr > 255) {
			cur_cmd = RELAX;
			cur_chr = 256;
		}
		if (this_if == IF_CHAR_CODE) {
			b = n == cur_chr;
		} else {
			b = m == cur_cmd;
		}
		break;
	
	case IF_INT_CODE:
	case IF_DIM_CODE:
		if (this_if == IF_INT_CODE) {
			scan_int();
		} else {
			scan_normal_dimen();
		}
		n = cur_val;
		get_nbx_token(); 
		if (cur_tok >= OTHER_TOKEN + '<'
		&& cur_tok <= OTHER_TOKEN + '>') {
			r = cur_tok - OTHER_TOKEN;
		} else {
			print_err("Missing = inserted for ");
			print_cmd_chr(IF_TEST, this_if);
			help_relation();
			back_error();
			r = '=';
		}
		if (this_if == IF_INT_CODE) {
			scan_int();
		} else {
			scan_normal_dimen();
		}
		switch (r) {
		case '<': b = n < cur_val; break;
		case '=': b = n == cur_val; break; 
		case '>': b = n > cur_val; break;
		}
		break;
	
	case IF_ODD_CODE:
		scan_int();
		b = odd(cur_val);
		break;
	
	case IF_VMODE_CODE:
		b = abs(mode) == VMODE;
		break;

	case IF_HMODE_CODE:
		b = abs(mode) == HMODE;
		break;

	case IF_MMODE_CODE:
		b = abs(mode) == MMODE;
		break;
	
	case IF_INNER_CODE:
		b = mode < 0;
		break;
	
	case IF_VOID_CODE:
	case IF_HBOX_CODE:
	case IF_VBOX_CODE:
		scan_eight_bit_int();
		p = box(cur_val);
		if (this_if == IF_VOID_CODE) {
			b = p == null;
		} else if (p == null) {
			b = FALSE;
		} else if (this_if == IF_HBOX_CODE) {
			b = type(p) == HLIST_NODE;
		} else {
			b = type(p) == VLIST_NODE;
		}
		break;

	case IFX_CODE:
		save_scanner_status = scanner_status;
		scanner_status = NORMAL;
		get_next();
		s = cur_cs;
		p = cur_cmd;
		q = cur_chr;
		get_next(); 
		if (cur_cmd != p) {
			b = FALSE;
		} else if (cur_cmd < CALL) {
			b = cur_chr == q;
		} else {
			p = token_link(cur_chr);
			q = token_link(equiv(s));
			if (p == q) {
				b = TRUE;
			} else {
				while (p != null && q != null) {
					if (token(p) != token(q)) {
						p = null;
					} else {
						p = token_link(p);
						q = token_link(q);
					}
				}
				b = p == null && q == null;
			}
		}
		scanner_status = save_scanner_status;
		break;

	case IF_EOF_CODE:
		scan_four_bit_int();
		b = read_open[cur_val] == CLOSED;
		break;
	
	case IF_TRUE_CODE:
		b = TRUE;
		break;

	case IF_FALSE_CODE:
		b = FALSE;
		break;

	case IF_CASE_CODE: 
		scan_int();
		n = cur_val;
		if (tracing_commands > 1) {
			begin_diagnostic();
			print("{case ");
			print_int(n);
			print("}");
			end_diagnostic(FALSE);
		}
		while (n != 0) {
			pass_text();
			if (cond_ptr == save_cond_ptr) {
				if (cur_chr == OR_CODE) {
					decr(n);
				} else {
					goto common_end;
				}
			} else if (cur_chr == FI_CODE) {
				pop_cond();
			}
		}
		change_if_limit(OR_CODE, save_cond_ptr);
		return;
	
	default:
		break;
	}

	if (tracing_commands > 1) {
		begin_diagnostic();
		print(b ? "{true}" : "{false}");
		end_diagnostic(FALSE);
	}

	if (b) {
		change_if_limit(ELSE_CODE, save_cond_ptr);
		return;
	}

	loop {
		pass_text(); 
		if (cond_ptr == save_cond_ptr) {
			if (cur_chr != OR_CODE)
				goto common_end;
			print_err("Extra ");
			print_esc("or");
			help_or();
			error();
		} else if (cur_chr == FI_CODE) {
			pop_cond();
		}
	}

common_end:
	if (cur_chr == FI_CODE) {
		pop_cond();
	} else {
		if_limit = FI_CODE;
	}
}
Пример #23
0
Файл: lib.c Проект: Tayacan/OSM
static int vxnprintf(char *buf,
		     int size,
		     const char *fmt,
		     va_list ap,
		     int flags)
{
  int written = 0, w, moremods;
  int width, prec;
  char ch, *s;
  unsigned int uarg;
  int arg;

  if (size <= 0) return 0;

  while (written < size) {
    ch = *fmt++;
    if (ch == '\0') break;

    /* normal character => just output it */
    if (ch != '%') {
      printc(buf++, ch, flags);
      written++;
      continue;
    }

    /* to get here, ch == '%' */
    ch = *fmt++;
    if (ch == '\0') break;

    flags &= FLAG_TTY; /*  preserve only the TTY flag */
    width = prec = -1;
    moremods = 1;

    /* read flags and modifiers (width+precision): */
    do {
      switch(ch) {
      case '#': /* alternative output */
        flags |= FLAG_ALT;
        break;

      case '0': /* zero padding */
        flags |= FLAG_ZEROPAD;
        break;

      case ' ': /* space in place of '-' */
        flags |= FLAG_SPACE;
        break;

      case '+': /* '+' in place of '-' */
        flags |= FLAG_SIGN;
        break;

      case '-': /* left align the field */
        flags |= FLAG_LEFT;
        break;

      case '.': /* value precision */
        prec = scan_int(fmt, &fmt);
        break;

      case '1': case '2': case '3': case '4': case '5':
      case '6': case '7': case '8': case '9': /* field width */
        width = scan_int(fmt-1, &fmt);
        break;

      default: /* no more modifiers to scan */
        moremods = 0;
      }

      if (moremods) ch = *fmt++;
    } while (moremods && ch != '\0');


    if (ch == '\0') break;

    /* read the type of the argument : */
    switch(ch) {
    case 'i': /* signed integer */
    case 'd':
      arg = va_arg(ap, int);

      if (arg < 0) { /* negative value, print '-' and negate */
        printc(buf++, '-', flags);
        written++;
        arg = -arg;
      } if (flags & FLAG_SIGN) { /* '+' in place of '-' */
        printc(buf++, '+', flags);
        written++;
      } else if (flags & FLAG_SPACE) { /* ' ' in place of '-' */
        printc(buf++, ' ', flags);
        written++;
      }
      
      w = print_uint(buf, size-written, arg, 10, flags, 0, 0);
      buf += w;
      written += w;
      break;

    case 'o': /* octal integer */
      if (prec < width && (flags & FLAG_ZEROPAD)) prec = width;
      uarg = va_arg(ap, unsigned int);
      w = print_uint(buf, size-written, uarg, 8, flags, prec, width);
      buf += w;
      written += w;
      break;

    case 'u': /* unsigned integer */
      if (prec < width && (flags & FLAG_ZEROPAD)) prec = width;
      uarg = va_arg(ap, unsigned int);
      w = print_uint(buf, size-written, uarg, 10, flags, prec, width);
      buf += w;
      written += w;
      break;

    case 'p': /* memory pointer */
      flags |= FLAG_ALT;
    case 'x': /* hexadecimal integer, noncapitals */
      flags |= FLAG_SMALLS;
    case 'X': /* hexadecimal integer, capitals */

      if (flags & FLAG_ALT) { /* alt form begins with '0x' */
        printc(buf++, '0', flags);
        written++;
        if (written < size) {
          printc(buf++, 'x', flags);
          written++;
        }
        width -= 2;
      }
      if (prec < width && (flags & FLAG_ZEROPAD)) prec = width;

      uarg = va_arg(ap, unsigned int);
      w = print_uint(buf, size-written, uarg, 16, flags, prec, width);
      buf += w;
      written += w;
      break;

    case 'c': /* character */
      arg = va_arg(ap, int);
      printc(buf++, (char)arg, flags);
      written++;
      break;

    case 's': /* string */
      s = va_arg(ap, char*);
      w = size;
      if (prec != -1 && written+prec < size) w = written+prec;
      while (written < w && *s != '\0') {
        printc(buf++, *s++, flags);
        written++;
      }
      break;

    default: /* unknown type, just output */
      printc(buf++, ch, flags);
      written++;
    }
  }
  /* the string was truncated */
  if (written == size) { 
    buf--;
    written = -1;
  }
  printc(buf, '\0', flags); /* terminating zero */

  return written;
}
Пример #24
0
struct skin_element* skin_parse(const char* document, 
                                skin_callback cb, void* cb_data)
{
    callback = cb;
    callback_data = cb_data;
#else
struct skin_element* skin_parse(const char* document)
{
#endif
    struct skin_element* root = NULL;
    struct skin_element* last = NULL;

    const char* cursor = document; /*Keeps track of location in the document*/
    
    skin_line = 1;
    skin_start = (char*)document;
    viewport_line = 0;

    skin_clear_errors();

    while(*cursor != '\0')
    {
        struct skin_element* tree = skin_parse_viewport(&cursor);
        if(!root)
        {
            root = tree;
            last = root;
        }
        else
        {
            last->next = skin_buffer_to_offset(tree);
            last = tree;
        }

        if(!last)
        {
            skin_free_tree(root); /* Clearing any memory already used */
            return NULL;
        }

        /* Making sure last is at the end */
        while(IS_VALID_OFFSET(last->next))
            last = skin_buffer_from_offset(last->next);

    }
    return root;

}

static struct skin_element* skin_parse_viewport(const char** document)
{
    struct skin_element* root = NULL;
    struct skin_element* last = NULL;
    struct skin_element* retval = NULL;

    retval = skin_alloc_element();
    if (!retval)
        return NULL;
    retval->type = VIEWPORT;
    retval->children_count = 1;
    retval->line = skin_line;
    viewport_line = skin_line;

    OFFSETTYPE(struct skin_element*)* children;

    const char* cursor = *document; /* Keeps track of location in the document */
    const char* bookmark; /* Used when we need to look ahead */

    int sublines = 0; /* Flag for parsing sublines */

    /* Parsing out the viewport tag if there is one */
    if(check_viewport(cursor))
    {
        if (!skin_parse_tag(retval, &cursor))
            return NULL;
        if(*cursor == '\n')
        {
            cursor++;
            skin_line++;
        }
    }
#ifdef ROCKBOX
    else if (callback)
    {
        if (callback(retval, callback_data) == CALLBACK_ERROR)
        {
            skin_error(GOT_CALLBACK_ERROR, cursor);
            return NULL;
        }
    }
#endif

    if (check_viewport(cursor))
    {
        retval->children_count = 0;
        *document = cursor;
        return retval;
    }
    retval->children_count = 1;
    children = skin_alloc_children(1);
    if (!children)
        return NULL;
    do
    {

        /* First, we check to see if this line will contain sublines */
        bookmark = cursor;
        sublines = 0;
        while(*cursor != '\n' && *cursor != '\0'
              && !(check_viewport(cursor) && cursor != *document))
        {
            if(*cursor == MULTILINESYM)
            {
                sublines = 1;
                break;
            }
            else if(*cursor == TAGSYM)
            {
                skip_tag(&cursor);
            }
            else if(*cursor == COMMENTSYM)
            {
                skip_comment(&cursor);
            }
            else
            {
                /* Advancing the cursor as normal */
                cursor++;
            }
        }
        cursor = bookmark;

        if(sublines)
        {
            struct skin_element* out = skin_parse_sublines(&cursor);
            if (!root)
            {
                root = out;
                last = root;
            }
            else
            {
                last->next = skin_buffer_to_offset(out);
                last = out;
            }
            if(!last)
                return NULL;
        }
        else
        {
#ifdef ROCKBOX
            /* strip all leading comments */
            while(*cursor == '#')
            {
                skip_comment(&cursor);
                skin_line++;
                
            }
            if (check_viewport(cursor))
                break;
#endif

            struct skin_element* out = skin_parse_line(&cursor);
            if (!root)
            {
                root = out;
                last = root;
            }
            else
            {
                last->next = skin_buffer_to_offset(out);
                last = out;
            }
            if(!last)
                return NULL;

        }
        /* Making sure last is at the end */
        while(IS_VALID_OFFSET(last->next))
            last = skin_buffer_from_offset(last->next);

        if(*cursor == '\n')
        {
            cursor++;
            skin_line++;
        }
#ifdef ROCKBOX
        /* strip all comments */
        while(*cursor == '#')
        {
            skip_comment(&cursor);
            skin_line++;
            
        }
        if (check_viewport(cursor))
            break;
#endif

    }
    while(*cursor != '\0' && !(check_viewport(cursor) && cursor != *document));

    *document = cursor;

    children[0] = skin_buffer_to_offset(root);
    retval->children = skin_buffer_to_offset(children);
    return retval;
}

/* Auxiliary Parsing Functions */

static struct skin_element* skin_parse_line(const char**document)
{
    return skin_parse_line_optional(document, 0);
}

/*
 * If conditional is set to true, then this will break upon encountering
 * SEPARATESYM.  This should only be used when parsing a line inside a
 * conditional, otherwise just use the wrapper function skin_parse_line()
 */
static struct skin_element* skin_parse_line_optional(const char** document,
                                                     int conditional)
{
    const char* cursor = *document;

    struct skin_element* root = NULL;
    struct skin_element* current = NULL;
    struct skin_element* retval = NULL;
    OFFSETTYPE(struct skin_element*)* children = NULL;

    /* A wrapper for the line */
    retval = skin_alloc_element();
    if (!retval)
        return NULL;
    retval->type = LINE;
    retval->line = skin_line;
    while (*cursor == '\t')
        cursor++;

    if(*cursor != '\0' && *cursor != '\n' && *cursor != MULTILINESYM
       && !(conditional && (*cursor == ARGLISTSEPARATESYM
                            || *cursor == ARGLISTCLOSESYM
                            || *cursor == ENUMLISTSEPARATESYM
                            || *cursor == ENUMLISTCLOSESYM)))
    {
        retval->children_count = 1;
    }
    else
    {
        retval->children_count = 0;
    }

    if(retval->children_count > 0)
    {
        children = skin_alloc_children(1);
        if (!children)
            return NULL;
    }

#ifdef ROCKBOX
    if (callback)
    {
        switch (callback(retval, callback_data))
        {
            case CALLBACK_ERROR:
                skin_error(GOT_CALLBACK_ERROR, cursor);
                return NULL;
            default:
                break;
        }
    }
#endif

    while(*cursor != '\n' && *cursor != '\0' && *cursor != MULTILINESYM
          && !((*cursor == ARGLISTSEPARATESYM
                || *cursor == ARGLISTCLOSESYM
                || *cursor == ENUMLISTSEPARATESYM
                || *cursor == ENUMLISTCLOSESYM)
               && conditional)
          && !(check_viewport(cursor) && cursor != *document))
    {
        /* Allocating memory if necessary */
        if(root)
        {
            struct skin_element *next = skin_alloc_element();
            if (!next)
                return NULL;
            current->next = skin_buffer_to_offset(next);
            current = next;
        }
        else
        {
            current = skin_alloc_element();
            if (!current)
                return NULL;
            root = current;
        }

        /* Parsing the current element */
        if(*cursor == TAGSYM && cursor[1] == CONDITIONSYM)
        {
            if(!skin_parse_conditional(current, &cursor))
                return NULL;
        }
        else if(*cursor == TAGSYM && !find_escape_character(cursor[1]))
        {
            if(!skin_parse_tag(current, &cursor))
                return NULL;
        }
        else if(*cursor == COMMENTSYM)
        {
            if(!skin_parse_comment(current, &cursor))
                return NULL;
        }
        else
        {
            if(!skin_parse_text(current, &cursor, conditional))
                return NULL;
        }
    }

    /* Moving up the calling function's pointer */
    *document = cursor;
    
    if(root)
    {
        children[0] = skin_buffer_to_offset(root);
        retval->children = skin_buffer_to_offset(children);
    }
    return retval;
}

static struct skin_element* skin_parse_sublines(const char** document)
{
    return skin_parse_sublines_optional(document, 0);
}

static struct skin_element* skin_parse_sublines_optional(const char** document,
                                                  int conditional)
{
    struct skin_element* retval;
    OFFSETTYPE(struct skin_element*)* children;
    const char* cursor = *document;
    int sublines = 1;
    int i;

    retval = skin_alloc_element();
    if (!retval)
        return NULL;
    retval->type = LINE_ALTERNATOR;
    retval->next = skin_buffer_to_offset(NULL);
    retval->line = skin_line;
    while (*cursor == '\t')
        cursor++;

    /* First we count the sublines */
    while(*cursor != '\0' && *cursor != '\n'
          && !((*cursor == ARGLISTSEPARATESYM
                || *cursor == ARGLISTCLOSESYM
                || *cursor == ENUMLISTSEPARATESYM
                || *cursor == ENUMLISTCLOSESYM)
               && conditional)
          && !(check_viewport(cursor) && cursor != *document))
    {
        if(*cursor == COMMENTSYM)
        {
            skip_comment(&cursor);
        }
        else if(*cursor == TAGSYM)
        {
            skip_tag(&cursor);
        }
        else if(*cursor == MULTILINESYM)
        {
            sublines++;
            cursor++;
        }
        else
        {
            cursor++;
        }
    }

    /* ...and then we parse them */
    retval->children_count = sublines;
    children = skin_alloc_children(sublines);
    if (!children)
        return NULL;

    cursor = *document;
    for(i = 0; i < sublines; i++)
    {
        children[i] = skin_buffer_to_offset(skin_parse_line_optional(&cursor, conditional));
        if (children[i] < 0)
            return NULL;
        skip_whitespace(&cursor);

        if(*cursor != MULTILINESYM && i != sublines - 1)
        {
            skin_error(MULTILINE_EXPECTED, cursor);
            return NULL;
        }
        else if(i != sublines - 1)
        {
            cursor++;
        }
    }

#ifdef ROCKBOX
    if (callback)
    {
        if (callback(retval, callback_data) == CALLBACK_ERROR)
        {
            skin_error(GOT_CALLBACK_ERROR, *document);
            return NULL;
        }
    }
#endif
    *document = cursor;
    retval->children = skin_buffer_to_offset(children);

    return retval;
}

static int skin_parse_tag(struct skin_element* element, const char** document)
{
    const char* cursor = *document + 1;
    const char* bookmark;
    char *open_square_bracket = NULL;

    char tag_name[MAX_TAG_LENGTH];
    char* tag_args;
    const struct tag_info *tag;
    struct skin_tag_parameter* params = NULL;

    int num_args = 1;
    int i;
    int qmark = 0; /* Flag for the all-or-none option */

    int optional = 0;

    /* Checking the tag name */
    for (i=0; cursor[i] && i<MAX_TAG_LENGTH; i++)
        tag_name[i] = cursor[i];

    /* First we check the two characters after the '%', then a single char */
    tag = NULL;
    i = MAX_TAG_LENGTH;
    while (!tag && i > 1)
    {
        tag_name[i-1] = '\0';
        tag = find_tag(tag_name);
        i--;
    }

    if(!tag)
    {
        skin_error(ILLEGAL_TAG, cursor);
        return 0;
    }
    cursor += i;

    /* Copying basic tag info */
    if(element->type != CONDITIONAL && element->type != VIEWPORT)
        element->type = TAG;
    element->tag = tag;
    tag_args = tag->params;
    element->line = skin_line;

    /* Checking for the * flag */
    if(tag_args[0] == '?')
    {
        qmark = 1;
        tag_args++;
    }

    /* If this tag has no arguments, we can bail out now */
    if(strlen(tag_args) == 0
       || (tag_args[0] == '|' && *cursor != ARGLISTOPENSYM)
       || (qmark && *cursor != ARGLISTOPENSYM))
    {
        
#ifdef ROCKBOX
        if (callback)
        {
            if (callback(element, callback_data) == CALLBACK_ERROR)
            {
                skin_error(GOT_CALLBACK_ERROR, cursor);
                return 0;
            }
        }
#endif
        *document = cursor;
        return 1;
    }

    /* Checking the number of arguments and allocating args */
    if(*cursor != ARGLISTOPENSYM && tag_args[0] != '|')
    {
        skin_error(ARGLIST_EXPECTED, cursor);
        return 0;
    }
    else
    {
        cursor++;
    }

    bookmark = cursor;
    while(*cursor != '\n' && *cursor != '\0' && *cursor != ARGLISTCLOSESYM)
    {
        /* Skipping over escaped characters */
        if(*cursor == TAGSYM && *(cursor+1) != ARGLISTSEPARATESYM)
        {
            skip_tag(&cursor);
        }
        else if(*cursor == COMMENTSYM)
        {
            skip_comment(&cursor);
        }
        else if(*cursor == ARGLISTSEPARATESYM)
        {
            num_args++;
            cursor++;
        }
        else
        {
            cursor++;
        }
    }

    cursor = bookmark; /* Restoring the cursor */
    element->params_count = num_args;
    params = skin_alloc_params(num_args);
    if (!params)
        return 0;

    /* Now we have to actually parse each argument */
    for(i = 0; i < num_args; i++)
    {
        char type_code;
        /* Making sure we haven't run out of arguments */
        if(*tag_args == '\0')
        {
            skin_error(TOO_MANY_ARGS, cursor);
            return 0;
        }

        /* Checking for the optional bar */
        if(*tag_args == '|')
        {
            optional = 1;
            tag_args++;
        }

        /* Scanning the arguments */
        skip_whitespace(&cursor);

        /* Checking for comments */
        if(*cursor == COMMENTSYM)
            skip_comment(&cursor);

        if (*tag_args == '[')
        {
            /* we need to guess which type of param it is. 
             * guess using this priority:
             * default > decimal/integer > single tag/code > string
             */
            int j=0;
            bool canbedefault = false, last_char_is_percent = false;
            bool haspercent = false, number = true, hasdecimal = false;
            char temp_params[8];
            open_square_bracket = tag_args;
            tag_args++;
            while (*tag_args != ']')
            {
                if (*tag_args >= 'a' && *tag_args <= 'z')
                    canbedefault = true;
                temp_params[j++] = tolower(*tag_args++);
            }
            temp_params[j] = '\0';
            j = 0;
            while (cursor[j] && cursor[j] != ',' && cursor[j] != ')')
            {
                haspercent = haspercent || (cursor[j] == '%');
                hasdecimal = hasdecimal || (cursor[j] == '.');
                number = number && (isdigit(cursor[j]) || 
                                    (cursor[j] == '.') ||
                                    (cursor[j] == '-') ||
                                    (cursor[j] == '%'));
                j++;
            }
            last_char_is_percent = cursor[j-1] == '%';
            type_code = '?';
            if (canbedefault && *cursor == DEFAULTSYM && !isdigit(cursor[1]))
            {
                type_code = 'i';
            }
            else if (number && hasdecimal && strchr(temp_params, 'd'))
            {
                type_code = 'd';
            }
            else if (number && last_char_is_percent && strchr(temp_params, 'p'))
            {
                type_code = 'p';
            }
            else if (number && 
                     (strchr(temp_params, 'i') || strchr(temp_params, 'd')))
            {
                type_code = strchr(temp_params, 'i') ? 'i' : 'd';
            }
            else if (haspercent && 
                    (strchr(temp_params, 't') || strchr(temp_params, 'c')))
            {
                type_code = strchr(temp_params, 't') ? 't' : 'c';
            }
            else if (strchr(temp_params, 's'))
            {
                type_code = 's';
            }
            if (type_code == '?')
            {
                skin_error(INSUFFICIENT_ARGS, cursor);
                return 0;
            }   
        }
        else
            type_code = *tag_args;
        /* Storing the type code */
        params[i].type_code = type_code;

        /* Checking a nullable argument for null. */
        if(*cursor == DEFAULTSYM && !isdigit(cursor[1]))
        {
            if(islower(type_code))
            {
                params[i].type = DEFAULT;
                cursor++;
            }
            else
            {
                skin_error(DEFAULT_NOT_ALLOWED, cursor);
                return 0;
            }
        }
        else if(tolower(type_code) == 'i')
        {
            /* Scanning an int argument */
            if(!isdigit(*cursor) && *cursor != '-')
            {
                skin_error(INT_EXPECTED, cursor);
                return 0;
            }

            params[i].type = INTEGER;
            params[i].data.number = scan_int(&cursor);
        }
        else if(tolower(type_code) == 'd' || tolower(type_code) == 'p')
        {
            int val = 0;
            bool have_point = false;
            bool have_tenth = false;
            while ( isdigit(*cursor) || *cursor == '.' )
            {
                if (*cursor != '.')
                {
                    val *= 10;
                    val += *cursor - '0';
                    if (have_point)
                    {
                        have_tenth = true;
                        cursor++;
                        break;
                    }
                }
                else
                    have_point = true;
                cursor++;
            }
            if (have_tenth == false)
                val *= 10;
            if (tolower(type_code) == 'd')
                params[i].type = DECIMAL;
            else
            {
                params[i].type = PERCENT;
                cursor++; /* skip trailing % sign */
            }
            params[i].data.number = val;
        }
        else if(tolower(type_code) == 's' || tolower(type_code) == 'f')
        {
            /* Scanning a string argument */
            params[i].type = STRING;
            params[i].data.text = skin_buffer_to_offset(scan_string(&cursor));

        }
        else if(tolower(type_code) == 'c')
        {
            /* Recursively parsing a code argument */
            params[i].type = CODE;
            params[i].data.code = skin_buffer_to_offset(skin_parse_code_as_arg(&cursor));
            if(params[i].data.code < 0)
                return 0;
        }
        else if (tolower(type_code) == 't')
        {
            struct skin_element* child = skin_alloc_element();
            child->type = TAG;
            if (!skin_parse_tag(child, &cursor))
                return 0;
            child->next = skin_buffer_to_offset(NULL);
            params[i].type = CODE;
            params[i].data.code = skin_buffer_to_offset(child);
        }
            

        skip_whitespace(&cursor);

        if(*cursor != ARGLISTSEPARATESYM && i < num_args - 1)
        {
            skin_error(SEPARATOR_EXPECTED, cursor);
            return 0;
        }
        else if(*cursor != ARGLISTCLOSESYM && i == num_args - 1)
        {
            skin_error(CLOSE_EXPECTED, cursor);
            return 0;
        }
        else
        {
            cursor++;
        }

        if (*(tag_args + 1) == '*')
        {
            if (i+1 == num_args)
                tag_args += 2;
            else if (open_square_bracket  && *tag_args == ']')
            {
                tag_args = open_square_bracket;
                open_square_bracket = NULL;
            }
        }
        else
            tag_args++;

        /* Checking for the optional bar */
        if(*tag_args == '|')
        {
            optional = 1;
            tag_args++;
        }
    }
    element->params = skin_buffer_to_offset(params);

    /* Checking for a premature end */
    if(*tag_args != '\0' && !optional)
    {
        skin_error(INSUFFICIENT_ARGS, cursor);
        return 0;
    }
#ifdef ROCKBOX
    if (callback)
    {
        if (callback(element, callback_data) == CALLBACK_ERROR)
        {
            skin_error(GOT_CALLBACK_ERROR, *document);
            return 0;
        }
    }
#endif
    *document = cursor;

    return 1;
}

/*
 * If the conditional flag is set true, then parsing text will stop at an
 * ARGLISTSEPARATESYM.  Only set that flag when parsing within a conditional
 */
static int skin_parse_text(struct skin_element* element, const char** document,
                           int conditional)
{
    const char* cursor = *document;
    int length = 0;
    int dest;
    char *text = NULL;

    /* First figure out how much text we're copying */
    while(*cursor != '\0' && *cursor != '\n' && *cursor != MULTILINESYM
          && *cursor != COMMENTSYM
          && !((*cursor == ARGLISTSEPARATESYM
                || *cursor == ARGLISTCLOSESYM
                || *cursor == ENUMLISTSEPARATESYM
                || *cursor == ENUMLISTCLOSESYM)
               && conditional))
    {
        /* Dealing with possibility of escaped characters */
        if(*cursor == TAGSYM)
        {
            if(find_escape_character(cursor[1]))
                cursor++;
            else
                break;
        }

        length++;
        cursor++;
    }

    cursor = *document;

    /* Copying the text into the element struct */
    element->type = TEXT;
    element->line = skin_line;
    element->next = skin_buffer_to_offset(NULL);
    text = skin_alloc_string(length);
    element->data = skin_buffer_to_offset(text);
    if (element->data < 0)
        return 0;
    
    for(dest = 0; dest < length; dest++)
    {
        /* Advancing cursor if we've encountered an escaped character */
        if(*cursor == TAGSYM)
            cursor++;

        text[dest] = *cursor;
        cursor++;
    }
    text[length] = '\0';
    
#ifdef ROCKBOX
    if (callback)
    {
        if (callback(element, callback_data) == CALLBACK_ERROR)
        {
            skin_error(GOT_CALLBACK_ERROR, *document);
            return 0;
        }
    }
#endif

    *document = cursor;

    return 1;
}

static int skin_parse_conditional(struct skin_element* element, const char** document)
{
    const char* cursor = *document + 1; /* Starting past the "%" */
    const char* bookmark;
    int children = 1;
    int i;
    
#ifdef ROCKBOX
    bool feature_available = true;
    const char *false_branch = NULL;
    const char *conditional_end = NULL;
#endif
    OFFSETTYPE(struct skin_element*)* children_array = NULL;

    /* Some conditional tags allow for target feature checking,
     * so to handle that call the callback as usual with type == TAG
     * then call it a second time with type == CONDITIONAL and check the return
     * value */
    element->type = TAG;
    element->line = skin_line;

    /* Parsing the tag first */
    if(!skin_parse_tag(element, &cursor))
        return 0;

    element->type = CONDITIONAL;
#ifdef ROCKBOX
    if (callback)
    {
        switch (callback(element, callback_data))
        {
            case FEATURE_NOT_AVAILABLE:
                feature_available = false;
                break;
            case CALLBACK_ERROR:
                return 0;
            default:
                break;
        }
    }
#endif
    
    /* Counting the children */
    if(*(cursor++) != ENUMLISTOPENSYM)
    {
        skin_error(ARGLIST_EXPECTED, cursor);
        return 0;
    }
    bookmark = cursor;
    while(*cursor != ENUMLISTCLOSESYM && *cursor != '\0')
    {
        if(*cursor == COMMENTSYM)
        {
            skip_comment(&cursor);
        }
        else if(*cursor == TAGSYM)
        {
            skip_tag(&cursor);
        }
        else if(*cursor == ENUMLISTSEPARATESYM)
        {
            children++;
            cursor++;
            if (*cursor == '\n')
                cursor++;
#ifdef ROCKBOX
            if (false_branch == NULL && !feature_available)
            {
                false_branch = cursor;
                children--;
            }
#endif
        }
        else
        {
            cursor++;
        }
    }
#ifdef ROCKBOX
    if (*cursor == ENUMLISTCLOSESYM && 
        false_branch == NULL && !feature_available)
    {
        false_branch = cursor+1;
        children--;
    }
    if (element->tag->flags&FEATURE_TAG)
    {
        if (feature_available && children > 1)
            children--;
    }
    conditional_end = cursor;
    /* if we are skipping the true branch fix that up */
    cursor = false_branch ? false_branch : bookmark;
#else
    cursor = bookmark;
#endif
    /* Parsing the children */
    
    /* Feature tags could end up having 0 children which breaks
     * the render in dangerous ways. Minor hack, but insert an empty
     * child.  (e.g %?xx<foo> when xx isnt available ) */
    
    if (children == 0)
    {
        const char* emptyline= "";
        children = 1;
        children_array = skin_alloc_children(children);
        if (!children_array)
            return 0;
        element->children_count = children;
        children_array[0] = skin_buffer_to_offset(skin_parse_code_as_arg(&emptyline));
    }
    else
    {    
        children_array = skin_alloc_children(children);
        if (!children_array)
            return 0;
        element->children_count = children;

        for(i = 0; i < children; i++)
        {
            if (*cursor == '\n')
            {
                skin_line++;
                cursor++;
            }
            children_array[i] = skin_buffer_to_offset(skin_parse_code_as_arg(&cursor));
            if (children_array[i] < 0)
                return 0;
            skip_whitespace(&cursor);
#ifdef ROCKBOX
            if ((element->tag->flags&FEATURE_TAG) && feature_available)
                cursor = conditional_end;
#endif

            if(i < children - 1 && *cursor != ENUMLISTSEPARATESYM)
            {
                skin_error(SEPARATOR_EXPECTED, cursor);
                return 0;
            }
            else if(i == children - 1 && *cursor != ENUMLISTCLOSESYM)
            {
                skin_error(CLOSE_EXPECTED, cursor);
                return 0;
            }
            else
            {
                cursor++;
            }
        }
    }
    *document = cursor;
    element->children = skin_buffer_to_offset(children_array);

    return 1;
}

static int skin_parse_comment(struct skin_element* element, const char** document)
{
    const char* cursor = *document;
#ifndef ROCKBOX
    char* text = NULL;
#endif
    int length;
    /*
     * Finding the index of the ending newline or null-terminator
     * The length of the string of interest doesn't include the leading #, the
     * length we need to reserve is the same as the index of the last character
     */
    for(length = 0; cursor[length] != '\n' && cursor[length] != '\0'; length++);

    element->type = COMMENT;
    element->line = skin_line;
#ifdef ROCKBOX 
    element->data = INVALID_OFFSET;
#else    
    element->data = text = skin_alloc_string(length);
    if (!element->data)
        return 0;
    /* We copy from one char past cursor to leave out the # */
    memcpy((void*)text, (void*)(cursor + 1),
           sizeof(char) * (length-1));
    text[length - 1] = '\0';
#endif
    if(cursor[length] == '\n')
        skin_line++;

    *document += (length); /* Move cursor up past # and all text */
    if(**document == '\n')
        (*document)++;

    return 1;
}

static struct skin_element* skin_parse_code_as_arg(const char** document)
{
    int sublines = 0;
    const char* cursor = *document;

    /* Checking for sublines */
    while(*cursor != '\n' && *cursor != '\0'
          && *cursor != ENUMLISTSEPARATESYM && *cursor != ARGLISTSEPARATESYM
          && *cursor != ENUMLISTCLOSESYM && *cursor != ARGLISTCLOSESYM)
    {
        if(*cursor == MULTILINESYM)
        {
            sublines = 1;
            break;
        }
        else if(*cursor == TAGSYM)
        {
            skip_tag(&cursor);
        }
        else
        {
            /* Advancing the cursor as normal */
            cursor++;
        }
    }

    if(sublines)
        return skin_parse_sublines_optional(document, 1);
    else
        return skin_parse_line_optional(document, 1);
}
Пример #25
0
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

#include "internal.h"
#include <limits.h>
#include <errno.h>

unsigned long long strtoull(const char * restrict nptr, char ** restrict endptr, int base) {
    uintmax_t ret = 0;
    int sign = scan_int(nptr, endptr, base, &ret);
    if (sign < 0) {
        errno = -sign;
        return sign == -ERANGE ? ULLONG_MAX : ret;
    }
    return sign ? -ret : ret;
}
Пример #26
0
void loop(void)
{
    char s[2048];
    char file[256];
    int num;

    for (;;)
    {
        if (!fgets(s, 2048, stdin))
        {
            Sleep( 100 );
            continue;
        }
        if (SCAN("uci"))
        {
            printf("id name Irina %s\n", VERSION);
            printf("id author Lucas Monge\n");
            printf("option name Hash type spin min 2 max 1024 default 32");
            printf("option name Personality type combo default Irina var Irina var Steven var Monkey var Donkey var Bull var Wolf var Lion var Rat var Snake var Material var Random var Capture var Advance\n");
            printf("option name Min Time type spin default 0 min 0 max 99\n");
            printf("option name Max Time type spin default 0 min 0 max 99\n");
            printf("uciok\n");
        }
        else if (SCAN("isready"))
        {
            printf("readyok\n");
        }
        else if (SCAN("stop"))
        {
            continue;
        }
        else if (SCAN("quit"))
        {
            break;
        }
        else if (SCAN("fen"))
        {
            board_fen(s);
            printf("%s\n", s);
        }
        else if (SCAN("test"))
        {
            test();
        }
        else if (SCAN("perft file "))
        {
            strcpy(file, s+11);
            strip(file);
            perft_file( file );
        }
        else if (SCAN("perft"))
        {
            num = scan_int(s,"perft");
            perft( num );
        }
        else if (SCAN("ucinewgame"))
        {
            continue;
        }
        else if (SCAN("position"))
        {
            set_position(s);
        }
        else if (SCAN("go"))
        {
            go(s);
        }
        else if (SCAN("setoption name"))
        {
            set_option(s);

        }
    }
}
Пример #27
0
void scan_pdfximage(PDF pdf)
{
    scaled_whd alt_rule;
    image_dict *idict;
    int transform = 0, page = 1, pagebox, colorspace = 0;
    char *named = NULL, *attr = NULL, *file_name = NULL, *user = NULL, *owner = NULL, *visible = NULL;
    alt_rule = scan_alt_rule();
    if (scan_keyword("attr")) {
        scan_toks(false, true);
        attr = tokenlist_to_cstring(def_ref, true, NULL);
        delete_token_ref(def_ref);
    }
    if (scan_keyword("named")) {
        scan_toks(false, true);
        if (0) {
            named = tokenlist_to_cstring(def_ref, true, NULL);
            page = 0;
        } else {
            normal_warning("pdf backend","named pages are not supported, using page 1");
            page = 1;
        }
        delete_token_ref(def_ref);
    } else if (scan_keyword("page")) {
        scan_int();
        page = cur_val;
    }
    if (scan_keyword("userpassword")) {
        scan_toks(false, true);
        user = tokenlist_to_cstring(def_ref, true, NULL);
        delete_token_ref(def_ref);
    }
    if (scan_keyword("ownerpassword")) {
        scan_toks(false, true);
        owner = tokenlist_to_cstring(def_ref, true, NULL);
        delete_token_ref(def_ref);
    }
    if (scan_keyword("visiblefilename")) {
        scan_toks(false, true);
        visible = tokenlist_to_cstring(def_ref, true, NULL);
        delete_token_ref(def_ref);
    }
    if (scan_keyword("colorspace")) {
        scan_int();
        colorspace = cur_val;
    }
    pagebox = scan_pdf_box_spec();
    if (pagebox == PDF_BOX_SPEC_NONE) {
        pagebox = pdf_pagebox;
        if (pagebox == PDF_BOX_SPEC_NONE)
            pagebox = PDF_BOX_SPEC_CROP;
    }
    scan_toks(false, true);
    file_name = tokenlist_to_cstring(def_ref, true, NULL);
    if (file_name == NULL) {
        normal_error("pdf backend","no image filename given");
    }
    delete_token_ref(def_ref);
    idict = read_image(file_name, page, named, colorspace, pagebox, user, owner, visible);
    img_attr(idict) = attr;
    img_dimen(idict) = alt_rule;
    img_transform(idict) = transform;
    last_saved_image_index = img_objnum(idict);
    last_saved_image_pages = img_totalpages(idict);
}
Пример #28
0
static void do_extension_pdf(int immediate)
{
int i;

if(scan_keyword("literal")){
new_whatsit(pdf_literal_node);
if(scan_keyword("direct"))
set_pdf_literal_mode(tail,direct_always);
else if(scan_keyword("page"))
set_pdf_literal_mode(tail,direct_page);
else
set_pdf_literal_mode(tail,set_origin);
scan_toks(false,true);
set_pdf_literal_type(tail,normal);
set_pdf_literal_data(tail,def_ref);
}else if(scan_keyword("dest")){
scan_pdfdest(static_pdf);
}else if(scan_keyword("annot")){
scan_annot(static_pdf);
}else if(scan_keyword("save")){
new_whatsit(pdf_save_node);
}else if(scan_keyword("restore")){
new_whatsit(pdf_restore_node);
}else if(scan_keyword("setmatrix")){
new_whatsit(pdf_setmatrix_node);
scan_toks(false,true);
set_pdf_setmatrix_data(tail,def_ref);
}else if(scan_keyword("obj")){
scan_obj(static_pdf);
if(immediate){
if(obj_data_ptr(static_pdf,pdf_last_obj)==0)
normal_error("pdf backend","\\pdfextension obj 'reserveobjnum' cannot be used with \\immediate");
pdf_write_obj(static_pdf,pdf_last_obj);
}
}else if(scan_keyword("refobj")){
scan_refobj(static_pdf);
}else if(scan_keyword("colorstack")){
scan_int();
if(cur_val>=colorstackused()){
print_err("Unknown color stack number ");
print_int(cur_val);
help3
("Allocate and initialize a color stack with \\pdfextension colorstackinit.",
"I'll use default color stack 0 here.",
"Proceed, with fingers crossed.");
error();
cur_val= 0;
}
if(cur_val<0){
print_err("Invalid negative color stack number");
help2("I'll use default color stack 0 here.",
"Proceed, with fingers crossed.");
error();
cur_val= 0;
}
if(scan_keyword("set"))
i= colorstack_set;
else if(scan_keyword("push"))
i= colorstack_push;
else if(scan_keyword("pop"))
i= colorstack_pop;
else if(scan_keyword("current"))
i= colorstack_current;
else
i= -1;
if(i>=0){
new_whatsit(pdf_colorstack_node);
set_pdf_colorstack_stack(tail,cur_val);
set_pdf_colorstack_cmd(tail,i);
set_pdf_colorstack_data(tail,null);
if(i<=colorstack_data){
scan_toks(false,true);
set_pdf_colorstack_data(tail,def_ref);
}
}else{
print_err("Color stack action is missing");
help3("The expected actions for \\pdfextension colorstack:",
"    set, push, pop, current",
"I'll ignore the color stack command.");
error();
}
}else if(scan_keyword("startlink")){
scan_startlink(static_pdf);
}else if(scan_keyword("endlink")){
if(abs(mode)==vmode)
normal_error("pdf backend","\\pdfextension endlink cannot be used in vertical mode");
new_whatsit(pdf_end_link_node);
}else if(scan_keyword("startthread")){
new_annot_whatsit(pdf_start_thread_node);
scan_thread_id();
}else if(scan_keyword("endthread")){
new_whatsit(pdf_end_thread_node);
}else if(scan_keyword("thread")){
new_annot_whatsit(pdf_thread_node);
scan_thread_id();
}else if(scan_keyword("outline")){
scan_pdfoutline(static_pdf);
}else if(scan_keyword("glyphtounicode")){
glyph_to_unicode();
}else if(scan_keyword("catalog")){
scan_pdfcatalog(static_pdf);
}else if(scan_keyword("fontattr")){





scan_font_ident();
i= cur_val;
if(i==null_font)
normal_error("pdf backend","invalid font identifier");
scan_toks(false,true);
set_pdf_font_attr(i,tokens_to_string(def_ref));
if(str_length(pdf_font_attr(i))==0){
flush_str((str_ptr-1));
set_pdf_font_attr(i,0);
}
}else if(scan_keyword("mapfile")){
scan_toks(false,true);
pdfmapfile(def_ref);
delete_token_ref(def_ref);
}else if(scan_keyword("mapline")){
scan_toks(false,true);
pdfmapline(def_ref);
delete_token_ref(def_ref);
}else if(scan_keyword("includechars")){
pdf_include_chars(static_pdf);
}else if(scan_keyword("info")){
scan_toks(false,true);
pdf_info_toks= concat_tokens(pdf_info_toks,def_ref);
}else if(scan_keyword("names")){
scan_toks(false,true);
pdf_names_toks= concat_tokens(pdf_names_toks,def_ref);
}else if(scan_keyword("trailer")){
scan_toks(false,true);
pdf_trailer_toks= concat_tokens(pdf_trailer_toks,def_ref);
}else{
tex_error("unexpected use of \\pdfextension",null);
}
}
Пример #29
0
std::string string_format(const char* fmt, int numargs, FormatArg const * const args[]) {
	std::string out;
	const char *c = fmt;
	while (*c) {
		while (*c && *c != '%') ++c;
		if (c != fmt) out.append(fmt, c - fmt);
		fmt = c;

		if (*c == '%') {
			++c;
			if (*c == '%') {
				fmt = c;
				++c;
			} else {
				int argid = -1;
				const char* identBegin = c;
				const char* identEnd = c;

				// parse and match reference
				if (isdigit(*c)) {
					c = identEnd = scan_int(identBegin = c, argid);
				} else {
					if (*c == '{') {
						identBegin = ++c;
						while (*c && (*c != '}')) ++c;
						identEnd = c;
						if (*c == '}')
							++c;
						else {
							out.append("%(err: unfinished reference)");
							goto bad_reference;
						}
					} else if (isalpha(*c) || (*c == '_')) {
						c = identEnd = scan_ident(identBegin = c);
					} else {
						out.append("%(err: unfinished reference)");
						goto bad_reference;
					}

					if (identBegin == identEnd) {
						out.append("%(err: blank reference)");
						goto bad_reference;
					}

					for (int i = 0; i < numargs; ++i) {
						size_t identLen = (identEnd - identBegin);
						if (args[i]->name
							&& (strncmp(args[i]->name, identBegin, identLen) == 0)
							&& (args[i]->name[identLen] == '\0')) {
							argid = i;
							break;
						}
					}
				}

				if (argid >= 0 && argid < numargs) {
					const FormatArg& arg = *args[argid];
					const char* fmtBegin = 0;
					const char* fmtEnd = 0;
					// scan format specifier, if provided
					if (*c == '{') {
						++c;
						if (!*c) {
							out.append("%(err: unfinished format)");
							goto bad_reference;
						}

						c = fmtEnd = scan_bracetext(fmtBegin = c);

						if (fmtBegin == fmtEnd) {
							fmtBegin = fmtEnd = 0;
						}

						if (!*c) {
							out.append("%(err: unfinished format)");
							goto bad_reference;
						} else
							++c;
					}

					if (fmtBegin) {
						assert(fmtEnd > fmtBegin);
						FormatSpec fspec(fmtBegin, fmtEnd - fmtBegin);
						out.append(arg.format(fspec));
					} else if (arg.defaultformat) {
						FormatSpec fspec(arg.defaultformat);
						out.append(arg.format(fspec));
					} else
						out.append(arg.format(FormatSpec()));

				} else {
					out.append("%(err: unknown arg '");
					out.append(identBegin, identEnd - identBegin);
					out.append("')");
					goto bad_reference;
				}

bad_reference:
				fmt = c;
			}
		}
	}
	// append the final range
	if (c != fmt)
		out.append(fmt, c - fmt);
	return out;
}
Пример #30
0
int yylex(void) {
	int status;
	
#ifdef DEBUG
	printf("yylex is called\n"
		"  first_line:   %d\n"
		"  first_column: %d\n"
		"  last_line:    %d\n"
		"  last_column:  %d\n",
		yylloc.first_line,
		yylloc.first_column,
		yylloc.last_line,
		yylloc.last_column);
#endif
	
	skip_white_space:
	while(*src == ' ' || *src == '\t') {
		++yylloc.last_column;
		++src;
	}
	
	/* skip comments */
	if(*src == ';') {
		while(*src != '\n' && *src != 0) {
			++yylloc.last_column;
			++src;
		}
	}
	
	/* when a newline appears, update yylloc accordingly and start to skip
	whitespace again */
	if(*src == '\n') {
		++yylloc.last_line;
		yylloc.last_column = 1;
		++src;
		goto skip_white_space;
	}
	
	yylloc.first_line = yylloc.last_line;
	yylloc.first_column = yylloc.last_column;
	
	status = scan_multibyte_operator();
	if(status != 0)
		return status;
	
	status = scan_int();
	if(status != 0)
		return status;
	
	status = scan_string();
	if(status != 0)
		return status;
	
	status = scan_special_identifier();
	if(status != 0)
		return status;
	
	status = scan_identifier();
	if(status != 0)
		return status;
	
	/* Return a single char or, when end of string, 0 */
	++yylloc.last_column;
#ifdef DEBUG
	if(*src == 0)
		printf("yylex returns EOF\n");
	else
		printf("yylex returns '%c'\n", *src);
#endif
	return *src++;
}