/*
 * This file contains the code necessary to fake out the rest
 * of the runtime into thinking that we actually do have primitive
 * classes.
 */
/*
  This file is part of Japhar, the GNU Virtual Machine for Java Bytecodes.
  Japhar is a project of The Hungry Programmers, GNU, and OryxSoft.

  Copyright (C) 1998, 1999 The Hungry Programmers

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "jni.h"
#include "ClazzFile.h"
#include "log.h"
#include "resolve.h"
#include "arrays.h"
#include "objects.h"
#include "primitive-class.h"
#include "class-repository.h"

#include <string.h>
#include <stdlib.h>

#define MYLOG "PrimitiveClass"

static ClassConstant superclass_constant = {
  CONSTANT_Class,
  2
};

#define JAVA_LANG_OBJECT "java/lang/Object"

static Utf8Constant object_name_constant = {
  CONSTANT_Utf8,
  sizeof(JAVA_LANG_OBJECT)-1, /* strlen(...) */
  NULL
};

jclass
createFakePrimitiveClass(JNIEnv *env, char *class_name)
{
  ClazzFile *clazz = find_class_in_repository(env, class_name);

  /* we've already created it. */
  if (clazz)
    return clazzfile_to_jclass(env, clazz);

  JAVARLOG1(MYLOG, 1, "creating primitive class %s\n",
	    class_name);

  clazz = (ClazzFile*)calloc(1, sizeof(ClazzFile));

  clazz->access_flags = ACC_PRIMITIVE | ACC_PUBLIC;
  clazz->constant_pool_count = 4;
  clazz->superclass_index = 1;
  clazz->superclass = (ClazzFile*)find_class(env, JAVA_LANG_OBJECT);
  clazz->class_name = strdup(class_name);
  clazz->initialization_state = CLASS_INIT_FINISHED;

  clazz->constants = (ConstantPoolEntry*)calloc(3, sizeof(ConstantPoolEntry));
  clazz->constants[1].clazz_info = superclass_constant;
  clazz->constants[2].utf8_info = object_name_constant;
  clazz->constants[2].utf8_info.bytes = (u1*)strdup(JAVA_LANG_OBJECT);

  clazz->num_fields = 0;
  clazz->num_instance_fields = 0;

  clazz->nesting_level = 1;

  calculate_instance_field_offsets(env, clazz);

  JAVARLOG0(MYLOG, 1, "  adding primitive class to repository\n");

  add_class_to_repository(env, clazz, class_name);

  return clazzfile_to_jclass(env, clazz);
}
