Ejemplo n.º 1
0
// new Function([arg1[, arg2[, ...]],] functionBody)
js_val *
func_new(js_val *instance, js_args *args, eval_state *state)
{
  unsigned arglen = ARGLEN(args);
  unsigned i = 0;
  char *arg_lst = NULL;
  char *tmp;

  for (i = 0; arglen > 0 && i < (arglen - 1); i++) {
    if (!arg_lst) {
      arg_lst = TO_STR(ARG(args, i))->string.ptr;
    }
    else {
      tmp = arg_lst;
      arg_lst = fh_str_concat(arg_lst, ", ");
      free(tmp);
      tmp = arg_lst;
      arg_lst = fh_str_concat(arg_lst, TO_STR(ARG(args, i))->string.ptr);
      free(tmp);
    }
  }

  if (arglen <= 1)
    arg_lst = "";

  char *body = arglen > 0 ? TO_STR(ARG(args, i))->string.ptr : "";
  char *fmt = "(function(%s) { %s });";

  int size = snprintf(NULL, 0, fmt, arg_lst, body) + 1;
  char *func_def = malloc(size);
  snprintf(func_def, size, fmt, arg_lst, body);

  return fh_eval_string(func_def, state->ctx);
}
Ejemplo n.º 2
0
// Error.prototype.toString()
js_val *
error_proto_to_string(js_val *instance, js_args *args, eval_state *state)
{
  if (!IS_OBJ(instance))
    fh_error(state, E_TYPE, "Error.prototype.toString called on a non-object");

  js_val *name_prop = fh_get_proto(instance, "name");
  js_val *msg_prop = fh_get_proto(instance, "message");
  js_val *name = IS_UNDEF(name_prop) ? JSSTR("Error") : TO_STR(name_prop);
  js_val *msg = IS_UNDEF(msg_prop) ? JSSTR("") : TO_STR(msg_prop);

  if (strlen(name->string.ptr) == 0) return msg;
  if (strlen(msg->string.ptr) == 0) return name;
  return JSSTR(fh_str_concat(fh_str_concat(name->string.ptr, ": "), msg->string.ptr));
}