JCC-3.6/0000755000076500000000000000000013536235634012176 5ustar vajdawheel00000000000000JCC-3.6/PKG-INFO0000644000076500000000000000554613536235634013305 0ustar vajdawheel00000000000000Metadata-Version: 1.1 Name: JCC Version: 3.6 Summary: a C++ code generator for calling Java from C++/Python Home-page: UNKNOWN Author: Andi Vajda Author-email: vajda@apache.org License: UNKNOWN Description: For changes since earlier releases, see: http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc/CHANGES JCC is a C++ code generator for producing the code necessary to call into Java classes from CPython via Java's Native Invocation Interface (JNI). JCC generates C++ wrapper classes that hide all the gory details of JNI access as well Java memory and object reference management. JCC generates CPython types that make these C++ classes accessible from a Python interpreter. JCC attempts to make these Python types pythonic by detecting iterators and property accessors. Iterators and mappings may also be declared to JCC. JCC has been built on Python 2.3 to 2.7, on Python 3.6, and has been used with various Java Runtime Environments such as Sun Java 1.5 and 1.6, Apple's Java 1.5 and 1.6 on Mac OS X, open source Java OpenJDK 1.7 builds as well as Oracle Java 1.7 and 1.8. JCC is supported on Mac OS X, Linux, Solaris and Windows. JCC is written in C++ and Python. It uses Java's reflection API to do its job and needs a Java Runtime Environment to be present to operate. JCC is built with distutils or setuptools:: python setup.py build sudo python setup.py install Setuptools is required to build JCC on Python 2.3. JCC's setup.py file needs to be edited before building JCC to specify the location of the Java Runtime Environment's header files and libraries. The svn sources for JCC are available at: http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc/ For more information about JCC see: http://lucene.apache.org/pylucene/jcc/index.html JCC comes with an Apache 2.0 copyright license: http://www.apache.org/licenses/LICENSE-2.0 Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: C++ Classifier: Programming Language :: Java Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Software Development :: Code Generators Classifier: Topic :: Software Development :: Libraries :: Java Libraries JCC-3.6/INSTALL0000644000076500000000000000007713240635267013231 0ustar vajdawheel00000000000000 Please see http://lucene.apache.org/pylucene/jcc/install.html JCC-3.6/helpers2/0000755000076500000000000000000013536235634013722 5ustar vajdawheel00000000000000JCC-3.6/helpers2/build.py0000644000076500000000000000277113063044246015372 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from distutils.command.build_py import build_py from distutils import log class jcc_build_py(build_py): config_text = None config_file = None def run(self): self.write_jcc_config() return build_py.run(self) def write_jcc_config(self): # only write jcc's config.py file if it doesn't exist or a build # command is given write = False if not os.path.isfile(self.config_file): write = True else: for command in self.distribution.commands: if command.startswith("build"): write = True break if write: log.info("writing %s" %(self.config_file)) config = open(self.config_file, 'w') try: config.write(self.config_text) finally: config.close() else: log.info("not writing %s" %(self.config_file)) JCC-3.6/helpers2/mingw32.py0000644000076500000000000000371213063044246015555 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, copy from distutils.cygwinccompiler import Mingw32CCompiler class JCCMinGW32CCompiler(Mingw32CCompiler): def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # use separate copies, so we can modify the lists extra_preargs = copy.copy(extra_preargs or []) (dll_name, dll_extension) = os.path.splitext(output_filename) if dll_extension.lower() == ".dll": extra_preargs.extend(["-Wl,--out-implib,%s" %(os.path.join(os.path.dirname(dll_name), "jcc", "jcc.lib"))]) Mingw32CCompiler.link(self, target_desc=target_desc, objects=objects, output_filename=output_filename, output_dir=output_dir, libraries=libraries, library_dirs=library_dirs, runtime_library_dirs=runtime_library_dirs, export_symbols=export_symbols, debug=debug, extra_preargs=extra_preargs, extra_postargs=extra_postargs, build_temp=build_temp, target_lang=target_lang) JCC-3.6/helpers2/__init__.py0000644000076500000000000000002213063044246016015 0ustar vajdawheel00000000000000# helpers package JCC-3.6/helpers2/darwin.py0000644000076500000000000000504113063044246015550 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys, os global JAVAHOME, JAVAFRAMEWORKS JAVAHOME = None JAVAFRAMEWORKS = None if sys.platform == "darwin": # figure out where the JDK lives from subprocess import Popen, PIPE try: args = ['/usr/libexec/java_home'] process = Popen(args, stdout=PIPE, stderr=PIPE) except Exception, e: print >>sys.stderr, "%s: %s" %(e, args) else: process.wait() if process.returncode == 0: _path = process.stdout.read().strip() if os.path.exists(os.path.join(_path, "include", "jni.h")): JAVAHOME = _path print >>sys.stderr, 'found JAVAHOME =', JAVAHOME else: print >>sys.stderr, process.stderr.read() # figure out where the JDK Frameworks lives import platform, re _os_version = re.match("[0-9]+\.[0-9]+", platform.mac_ver()[0]).group(0) # this is where Apple says we should look for headers _path = "/System/Library/Frameworks/JavaVM.framework" if os.path.exists(os.path.join(_path, "Headers", "jni.h")): JAVAFRAMEWORKS = _path print >>sys.stderr, 'found JAVAFRAMEWORKS =', JAVAFRAMEWORKS else: # but their updates don't always match their documentation, # so look up the same path in the OS's /Developer tree _path = "/Developer/SDKs/MacOSX%s.sdk%s" %(_os_version, _path) if os.path.exists(os.path.join(_path, "Headers", "jni.h")): JAVAFRAMEWORKS = _path print >>sys.stderr, 'found JAVAFRAMEWORKS =', JAVAFRAMEWORKS # monkeypatch customize_compiler so that we can remove -Wl,-x from LDSHARED # set in setuptools.command.build_ext.build_ext.setup_shlib_compiler from distutils.sysconfig import customize_compiler, get_config_vars def _customize_compiler(compiler): get_config_vars()['LDSHARED'] = "gcc -dynamiclib -undefined dynamic_lookup" customize_compiler(compiler) from distutils import sysconfig sysconfig.customize_compiler = _customize_compiler JCC-3.6/helpers2/windows.py0000644000076500000000000000356513063044246015767 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys global JAVAHOME JAVAHOME = None if sys.platform == "win32": # figure out where the JDK lives try: import _winreg as wreg class WindowsRegistry: # see the Python Cookbook, #146305, Dirk Holtwick def __init__(self, keyname): " handle registry access " self.reg = wreg.ConnectRegistry(None, wreg.HKEY_LOCAL_MACHINE) self.key = wreg.OpenKey(self.reg, keyname) def get(self, name): " get value out of registry " v, t = wreg.QueryValueEx(self.key, name) return v, t def close(self): " close the key finally " if hasattr(self, 'key'): self.key.Close() if hasattr(self, 'reg'): self.reg.Close() def __del__(self): self.close() def get_registry_value(vname, subname): r = WindowsRegistry(vname) v, t = r.get(subname) return v javaversion = get_registry_value(r"SOFTWARE\JavaSoft\Java Development Kit", "CurrentVersion") JAVAHOME = get_registry_value(r"SOFTWARE\JavaSoft\Java Development Kit\%s" % javaversion, "JavaHome") except: JAVAHOME = 'c:/Program Files/Java/jdk1.6.0_18' JCC-3.6/helpers2/linux.py0000644000076500000000000001263313240641243015425 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys, os, os.path, re import distutils, setuptools from setuptools import dist, extension from setuptools.command import build_ext from setuptools.extension import Library as _Library def patch_st_dir(patch_version, st_egg, jccdir): return ''' Shared mode is disabled, setuptools patch.43.%s must be applied to enable it or the NO_SHARED environment variable must be set to turn off this error. sudo patch -d %s -Nup0 < %s/jcc2/patches/patch.43.%s See %s/INSTALL for more information about shared mode. ''' %(patch_version, st_egg, jccdir, patch_version, jccdir) def patch_st_zip(patch_version, st_egg, jccdir): return ''' Shared mode is disabled, setuptools patch.43.%s must be applied to enable it or the NO_SHARED environment variable must be set to turn off this error. mkdir tmp cd tmp unzip -q %s patch -Nup0 < %s/jcc2/patches/patch.43.%s sudo zip %s -f cd .. rm -rf tmp See %s/INSTALL for more information about shared mode. ''' %(patch_version, st_egg, jccdir, patch_version, st_egg, jccdir) def patch_setuptools(with_setuptools): try: from setuptools.command.build_ext import sh_link_shared_object enable_shared = True # jcc2/patches/patch.43 was applied except ImportError: jccdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) st_egg = os.path.dirname(setuptools.__path__[0]) setuptools.Library = LinuxLibrary extension.Library = LinuxLibrary build_ext.build_ext = LinuxBuildExt if build_ext.use_stubs: # Build shared libraries. global sh_link_shared_object # Fix UnboundLocalError build_ext.link_shared_object = sh_link_shared_object else: # Build static libraries every where else (unless forced) build_ext.libtype = 'static' build_ext.link_shared_object = st_link_shared_object print >>sys.stderr, "Applied shared mode monkey patch to:", setuptools return True # monkey patch was applied return enable_shared class LinuxLibrary(_Library): def __init__(self, *args, **kwds): self.force_shared = kwds.pop('force_shared', False) extension.Extension.__init__(self, *args, **kwds) class LinuxBuildExt(build_ext.build_ext): def get_ext_filename(self, fullname): filename = build_ext._build_ext.get_ext_filename(self, fullname) if fullname in self.ext_map: ext = self.ext_map[fullname] if isinstance(ext, _Library): if ext.force_shared and not build_ext.use_stubs: libtype = 'shared' else: libtype = build_ext.libtype fn, ext = os.path.splitext(filename) return self.shlib_compiler.library_filename(fn, libtype) elif build_ext.use_stubs and ext._links_to_dynamic: d, fn = os.path.split(filename) return os.path.join(d, 'dl-' + fn) return filename def build_extension(self, ext): _compiler = self.compiler try: force_shared = False if isinstance(ext, _Library): self.compiler = self.shlib_compiler force_shared = ext.force_shared and not build_ext.use_stubs if force_shared: self.compiler.link_shared_object = sh_link_shared_object.__get__(self.compiler) build_ext._build_ext.build_extension(self, ext) if ext._needs_stub: self.write_stub(self.get_finalized_command('build_py').build_lib, ext) finally: if force_shared: self.compiler.link_shared_object = build_ext.link_shared_object.__get__(self.compiler) self.compiler = _compiler def sh_link_shared_object(self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): self.link(self.SHARED_LIBRARY, objects, output_libname, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols, debug, extra_preargs, extra_postargs, build_temp, target_lang) def st_link_shared_object(self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): assert output_dir is None # distutils build_ext doesn't pass this output_dir, filename = os.path.split(output_libname) basename, ext = os.path.splitext(filename) if self.library_filename("x").startswith('lib'): # strip 'lib' prefix; this is kludgy if some platform uses # a different prefix basename = basename[3:] self.create_static_lib(objects, basename, output_dir, debug, target_lang) JCC-3.6/_jcc2/0000755000076500000000000000000013536235634013156 5ustar vajdawheel00000000000000JCC-3.6/_jcc2/boot.cpp0000644000076500000000000000316013063024530014607 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "java/lang/Class.h" #include "java/lang/RuntimeException.h" #include "macros.h" extern PyTypeObject PY_TYPE(JObject), PY_TYPE(ConstVariableDescriptor); PyObject *initJCC(PyObject *module); PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds); namespace java { namespace lang { void __install__(PyObject *m); } namespace io { void __install__(PyObject *m); } } PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds) { PyObject *env = initVM(module, args, kwds); if (env == NULL) return NULL; java::lang::Class::initializeClass(false); java::lang::RuntimeException::initializeClass(false); return env; } #include "jccfuncs.h" extern "C" { void init_jcc2(void) { PyObject *m = Py_InitModule3("_jcc2", jcc_funcs, "_jcc2"); initJCC(m); INSTALL_TYPE(JObject, m); INSTALL_TYPE(ConstVariableDescriptor, m); java::lang::__install__(m); java::io::__install__(m); } } JCC-3.6/_jcc2/java/0000755000076500000000000000000013536235634014077 5ustar vajdawheel00000000000000JCC-3.6/_jcc2/java/util/0000755000076500000000000000000013536235634015054 5ustar vajdawheel00000000000000JCC-3.6/_jcc2/java/util/Iterator.cpp0000644000076500000000000000720713063017611017343 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/util/Iterator.h" namespace java { namespace util { enum { mid_hasNext, mid_next, max_mid }; Class *Iterator::class$ = NULL; jmethodID *Iterator::mids$ = NULL; jclass Iterator::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/util/Iterator"); mids$ = new jmethodID[max_mid]; mids$[mid_hasNext] = env->getMethodID(cls, "hasNext", "()Z"); mids$[mid_next] = env->getMethodID(cls, "next", "()Ljava/lang/Object;"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } jboolean Iterator::hasNext() const { return env->callBooleanMethod(this$, mids$[mid_hasNext]); } Object Iterator::next() const { return Object(env->callObjectMethod(this$, mids$[mid_next])); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace util { static PyObject *t_Iterator_hasNext(t_Iterator *self); static PyObject *t_Iterator_next(t_Iterator *self); static PyMethodDef t_Iterator__methods_[] = { DECLARE_METHOD(t_Iterator, hasNext, METH_NOARGS), DECLARE_METHOD(t_Iterator, next, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Iterator, t_Iterator, JObject, java::util::Iterator, abstract_init, 0, 0, 0, 0, 0); #ifdef _java_generics PyObject *t_Iterator::wrap_Object(const Iterator& object, PyTypeObject *T) { PyObject *obj = t_Iterator::wrap_Object(object); if (obj != Py_None) { t_Iterator *self = (t_Iterator *) obj; self->parameters[0] = T; } return obj; } PyObject *t_Iterator::wrap_jobject(const jobject& object, PyTypeObject *T) { PyObject *obj = t_Iterator::wrap_jobject(object); if (obj != Py_None) { t_Iterator *self = (t_Iterator *) obj; self->parameters[0] = T; } return obj; } #endif static PyObject *t_Iterator_hasNext(t_Iterator *self) { jboolean b; OBJ_CALL(b = self->object.hasNext()); Py_RETURN_BOOL(b); } static PyObject *t_Iterator_next(t_Iterator *self) { Object next((jobject) NULL); OBJ_CALL(next = self->object.next()); return t_Object::wrap_Object(next); } } } JCC-3.6/_jcc2/java/util/Enumeration.h0000644000076500000000000000362613063017611017506 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Enumeration_H #define _Enumeration_H #include #include "JObject.h" namespace java { namespace lang { class Class; class Object; } namespace util { using namespace java::lang; class Enumeration : public JObject { public: static Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Enumeration(jobject obj) : JObject(obj) { initializeClass(false); } jboolean hasMoreElements() const; Object nextElement() const; }; extern PyTypeObject PY_TYPE(Enumeration); class t_Enumeration { public: PyObject_HEAD Enumeration object; #ifdef _java_generics PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_Enumeration *self) { return (PyTypeObject **) &(self->parameters); } #endif static PyObject *wrap_Object(const Enumeration& object); #ifdef _java_generics static PyObject *wrap_Object(const Enumeration& object, PyTypeObject *T); #endif static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Enumeration_H */ JCC-3.6/_jcc2/java/util/Enumeration.cpp0000644000076500000000000000660613063017611020042 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/util/Enumeration.h" namespace java { namespace util { enum { mid_hasMoreElements, mid_nextElement, max_mid }; Class *Enumeration::class$ = NULL; jmethodID *Enumeration::mids$ = NULL; jclass Enumeration::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/util/Enumeration"); mids$ = new jmethodID[max_mid]; mids$[mid_hasMoreElements] = env->getMethodID(cls, "hasMoreElements", "()Z"); mids$[mid_nextElement] = env->getMethodID(cls, "nextElement", "()Ljava/lang/Object;"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } jboolean Enumeration::hasMoreElements() const { return env->callBooleanMethod(this$, mids$[mid_hasMoreElements]); } Object Enumeration::nextElement() const { return Object(env->callObjectMethod(this$, mids$[mid_nextElement])); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace util { static PyObject *t_Enumeration_hasMoreElements(t_Enumeration *self); static PyObject *t_Enumeration_nextElement(t_Enumeration *self); static PyMethodDef t_Enumeration__methods_[] = { DECLARE_METHOD(t_Enumeration, hasMoreElements, METH_NOARGS), DECLARE_METHOD(t_Enumeration, nextElement, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Enumeration, t_Enumeration, JObject, java::util::Enumeration, abstract_init, 0, 0, 0, 0, 0); #ifdef _java_generics PyObject *t_Enumeration::wrap_Object(const Enumeration& object, PyTypeObject *T) { PyObject *obj = t_Enumeration::wrap_Object(object); if (obj != Py_None) { t_Enumeration *self = (t_Enumeration *) obj; self->parameters[0] = T; } return obj; } #endif static PyObject *t_Enumeration_hasMoreElements(t_Enumeration *self) { jboolean b; OBJ_CALL(b = self->object.hasMoreElements()); Py_RETURN_BOOL(b); } static PyObject *t_Enumeration_nextElement(t_Enumeration *self) { Object nextElement((jobject) NULL); OBJ_CALL(nextElement = self->object.nextElement()); return t_Object::wrap_Object(nextElement); } } } JCC-3.6/_jcc2/java/util/Iterator.h0000644000076500000000000000374313063017611017011 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Iterator_H #define _Iterator_H #include #include "JObject.h" namespace java { namespace lang { class Class; class Object; } namespace util { using namespace java::lang; class Iterator : public JObject { public: static Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Iterator(jobject obj) : JObject(obj) { initializeClass(false); } jboolean hasNext() const; Object next() const; }; extern PyTypeObject PY_TYPE(Iterator); class t_Iterator { public: PyObject_HEAD Iterator object; #ifdef _java_generics PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_Iterator *self) { return (PyTypeObject **) &(self->parameters); } #endif static PyObject *wrap_Object(const Iterator& object); static PyObject *wrap_jobject(const jobject& object); #ifdef _java_generics static PyObject *wrap_Object(const Iterator& object, PyTypeObject *T); static PyObject *wrap_jobject(const jobject& object, PyTypeObject *T); #endif }; } } #endif /* _Iterator_H */ JCC-3.6/_jcc2/java/io/0000755000076500000000000000000013536235634014506 5ustar vajdawheel00000000000000JCC-3.6/_jcc2/java/io/PrintWriter.cpp0000644000076500000000000000505613063017611017475 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/io/PrintWriter.h" namespace java { namespace io { enum { mid__init_, max_mid }; java::lang::Class *PrintWriter::class$ = NULL; jmethodID *PrintWriter::_mids = NULL; jclass PrintWriter::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/io/PrintWriter"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(Ljava/io/Writer;)V"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } PrintWriter::PrintWriter(Writer writer) : Writer(env->newObject(initializeClass, &_mids, mid__init_, writer.this$)) { } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace io { static int t_PrintWriter_init(t_PrintWriter *self, PyObject *args, PyObject *kwds); static PyMethodDef t_PrintWriter__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(PrintWriter, t_PrintWriter, Writer, java::io::PrintWriter, t_PrintWriter_init, 0, 0, 0, 0, 0); static int t_PrintWriter_init(t_PrintWriter *self, PyObject *args, PyObject *kwds) { Writer writer((jobject) NULL); if (!parseArgs(args, "j", Writer::class$, &writer)) { INT_CALL(self->object = PrintWriter(writer)); return 0; } PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } } } JCC-3.6/_jcc2/java/io/__init__.cpp0000644000076500000000000000210113063017611016727 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "macros.h" namespace java { namespace io { extern PyTypeObject PY_TYPE(Writer); extern PyTypeObject PY_TYPE(StringWriter); extern PyTypeObject PY_TYPE(PrintWriter); namespace reflect { void __install__(PyObject *module); } void __install__(PyObject *m) { INSTALL_TYPE(Writer, m); INSTALL_TYPE(StringWriter, m); INSTALL_TYPE(PrintWriter, m); } } } JCC-3.6/_jcc2/java/io/StringWriter.h0000644000076500000000000000274213063017611017313 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _StringWriter_H #define _StringWriter_H #include #include "java/lang/Class.h" #include "java/io/Writer.h" namespace java { namespace io { class StringWriter : public Writer { public: static java::lang::Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit StringWriter(jobject obj) : Writer(obj) { initializeClass(false); } StringWriter(); StringWriter(const StringWriter& obj) : Writer(obj) {} }; extern PyTypeObject PY_TYPE(StringWriter); class t_StringWriter { public: PyObject_HEAD StringWriter object; static PyObject *wrap_Object(const StringWriter& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _StringWriter_H */ JCC-3.6/_jcc2/java/io/StringWriter.cpp0000644000076500000000000000477413063017611017655 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/io/StringWriter.h" namespace java { namespace io { enum { mid__init_, max_mid }; java::lang::Class *StringWriter::class$ = NULL; jmethodID *StringWriter::_mids = NULL; jclass StringWriter::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/io/StringWriter"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "()V"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } StringWriter::StringWriter() : Writer(env->newObject(initializeClass, &_mids, mid__init_)) { } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace io { static int t_StringWriter_init(t_StringWriter *self, PyObject *args, PyObject *kwds); static PyMethodDef t_StringWriter__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(StringWriter, t_StringWriter, Writer, java::io::StringWriter, t_StringWriter_init, 0, 0, 0, 0, 0); static int t_StringWriter_init(t_StringWriter *self, PyObject *args, PyObject *kwds) { switch (PyTuple_Size(args)) { case 0: INT_CALL(self->object = StringWriter()); break; default: PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } return 0; } } } JCC-3.6/_jcc2/java/io/Writer.h0000644000076500000000000000255713063017611016130 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Writer_H #define _Writer_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace io { class Writer : public java::lang::Object { public: static java::lang::Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Writer(jobject obj) : Object(obj) { initializeClass(false); } }; extern PyTypeObject PY_TYPE(Writer); class t_Writer { public: PyObject_HEAD Writer object; static PyObject *wrap_Object(const Writer& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Writer_H */ JCC-3.6/_jcc2/java/io/PrintWriter.h0000644000076500000000000000274313063017611017142 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _PrintWriter_H #define _PrintWriter_H #include #include "java/lang/Class.h" #include "java/io/Writer.h" namespace java { namespace io { class PrintWriter : public Writer { public: static java::lang::Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit PrintWriter(jobject obj) : Writer(obj) { initializeClass(false); } PrintWriter(Writer writer); PrintWriter(const PrintWriter& obj) : Writer(obj) {} }; extern PyTypeObject PY_TYPE(PrintWriter); class t_PrintWriter { public: PyObject_HEAD PrintWriter object; static PyObject *wrap_Object(const PrintWriter& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _PrintWriter_H */ JCC-3.6/_jcc2/java/io/Writer.cpp0000644000076500000000000000316513063017611016457 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/io/Writer.h" namespace java { namespace io { enum { max_mid }; java::lang::Class *Writer::class$ = NULL; jmethodID *Writer::_mids = NULL; jclass Writer::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/io/Writer"); _mids = NULL; class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace io { static PyMethodDef t_Writer__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Writer, t_Writer, java::lang::Object, Writer, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/0000755000076500000000000000000013536235634015020 5ustar vajdawheel00000000000000JCC-3.6/_jcc2/java/lang/RuntimeException.h0000644000076500000000000000267413063017611020470 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _RuntimeException_H #define _RuntimeException_H #include #include "java/lang/Class.h" #include "java/lang/Exception.h" #include "JArray.h" namespace java { namespace lang { class RuntimeException : public Exception { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit RuntimeException(jobject obj) : Exception(obj) { initializeClass(false); } }; extern PyTypeObject PY_TYPE(RuntimeException); class t_RuntimeException { public: PyObject_HEAD RuntimeException object; static PyObject *wrap_Object(const RuntimeException& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _RuntimeException_H */ JCC-3.6/_jcc2/java/lang/Float.h0000644000076500000000000000257713063017611016235 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Float_H #define _Float_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Float : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Float(jobject obj) : Object(obj) { initializeClass(false); } Float(jfloat); jfloat floatValue() const; }; extern PyTypeObject PY_TYPE(Float); class t_Float { public: PyObject_HEAD Float object; static PyObject *wrap_Object(const Float& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Float_H */ JCC-3.6/_jcc2/java/lang/Short.h0000644000076500000000000000257713063017611016267 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Short_H #define _Short_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Short : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Short(jobject obj) : Object(obj) { initializeClass(false); } Short(jshort); jshort shortValue() const; }; extern PyTypeObject PY_TYPE(Short); class t_Short { public: PyObject_HEAD Short object; static PyObject *wrap_Object(const Short& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Short_H */ JCC-3.6/_jcc2/java/lang/Throwable.cpp0000644000076500000000000000745313063017611017450 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "java/lang/Throwable.h" #include "java/io/PrintWriter.h" namespace java { namespace lang { enum { mid_printStackTrace_0, mid_printStackTrace_1, mid_getMessage, max_mid }; Class *Throwable::class$ = NULL; jmethodID *Throwable::_mids = NULL; jclass Throwable::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Throwable"); _mids = new jmethodID[max_mid]; _mids[mid_printStackTrace_0] = env->getMethodID(cls, "printStackTrace", "()V"); _mids[mid_printStackTrace_1] = env->getMethodID(cls, "printStackTrace", "(Ljava/io/PrintWriter;)V"); _mids[mid_getMessage] = env->getMethodID(cls, "getMessage", "()Ljava/lang/String;"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } void Throwable::printStackTrace() const { env->callVoidMethod(this$, _mids[mid_printStackTrace_0]); } void Throwable::printStackTrace(java::io::PrintWriter writer) const { env->callVoidMethod(this$, _mids[mid_printStackTrace_1], writer.this$); } String Throwable::getMessage() const { return String(env->callObjectMethod(this$, _mids[mid_getMessage])); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyObject *t_Throwable_printStackTrace(t_Throwable *self, PyObject *args); static PyMethodDef t_Throwable__methods_[] = { DECLARE_METHOD(t_Throwable, printStackTrace, METH_VARARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Throwable, t_Throwable, Object, Throwable, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_Throwable_printStackTrace(t_Throwable *self, PyObject *args) { switch (PyTuple_Size(args)) { case 0: OBJ_CALL(self->object.printStackTrace()); Py_RETURN_NONE; case 1: { java::io::PrintWriter writer((jobject) NULL); if (!parseArgs(args, "j", java::io::PrintWriter::class$, &writer)) { OBJ_CALL(self->object.printStackTrace(writer)); Py_RETURN_NONE; } } default: PyErr_SetString(PyExc_ValueError, "invalid args"); return NULL; } } } } JCC-3.6/_jcc2/java/lang/Exception.cpp0000644000076500000000000000313113063017611017444 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Exception.h" namespace java { namespace lang { enum { max_mid }; Class *Exception::class$ = NULL; jmethodID *Exception::_mids = NULL; jclass Exception::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Exception"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Exception__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Exception, t_Exception, Throwable, Exception, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Long.cpp0000644000076500000000000000407613063017611016416 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Long.h" namespace java { namespace lang { enum { mid__init_, mid_longValue, max_mid }; Class *Long::class$ = NULL; jmethodID *Long::_mids = NULL; jclass Long::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Long"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(J)V"); _mids[mid_longValue] = env->getMethodID(cls, "longValue", "()J"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Long::Long(jlong n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jlong Long::longValue() const { return env->callLongMethod(this$, _mids[mid_longValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Long__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Long, t_Long, Object, java::lang::Long, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Character.cpp0000644000076500000000000000416213063017611017407 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Character.h" namespace java { namespace lang { enum { mid__init_, mid_charValue, max_mid }; Class *Character::class$ = NULL; jmethodID *Character::_mids = NULL; jclass Character::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Character"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(C)V"); _mids[mid_charValue] = env->getMethodID(cls, "charValue", "()C"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Character::Character(jchar c) : Object(env->newObject(initializeClass, &_mids, mid__init_, c)) { } jchar Character::charValue() const { return env->callCharMethod(this$, _mids[mid_charValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Character__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Character, t_Character, Object, java::lang::Character, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/__init__.cpp0000644000076500000000000000376413063017611017261 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "macros.h" namespace java { namespace lang { extern PyTypeObject PY_TYPE(Object); extern PyTypeObject PY_TYPE(String); extern PyTypeObject PY_TYPE(Class); extern PyTypeObject PY_TYPE(Throwable); extern PyTypeObject PY_TYPE(Exception); extern PyTypeObject PY_TYPE(RuntimeException); extern PyTypeObject PY_TYPE(Boolean); extern PyTypeObject PY_TYPE(Byte); extern PyTypeObject PY_TYPE(Character); extern PyTypeObject PY_TYPE(Integer); extern PyTypeObject PY_TYPE(Double); extern PyTypeObject PY_TYPE(Float); extern PyTypeObject PY_TYPE(Long); extern PyTypeObject PY_TYPE(Short); namespace reflect { void __install__(PyObject *module); } void __install__(PyObject *m) { INSTALL_TYPE(Object, m); INSTALL_TYPE(String, m); INSTALL_TYPE(Class, m); INSTALL_TYPE(Throwable, m); INSTALL_TYPE(Exception, m); INSTALL_TYPE(RuntimeException, m); INSTALL_TYPE(Boolean, m); INSTALL_TYPE(Byte, m); INSTALL_TYPE(Character, m); INSTALL_TYPE(Double, m); INSTALL_TYPE(Float, m); INSTALL_TYPE(Integer, m); INSTALL_TYPE(Long, m); INSTALL_TYPE(Short, m); reflect::__install__(m); } } } JCC-3.6/_jcc2/java/lang/Object.cpp0000644000076500000000000001076513063017611016727 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" namespace java { namespace lang { enum { mid__init_, mid_toString, mid_getClass, mid_hashCode, mid_equals, max_mid }; Class *Object::class$ = NULL; jmethodID *Object::mids$ = NULL; jclass Object::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Object"); mids$ = new jmethodID[max_mid]; mids$[mid__init_] = env->getMethodID(cls, "", "()V"); mids$[mid_toString] = env->getMethodID(cls, "toString", "()Ljava/lang/String;"); mids$[mid_getClass] = env->getMethodID(cls, "getClass", "()Ljava/lang/Class;"); mids$[mid_hashCode] = env->getMethodID(cls, "hashCode", "()I"); mids$[mid_equals] = env->getMethodID(cls, "equals", "(Ljava/lang/Object;)Z"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Object::Object() : JObject(env->newObject(initializeClass, &mids$, mid__init_)) { } String Object::toString() const { return String(env->callObjectMethod(this$, mids$[mid_toString])); } Class Object::getClass() const { return Class(env->callObjectMethod(this$, mids$[mid_getClass])); } int Object::hashCode() const { return env->callIntMethod(this$, mids$[mid_hashCode]); } jboolean Object::equals(const Object& a0) const { return env->callBooleanMethod(this$, mids$[mid_equals], a0.this$); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static int t_Object_init(t_Object *self, PyObject *args, PyObject *kwds); static PyObject *t_Object_getClass(t_Object *self); static PyObject *t_Object_equals(t_Object *self, PyObject *arg); static PyMethodDef t_Object__methods_[] = { DECLARE_METHOD(t_Object, getClass, METH_NOARGS), DECLARE_METHOD(t_Object, equals, METH_O), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Object, t_Object, JObject, java::lang::Object, t_Object_init, 0, 0, 0, 0, 0); static int t_Object_init(t_Object *self, PyObject *args, PyObject *kwds) { switch (PyTuple_Size(args)) { case 0: INT_CALL(self->object = Object()); break; default: PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } return 0; } static PyObject *t_Object_getClass(t_Object *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Object_equals(t_Object *self, PyObject *arg) { Object a0((jobject) NULL); jboolean result; if (!parseArg(arg, "o", &a0)) { OBJ_CALL(result = self->object.equals(a0)); Py_RETURN_BOOL(result); } PyErr_SetArgsError((PyObject *) self, "equals", arg); return NULL; } } } JCC-3.6/_jcc2/java/lang/Byte.cpp0000644000076500000000000000406613063017611016421 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Byte.h" namespace java { namespace lang { enum { mid__init_, mid_byteValue, max_mid }; Class *Byte::class$ = NULL; jmethodID *Byte::_mids = NULL; jclass Byte::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Byte"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(B)V"); _mids[mid_byteValue] = env->getMethodID(cls, "byteValue", "()B"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Byte::Byte(jbyte b) : Object(env->newObject(initializeClass, &_mids, mid__init_, b)) { } jbyte Byte::byteValue() const { return env->callByteMethod(this$, _mids[mid_byteValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Byte__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Byte, t_Byte, Object, java::lang::Byte, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/reflect/0000755000076500000000000000000013536235634016444 5ustar vajdawheel00000000000000JCC-3.6/_jcc2/java/lang/reflect/Type.h0000644000076500000000000000227613063017611017531 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_Type_H #define java_lang_reflect_Type_H #include "java/lang/Object.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class Type : public java::lang::Object { public: static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Type(jobject obj) : java::lang::Object(obj) { if (obj != NULL) initializeClass(false); } Type(const Type& obj) : java::lang::Object(obj) {} }; } } } #include namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(Type); class t_Type { public: PyObject_HEAD Type object; static PyObject *wrap_Object(const Type&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/TypeVariable.h0000644000076500000000000000346113063017611021174 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_TypeVariable_H #define java_lang_reflect_TypeVariable_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { namespace reflect { class GenericDeclaration; } class Class; class String; } } template class JArray; namespace java { namespace lang { namespace reflect { class TypeVariable : public java::lang::reflect::Type { public: enum { mid_getBounds_6f565a00, mid_getGenericDeclaration_2dc62edd, mid_getName_14c7b5c5, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit TypeVariable(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } TypeVariable(const TypeVariable& obj) : java::lang::reflect::Type(obj) {} JArray getBounds() const; java::lang::reflect::GenericDeclaration getGenericDeclaration() const; java::lang::String getName() const; }; } } } #include namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(TypeVariable); class t_TypeVariable { public: PyObject_HEAD TypeVariable object; static PyObject *wrap_Object(const TypeVariable&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/WildcardType.cpp0000644000076500000000000000755113063017611021537 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/WildcardType.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *WildcardType::class$ = NULL; jmethodID *WildcardType::mids$ = NULL; jclass WildcardType::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/WildcardType"); mids$ = new jmethodID[max_mid]; mids$[mid_getLowerBounds_6f565a00] = env->getMethodID(cls, "getLowerBounds", "()[Ljava/lang/reflect/Type;"); mids$[mid_getUpperBounds_6f565a00] = env->getMethodID(cls, "getUpperBounds", "()[Ljava/lang/reflect/Type;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray WildcardType::getLowerBounds() const { return JArray(env->callObjectMethod(this$, mids$[mid_getLowerBounds_6f565a00])); } JArray WildcardType::getUpperBounds() const { return JArray(env->callObjectMethod(this$, mids$[mid_getUpperBounds_6f565a00])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_WildcardType_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_WildcardType_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_WildcardType_getLowerBounds(t_WildcardType *self); static PyObject *t_WildcardType_getUpperBounds(t_WildcardType *self); static PyMethodDef t_WildcardType__methods_[] = { DECLARE_METHOD(t_WildcardType, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_WildcardType, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_WildcardType, getLowerBounds, METH_NOARGS), DECLARE_METHOD(t_WildcardType, getUpperBounds, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(WildcardType, t_WildcardType, java::lang::reflect::Type, WildcardType, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_WildcardType_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, WildcardType::initializeClass, 1))) return NULL; return t_WildcardType::wrap_Object(WildcardType(((t_WildcardType *) arg)->object.this$)); } static PyObject *t_WildcardType_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, WildcardType::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_WildcardType_getLowerBounds(t_WildcardType *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getLowerBounds()); return result.toSequence(java::lang::reflect::t_Type::wrap_Object); } static PyObject *t_WildcardType_getUpperBounds(t_WildcardType *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getUpperBounds()); return result.toSequence(java::lang::reflect::t_Type::wrap_Object); } } } } #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/GenericArrayType.cpp0000644000076500000000000000623113063017611022353 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/GenericArrayType.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *GenericArrayType::class$ = NULL; jmethodID *GenericArrayType::mids$ = NULL; jclass GenericArrayType::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/GenericArrayType"); mids$ = new jmethodID[max_mid]; mids$[mid_getGenericComponentType_86037cf0] = env->getMethodID(cls, "getGenericComponentType", "()Ljava/lang/reflect/Type;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } java::lang::reflect::Type GenericArrayType::getGenericComponentType() const { return java::lang::reflect::Type(env->callObjectMethod(this$, mids$[mid_getGenericComponentType_86037cf0])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_GenericArrayType_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericArrayType_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericArrayType_getGenericComponentType(t_GenericArrayType *self); static PyMethodDef t_GenericArrayType__methods_[] = { DECLARE_METHOD(t_GenericArrayType, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericArrayType, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericArrayType, getGenericComponentType, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(GenericArrayType, t_GenericArrayType, java::lang::reflect::Type, GenericArrayType, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_GenericArrayType_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, GenericArrayType::initializeClass, 1))) return NULL; return t_GenericArrayType::wrap_Object(GenericArrayType(((t_GenericArrayType *) arg)->object.this$)); } static PyObject *t_GenericArrayType_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, GenericArrayType::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_GenericArrayType_getGenericComponentType(t_GenericArrayType *self) { java::lang::reflect::Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericComponentType()); return java::lang::reflect::t_Type::wrap_Object(result); } } } } #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/ParameterizedType.h0000644000076500000000000000341013063017611022235 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_ParameterizedType_H #define java_lang_reflect_ParameterizedType_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class ParameterizedType : public java::lang::reflect::Type { public: enum { mid_getActualTypeArguments_6f565a00, mid_getOwnerType_86037cf0, mid_getRawType_86037cf0, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit ParameterizedType(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } ParameterizedType(const ParameterizedType& obj) : java::lang::reflect::Type(obj) {} JArray getActualTypeArguments() const; java::lang::reflect::Type getOwnerType() const; java::lang::reflect::Type getRawType() const; }; } } } #include namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(ParameterizedType); class t_ParameterizedType { public: PyObject_HEAD ParameterizedType object; static PyObject *wrap_Object(const ParameterizedType&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/Modifier.cpp0000644000076500000000000002177013063017611020701 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Modifier.h" namespace java { namespace lang { namespace reflect { enum { mid_isPublic, mid_isStatic, mid_isNative, mid_isFinal, mid_isAbstract, mid_isPrivate, mid_isProtected, max_mid }; Class *Modifier::class$ = NULL; jmethodID *Modifier::_mids = NULL; jclass Modifier::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Modifier"); _mids = new jmethodID[max_mid]; _mids[mid_isPublic] = env->getStaticMethodID(cls, "isPublic", "(I)Z"); _mids[mid_isStatic] = env->getStaticMethodID(cls, "isStatic", "(I)Z"); _mids[mid_isNative] = env->getStaticMethodID(cls, "isNative", "(I)Z"); _mids[mid_isFinal] = env->getStaticMethodID(cls, "isFinal", "(I)Z"); _mids[mid_isAbstract] = env->getStaticMethodID(cls, "isAbstract", "(I)Z"); _mids[mid_isPrivate] = env->getStaticMethodID(cls, "isPrivate", "(I)Z"); _mids[mid_isProtected] = env->getStaticMethodID(cls, "isProtected", "(I)Z"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Modifier::isPublic(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isPublic], mod); } int Modifier::isStatic(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isStatic], mod); } int Modifier::isNative(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isNative], mod); } int Modifier::isFinal(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isFinal], mod); } int Modifier::isAbstract(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isAbstract], mod); } int Modifier::isPrivate(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isPrivate], mod); } int Modifier::isProtected(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isProtected], mod); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Modifier_isPublic(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isStatic(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isNative(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isFinal(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isAbstract(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isPrivate(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isProtected(PyTypeObject *type, PyObject *arg); static PyMethodDef t_Modifier__methods_[] = { DECLARE_METHOD(t_Modifier, isPublic, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isStatic, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isNative, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isFinal, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isAbstract, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isPrivate, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isProtected, METH_O | METH_CLASS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Modifier, t_Modifier, Object, Modifier, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_Modifier_isPublic(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isPublic; OBJ_CALL(isPublic = Modifier::isPublic(mod)); Py_RETURN_BOOL(isPublic); } static PyObject *t_Modifier_isStatic(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isStatic; OBJ_CALL(isStatic = Modifier::isStatic(mod)); Py_RETURN_BOOL(isStatic); } static PyObject *t_Modifier_isNative(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isNative; OBJ_CALL(isNative = Modifier::isNative(mod)); Py_RETURN_BOOL(isNative); } static PyObject *t_Modifier_isFinal(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isFinal; OBJ_CALL(isFinal = Modifier::isFinal(mod)); Py_RETURN_BOOL(isFinal); } static PyObject *t_Modifier_isAbstract(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isAbstract; OBJ_CALL(isAbstract = Modifier::isAbstract(mod)); Py_RETURN_BOOL(isAbstract); } static PyObject *t_Modifier_isPrivate(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isPrivate; OBJ_CALL(isPrivate = Modifier::isPrivate(mod)); Py_RETURN_BOOL(isPrivate); } static PyObject *t_Modifier_isProtected(PyTypeObject *type, PyObject *arg) { if (!PyInt_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyInt_AsLong(arg); int isProtected; OBJ_CALL(isProtected = Modifier::isProtected(mod)); Py_RETURN_BOOL(isProtected); } } } } JCC-3.6/_jcc2/java/lang/reflect/Field.h0000644000076500000000000000331113063017611017622 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Field_H #define _Field_H #include namespace java { namespace lang { class Class; class String; namespace reflect { #ifdef _java_generics class Type; #endif class Field : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Field(jobject obj) : Object(obj) { initializeClass(false); } Field(const Field& obj) : Object(obj) {} int getModifiers() const; Class getType() const; String getName() const; #ifdef _java_generics Type getGenericType() const; #endif }; extern PyTypeObject PY_TYPE(Field); class t_Field { public: PyObject_HEAD Field object; static PyObject *wrap_Object(const Field& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Field_H */ JCC-3.6/_jcc2/java/lang/reflect/__init__.cpp0000644000076500000000000000345213063017611020677 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "macros.h" namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(Constructor); extern PyTypeObject PY_TYPE(Method); extern PyTypeObject PY_TYPE(Modifier); extern PyTypeObject PY_TYPE(Field); #ifdef _java_generics extern PyTypeObject PY_TYPE(Type); extern PyTypeObject PY_TYPE(ParameterizedType); extern PyTypeObject PY_TYPE(TypeVariable); extern PyTypeObject PY_TYPE(GenericArrayType); extern PyTypeObject PY_TYPE(WildcardType); extern PyTypeObject PY_TYPE(GenericDeclaration); #endif void __install__(PyObject *m) { INSTALL_TYPE(Constructor, m); INSTALL_TYPE(Method, m); INSTALL_TYPE(Modifier, m); INSTALL_TYPE(Field, m); #ifdef _java_generics INSTALL_TYPE(Type, m); INSTALL_TYPE(ParameterizedType, m); INSTALL_TYPE(TypeVariable, m); INSTALL_TYPE(GenericArrayType, m); INSTALL_TYPE(WildcardType, m); INSTALL_TYPE(GenericDeclaration, m); #endif } } } } JCC-3.6/_jcc2/java/lang/reflect/Method.h0000644000076500000000000000430613063017611020024 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Method_H #define _Method_H #include #include "JArray.h" namespace java { namespace lang { class Class; class String; namespace reflect { #ifdef _java_generics class Type; class TypeVariable; #endif class Method : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Method(jobject obj) : Object(obj) { initializeClass(false); } Method(const Method& obj) : Object(obj) {} int getModifiers() const; Class getReturnType() const; String getName() const; JArray getParameterTypes() const; JArray getExceptionTypes() const; Class getDeclaringClass() const; bool isSynthetic() const; bool isBridge() const; #ifdef _java_generics JArray getTypeParameters() const; JArray getGenericExceptionTypes() const; JArray getGenericParameterTypes() const; Type getGenericReturnType() const; #endif }; extern PyTypeObject PY_TYPE(Method); class t_Method { public: PyObject_HEAD Method object; static PyObject *wrap_Object(const Method& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Method_H */ JCC-3.6/_jcc2/java/lang/reflect/Constructor.cpp0000644000076500000000000001706313063017611021470 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "JArray.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Constructor.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #include "java/lang/reflect/TypeVariable.h" #endif namespace java { namespace lang { namespace reflect { enum { mid_getModifiers, mid_getSignature, mid_getParameterTypes, mid_getExceptionTypes, #ifdef _java_generics mid_getTypeParameters, mid_getGenericExceptionTypes, mid_getGenericParameterTypes, #endif max_mid }; Class *Constructor::class$ = NULL; jmethodID *Constructor::_mids = NULL; jclass Constructor::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Constructor"); _mids = new jmethodID[max_mid]; _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_getParameterTypes] = env->getMethodID(cls, "getParameterTypes", "()[Ljava/lang/Class;"); _mids[mid_getExceptionTypes] = env->getMethodID(cls, "getExceptionTypes", "()[Ljava/lang/Class;"); #ifdef _java_generics _mids[mid_getTypeParameters] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); _mids[mid_getGenericExceptionTypes] = env->getMethodID(cls, "getGenericExceptionTypes", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericParameterTypes] = env->getMethodID(cls, "getGenericParameterTypes", "()[Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Constructor::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } JArray Constructor::getParameterTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getParameterTypes]); return JArray(array); } JArray Constructor::getExceptionTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getExceptionTypes]); return JArray(array); } #ifdef _java_generics JArray Constructor::getTypeParameters() const { return JArray(env->callObjectMethod(this$, _mids[mid_getTypeParameters])); } JArray Constructor::getGenericExceptionTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericExceptionTypes])); } JArray Constructor::getGenericParameterTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericParameterTypes])); } #endif } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Constructor_getModifiers(t_Constructor *self); static PyObject *t_Constructor_getParameterTypes(t_Constructor *self); static PyObject *t_Constructor_getExceptionTypes(t_Constructor *self); #ifdef _java_generics static PyObject *t_Constructor_getTypeParameters(t_Constructor *self); static PyObject *t_Constructor_getGenericExceptionTypes(t_Constructor *self); static PyObject *t_Constructor_getGenericParameterTypes(t_Constructor *self); #endif static PyMethodDef t_Constructor__methods_[] = { DECLARE_METHOD(t_Constructor, getModifiers, METH_NOARGS), DECLARE_METHOD(t_Constructor, getParameterTypes, METH_NOARGS), DECLARE_METHOD(t_Constructor, getExceptionTypes, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Constructor, getTypeParameters, METH_NOARGS), DECLARE_METHOD(t_Constructor, getGenericExceptionTypes, METH_NOARGS), DECLARE_METHOD(t_Constructor, getGenericParameterTypes, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Constructor, t_Constructor, Object, Constructor, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_Constructor_getModifiers(t_Constructor *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyInt_FromLong(modifiers); } static PyObject *t_Constructor_getParameterTypes(t_Constructor *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getParameterTypes()); return types.toSequence(t_Class::wrap_Object); } static PyObject *t_Constructor_getExceptionTypes(t_Constructor *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getExceptionTypes()); return types.toSequence(t_Class::wrap_Object); } #ifdef _java_generics static PyObject *t_Constructor_getTypeParameters(t_Constructor *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } static PyObject *t_Constructor_getGenericExceptionTypes(t_Constructor *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericExceptionTypes()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Constructor_getGenericParameterTypes(t_Constructor *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericParameterTypes()); return result.toSequence(t_Type::wrap_Object); } #endif } } } JCC-3.6/_jcc2/java/lang/reflect/Constructor.h0000644000076500000000000000376313063017611021137 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Constructor_H #define _Constructor_H #include #include "JArray.h" namespace java { namespace lang { class Class; class String; namespace reflect { #ifdef _java_generics class Type; class TypeVariable; #endif class Constructor : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Constructor(jobject obj) : Object(obj) { initializeClass(false); } Constructor(const Constructor& obj) : Object(obj) {} int getModifiers() const; JArray getParameterTypes() const; JArray getExceptionTypes() const; #ifdef _java_generics JArray getTypeParameters() const; JArray getGenericExceptionTypes() const; JArray getGenericParameterTypes() const; #endif }; extern PyTypeObject PY_TYPE(Constructor); class t_Constructor { public: PyObject_HEAD Constructor object; static PyObject *wrap_Object(const Constructor& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Constructor_H */ JCC-3.6/_jcc2/java/lang/reflect/ParameterizedType.cpp0000644000076500000000000001146313063017611022577 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/ParameterizedType.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *ParameterizedType::class$ = NULL; jmethodID *ParameterizedType::mids$ = NULL; jclass ParameterizedType::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/ParameterizedType"); mids$ = new jmethodID[max_mid]; mids$[mid_getActualTypeArguments_6f565a00] = env->getMethodID(cls, "getActualTypeArguments", "()[Ljava/lang/reflect/Type;"); mids$[mid_getOwnerType_86037cf0] = env->getMethodID(cls, "getOwnerType", "()Ljava/lang/reflect/Type;"); mids$[mid_getRawType_86037cf0] = env->getMethodID(cls, "getRawType", "()Ljava/lang/reflect/Type;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray ParameterizedType::getActualTypeArguments() const { return JArray(env->callObjectMethod(this$, mids$[mid_getActualTypeArguments_6f565a00])); } java::lang::reflect::Type ParameterizedType::getOwnerType() const { return java::lang::reflect::Type(env->callObjectMethod(this$, mids$[mid_getOwnerType_86037cf0])); } java::lang::reflect::Type ParameterizedType::getRawType() const { return java::lang::reflect::Type(env->callObjectMethod(this$, mids$[mid_getRawType_86037cf0])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_ParameterizedType_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_ParameterizedType_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_ParameterizedType_getActualTypeArguments(t_ParameterizedType *self); static PyObject *t_ParameterizedType_getOwnerType(t_ParameterizedType *self); static PyObject *t_ParameterizedType_getRawType(t_ParameterizedType *self); static PyMethodDef t_ParameterizedType__methods_[] = { DECLARE_METHOD(t_ParameterizedType, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_ParameterizedType, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_ParameterizedType, getActualTypeArguments, METH_NOARGS), DECLARE_METHOD(t_ParameterizedType, getOwnerType, METH_NOARGS), DECLARE_METHOD(t_ParameterizedType, getRawType, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(ParameterizedType, t_ParameterizedType, java::lang::reflect::Type, ParameterizedType, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_ParameterizedType_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, ParameterizedType::initializeClass, 1))) return NULL; return t_ParameterizedType::wrap_Object(ParameterizedType(((t_ParameterizedType *) arg)->object.this$)); } static PyObject *t_ParameterizedType_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, ParameterizedType::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_ParameterizedType_getActualTypeArguments(t_ParameterizedType *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getActualTypeArguments()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_ParameterizedType_getOwnerType(t_ParameterizedType *self) { java::lang::reflect::Type result((jobject) NULL); OBJ_CALL(result = self->object.getOwnerType()); return java::lang::reflect::t_Type::wrap_Object(result); } static PyObject *t_ParameterizedType_getRawType(t_ParameterizedType *self) { java::lang::reflect::Type result((jobject) NULL); OBJ_CALL(result = self->object.getRawType()); return java::lang::reflect::t_Type::wrap_Object(result); } } } } #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/GenericDeclaration.cpp0000644000076500000000000000634513063017611022666 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/GenericDeclaration.h" #include "java/lang/Class.h" #include "java/lang/reflect/TypeVariable.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *GenericDeclaration::class$ = NULL; jmethodID *GenericDeclaration::mids$ = NULL; jclass GenericDeclaration::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/GenericDeclaration"); mids$ = new jmethodID[max_mid]; mids$[mid_getTypeParameters_837d3468] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray GenericDeclaration::getTypeParameters() const { return JArray(env->callObjectMethod(this$, mids$[mid_getTypeParameters_837d3468])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_GenericDeclaration_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericDeclaration_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericDeclaration_getTypeParameters(t_GenericDeclaration *self); static PyMethodDef t_GenericDeclaration__methods_[] = { DECLARE_METHOD(t_GenericDeclaration, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericDeclaration, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericDeclaration, getTypeParameters, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(GenericDeclaration, t_GenericDeclaration, java::lang::Object, GenericDeclaration, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_GenericDeclaration_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, GenericDeclaration::initializeClass, 1))) return NULL; return t_GenericDeclaration::wrap_Object(GenericDeclaration(((t_GenericDeclaration *) arg)->object.this$)); } static PyObject *t_GenericDeclaration_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, GenericDeclaration::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_GenericDeclaration_getTypeParameters(t_GenericDeclaration *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } } } } #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/Field.cpp0000644000076500000000000001156613063017611020170 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Field.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #endif namespace java { namespace lang { namespace reflect { enum { mid_getModifiers, mid_getType, mid_getName, #ifdef _java_generics mid_getGenericType, #endif max_mid }; Class *Field::class$ = NULL; jmethodID *Field::_mids = NULL; jclass Field::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Field"); _mids = new jmethodID[max_mid]; _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_getType] = env->getMethodID(cls, "getType", "()Ljava/lang/Class;"); _mids[mid_getName] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); #ifdef _java_generics _mids[mid_getGenericType] = env->getMethodID(cls, "getGenericType", "()Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Field::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } Class Field::getType() const { return Class(env->callObjectMethod(this$, _mids[mid_getType])); } String Field::getName() const { return String(env->callObjectMethod(this$, _mids[mid_getName])); } #ifdef _java_generics Type Field::getGenericType() const { return Type(env->callObjectMethod(this$, _mids[mid_getGenericType])); } #endif } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Field_getModifiers(t_Field *self); static PyObject *t_Field_getType(t_Field *self); static PyObject *t_Field_getName(t_Field *self); #ifdef _java_generics static PyObject *t_Field_getGenericType(t_Field *self); #endif static PyMethodDef t_Field__methods_[] = { DECLARE_METHOD(t_Field, getModifiers, METH_NOARGS), DECLARE_METHOD(t_Field, getType, METH_NOARGS), DECLARE_METHOD(t_Field, getName, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Field, getGenericType, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Field, t_Field, Object, Field, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_Field_getModifiers(t_Field *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyInt_FromLong(modifiers); } static PyObject *t_Field_getType(t_Field *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getType()); return t_Class::wrap_Object(cls); } static PyObject *t_Field_getName(t_Field *self) { String name((jobject) NULL); OBJ_CALL(name = self->object.getName()); return j2p(name); } #ifdef _java_generics static PyObject *t_Field_getGenericType(t_Field *self) { Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericType()); return t_Type::wrap_Object(result); } #endif } } } JCC-3.6/_jcc2/java/lang/reflect/Method.cpp0000644000076500000000000003102313063017611020353 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "JArray.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Method.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #include "java/lang/reflect/TypeVariable.h" #endif namespace java { namespace lang { namespace reflect { enum { mid_getModifiers, mid_getReturnType, mid_getName, mid_getParameterTypes, mid_getExceptionTypes, mid_getDeclaringClass, mid_isSynthetic, mid_isBridge, #ifdef _java_generics mid_getTypeParameters, mid_getGenericExceptionTypes, mid_getGenericParameterTypes, mid_getGenericReturnType, #endif max_mid }; Class *Method::class$ = NULL; jmethodID *Method::_mids = NULL; jclass Method::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Method"); _mids = new jmethodID[max_mid]; _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_getReturnType] = env->getMethodID(cls, "getReturnType", "()Ljava/lang/Class;"); _mids[mid_getName] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); _mids[mid_getParameterTypes] = env->getMethodID(cls, "getParameterTypes", "()[Ljava/lang/Class;"); _mids[mid_getExceptionTypes] = env->getMethodID(cls, "getExceptionTypes", "()[Ljava/lang/Class;"); _mids[mid_getDeclaringClass] = env->getMethodID(cls, "getDeclaringClass", "()Ljava/lang/Class;"); _mids[mid_isSynthetic] = env->getMethodID(cls, "isSynthetic", "()Z"); _mids[mid_isBridge] = env->getMethodID(cls, "isBridge", "()Z"); #ifdef _java_generics _mids[mid_getTypeParameters] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); _mids[mid_getGenericExceptionTypes] = env->getMethodID(cls, "getGenericExceptionTypes", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericParameterTypes] = env->getMethodID(cls, "getGenericParameterTypes", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericReturnType] = env->getMethodID(cls, "getGenericReturnType", "()Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Method::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } Class Method::getReturnType() const { return Class(env->callObjectMethod(this$, _mids[mid_getReturnType])); } String Method::getName() const { return String(env->callObjectMethod(this$, _mids[mid_getName])); } JArray Method::getParameterTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getParameterTypes]); return JArray(array); } JArray Method::getExceptionTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getExceptionTypes]); return JArray(array); } Class Method::getDeclaringClass() const { return Class(env->callObjectMethod(this$, _mids[mid_getDeclaringClass])); } bool Method::isSynthetic() const { return env->callBooleanMethod(this$, _mids[mid_isSynthetic]); } bool Method::isBridge() const { return env->callBooleanMethod(this$, _mids[mid_isBridge]); } #ifdef _java_generics JArray Method::getTypeParameters() const { return JArray(env->callObjectMethod(this$, _mids[mid_getTypeParameters])); } JArray Method::getGenericExceptionTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericExceptionTypes])); } JArray Method::getGenericParameterTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericParameterTypes])); } Type Method::getGenericReturnType() const { return Type(env->callObjectMethod(this$, _mids[mid_getGenericReturnType])); } #endif } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Method_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_Method_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_Method_getModifiers(t_Method *self); static PyObject *t_Method_getReturnType(t_Method *self); static PyObject *t_Method_getName(t_Method *self); static PyObject *t_Method_getParameterTypes(t_Method *self); static PyObject *t_Method_getExceptionTypes(t_Method *self); static PyObject *t_Method_getDeclaringClass(t_Method *self); static PyObject *t_Method_isSynthetic(t_Method *self); static PyObject *t_Method_isBridge(t_Method *self); #ifdef _java_generics static PyObject *t_Method_getTypeParameters(t_Method *self); static PyObject *t_Method_getGenericExceptionTypes(t_Method *self); static PyObject *t_Method_getGenericParameterTypes(t_Method *self); static PyObject *t_Method_getGenericReturnType(t_Method *self); #endif static PyMethodDef t_Method__methods_[] = { DECLARE_METHOD(t_Method, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_Method, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_Method, getModifiers, METH_NOARGS), DECLARE_METHOD(t_Method, getReturnType, METH_NOARGS), DECLARE_METHOD(t_Method, getName, METH_NOARGS), DECLARE_METHOD(t_Method, getParameterTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getExceptionTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getDeclaringClass, METH_NOARGS), DECLARE_METHOD(t_Method, isSynthetic, METH_NOARGS), DECLARE_METHOD(t_Method, isBridge, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Method, getTypeParameters, METH_NOARGS), DECLARE_METHOD(t_Method, getGenericExceptionTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getGenericParameterTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getGenericReturnType, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Method, t_Method, Object, Method, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_Method_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, Method::initializeClass, 1))) return NULL; return t_Method::wrap_Object(Method(((t_Method *) arg)->object.this$)); } static PyObject *t_Method_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, Method::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_Method_getModifiers(t_Method *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyInt_FromLong(modifiers); } static PyObject *t_Method_getReturnType(t_Method *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getReturnType()); return t_Class::wrap_Object(cls); } static PyObject *t_Method_getName(t_Method *self) { String name((jobject) NULL); OBJ_CALL(name = self->object.getName()); return j2p(name); } static PyObject *t_Method_getParameterTypes(t_Method *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getParameterTypes()); return types.toSequence(t_Class::wrap_Object); } static PyObject *t_Method_getExceptionTypes(t_Method *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getExceptionTypes()); return types.toSequence(t_Class::wrap_Object); } static PyObject *t_Method_getDeclaringClass(t_Method *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getDeclaringClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Method_isSynthetic(t_Method *self) { int isSynthetic; OBJ_CALL(isSynthetic = self->object.isSynthetic()); Py_RETURN_BOOL(isSynthetic); } static PyObject *t_Method_isBridge(t_Method *self) { int isBridge; OBJ_CALL(isBridge = self->object.isBridge()); Py_RETURN_BOOL(isBridge); } #ifdef _java_generics static PyObject *t_Method_getTypeParameters(t_Method *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } static PyObject *t_Method_getGenericExceptionTypes(t_Method *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericExceptionTypes()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Method_getGenericParameterTypes(t_Method *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericParameterTypes()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Method_getGenericReturnType(t_Method *self) { Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericReturnType()); return t_Type::wrap_Object(result); } #endif } } } JCC-3.6/_jcc2/java/lang/reflect/GenericArrayType.h0000644000076500000000000000303613063017611022020 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_GenericArrayType_H #define java_lang_reflect_GenericArrayType_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class GenericArrayType : public java::lang::reflect::Type { public: enum { mid_getGenericComponentType_86037cf0, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit GenericArrayType(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } GenericArrayType(const GenericArrayType& obj) : java::lang::reflect::Type(obj) {} java::lang::reflect::Type getGenericComponentType() const; }; } } } #include namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(GenericArrayType); class t_GenericArrayType { public: PyObject_HEAD GenericArrayType object; static PyObject *wrap_Object(const GenericArrayType&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/TypeVariable.cpp0000644000076500000000000001122313063017611021522 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/TypeVariable.h" #include "java/lang/reflect/GenericDeclaration.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *TypeVariable::class$ = NULL; jmethodID *TypeVariable::mids$ = NULL; jclass TypeVariable::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/TypeVariable"); mids$ = new jmethodID[max_mid]; mids$[mid_getBounds_6f565a00] = env->getMethodID(cls, "getBounds", "()[Ljava/lang/reflect/Type;"); mids$[mid_getGenericDeclaration_2dc62edd] = env->getMethodID(cls, "getGenericDeclaration", "()Ljava/lang/reflect/GenericDeclaration;"); mids$[mid_getName_14c7b5c5] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray TypeVariable::getBounds() const { return JArray(env->callObjectMethod(this$, mids$[mid_getBounds_6f565a00])); } java::lang::reflect::GenericDeclaration TypeVariable::getGenericDeclaration() const { return java::lang::reflect::GenericDeclaration(env->callObjectMethod(this$, mids$[mid_getGenericDeclaration_2dc62edd])); } java::lang::String TypeVariable::getName() const { return java::lang::String(env->callObjectMethod(this$, mids$[mid_getName_14c7b5c5])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_TypeVariable_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_TypeVariable_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_TypeVariable_getBounds(t_TypeVariable *self); static PyObject *t_TypeVariable_getGenericDeclaration(t_TypeVariable *self); static PyObject *t_TypeVariable_getName(t_TypeVariable *self); static PyMethodDef t_TypeVariable__methods_[] = { DECLARE_METHOD(t_TypeVariable, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_TypeVariable, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_TypeVariable, getBounds, METH_NOARGS), DECLARE_METHOD(t_TypeVariable, getGenericDeclaration, METH_NOARGS), DECLARE_METHOD(t_TypeVariable, getName, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(TypeVariable, t_TypeVariable, java::lang::reflect::Type, TypeVariable, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_TypeVariable_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, TypeVariable::initializeClass, 1))) return NULL; return t_TypeVariable::wrap_Object(TypeVariable(((t_TypeVariable *) arg)->object.this$)); } static PyObject *t_TypeVariable_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, TypeVariable::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_TypeVariable_getBounds(t_TypeVariable *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getBounds()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_TypeVariable_getGenericDeclaration(t_TypeVariable *self) { java::lang::reflect::GenericDeclaration result((jobject) NULL); OBJ_CALL(result = self->object.getGenericDeclaration()); return java::lang::reflect::t_GenericDeclaration::wrap_Object(result); } static PyObject *t_TypeVariable_getName(t_TypeVariable *self) { java::lang::String result((jobject) NULL); OBJ_CALL(result = self->object.getName()); return j2p(result); } } } } #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/GenericDeclaration.h0000644000076500000000000000314113063017611022322 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_GenericDeclaration_H #define java_lang_reflect_GenericDeclaration_H #include "java/lang/Object.h" namespace java { namespace lang { namespace reflect { class TypeVariable; } class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class GenericDeclaration : public java::lang::Object { public: enum { mid_getTypeParameters_837d3468, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit GenericDeclaration(jobject obj) : java::lang::Object(obj) { if (obj != NULL) initializeClass(false); } GenericDeclaration(const GenericDeclaration& obj) : java::lang::Object(obj) {} JArray getTypeParameters() const; }; } } } #include namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(GenericDeclaration); class t_GenericDeclaration { public: PyObject_HEAD GenericDeclaration object; static PyObject *wrap_Object(const GenericDeclaration&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/Modifier.h0000644000076500000000000000350613063017611020343 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Modifier_H #define _Modifier_H #include #include "JArray.h" namespace java { namespace lang { class Class; class String; namespace reflect { class Modifier : public Object { private: explicit Modifier(); public: explicit Modifier(jobject obj) : Object(obj) { initializeClass(false); } static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); static int isPublic(int mod); static int isStatic(int mod); static int isNative(int mod); static int isFinal(int mod); static int isAbstract(int mod); static int isPrivate(int mod); static int isProtected(int mod); }; extern PyTypeObject PY_TYPE(Modifier); class t_Modifier { public: PyObject_HEAD Modifier object; static PyObject *wrap_Object(const Modifier& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Modifier_H */ JCC-3.6/_jcc2/java/lang/reflect/WildcardType.h0000644000076500000000000000314613063017611021200 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_WildcardType_H #define java_lang_reflect_WildcardType_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class WildcardType : public java::lang::reflect::Type { public: enum { mid_getLowerBounds_6f565a00, mid_getUpperBounds_6f565a00, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit WildcardType(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } WildcardType(const WildcardType& obj) : java::lang::reflect::Type(obj) {} JArray getLowerBounds() const; JArray getUpperBounds() const; }; } } } #include namespace java { namespace lang { namespace reflect { extern PyTypeObject PY_TYPE(WildcardType); class t_WildcardType { public: PyObject_HEAD WildcardType object; static PyObject *wrap_Object(const WildcardType&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/reflect/Type.cpp0000644000076500000000000000372713063017611020066 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/Type.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *Type::class$ = NULL; jmethodID *Type::mids$ = NULL; jclass Type::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/Type"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Type_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_Type_instance_(PyTypeObject *type, PyObject *arg); static PyMethodDef t_Type__methods_[] = { DECLARE_METHOD(t_Type, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_Type, instance_, METH_O | METH_CLASS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Type, t_Type, java::lang::Object, Type, abstract_init, 0, 0, 0, 0, 0); static PyObject *t_Type_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, Type::initializeClass, 1))) return NULL; return t_Type::wrap_Object(Type(((t_Type *) arg)->object.this$)); } static PyObject *t_Type_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, Type::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } } } } #endif /* _java_generics */ JCC-3.6/_jcc2/java/lang/String.cpp0000644000076500000000000000664513063017611016771 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" namespace java { namespace lang { enum { mid__init_, mid_toString, mid_length, max_mid }; Class *String::class$ = NULL; jmethodID *String::_mids = NULL; jclass String::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/String"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "()V"); _mids[mid_toString] = env->getMethodID(cls, "toString", "()Ljava/lang/String;"); _mids[mid_length] = env->getMethodID(cls, "length", "()I"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } String::String() : Object(env->newObject(initializeClass, &_mids, mid__init_)) { } int String::length() const { return env->callIntMethod(this$, _mids[mid_length]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static int t_String_init(t_String *self, PyObject *args, PyObject *kwds); static PyObject *t_String_length(t_String *self); static PyMethodDef t_String__methods_[] = { DECLARE_METHOD(t_String, length, METH_NOARGS), { NULL, NULL, 0, NULL } }; DECLARE_TYPE(String, t_String, Object, java::lang::String, t_String_init, 0, 0, 0, 0, 0); static int t_String_init(t_String *self, PyObject *args, PyObject *kwds) { char *bytes; switch (PyTuple_Size(args)) { case 0: INT_CALL(self->object = String()); break; case 1: if (!PyArg_ParseTuple(args, "s", &bytes)) return -1; INT_CALL(self->object = String(env->fromUTF(bytes))); break; default: PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } return 0; } static PyObject *t_String_length(t_String *self) { jint length; OBJ_CALL(length = self->object.length()); return PyInt_FromLong(length); } } } JCC-3.6/_jcc2/java/lang/Long.h0000644000076500000000000000256213063017611016061 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Long_H #define _Long_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Long : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Long(jobject obj) : Object(obj) { initializeClass(false); } Long(jlong); jlong longValue() const; }; extern PyTypeObject PY_TYPE(Long); class t_Long { public: PyObject_HEAD Long object; static PyObject *wrap_Object(const Long& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Long_H */ JCC-3.6/_jcc2/java/lang/Character.h0000644000076500000000000000264413063017611017057 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Character_H #define _Character_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Character : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Character(jobject obj) : Object(obj) { initializeClass(false); } Character(jchar); jchar charValue() const; }; extern PyTypeObject PY_TYPE(Character); class t_Character { public: PyObject_HEAD Character object; static PyObject *wrap_Object(const Character& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Character_H */ JCC-3.6/_jcc2/java/lang/Boolean.h0000644000076500000000000000273213063017611016540 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Boolean_H #define _Boolean_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Boolean : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Boolean(jobject obj) : Object(obj) { initializeClass(false); } Boolean(jboolean); int booleanValue() const; static Boolean *TRUE; static Boolean *FALSE; }; extern PyTypeObject PY_TYPE(Boolean); class t_Boolean { public: PyObject_HEAD Boolean object; static PyObject *wrap_Object(const Boolean& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Boolean_H */ JCC-3.6/_jcc2/java/lang/RuntimeException.cpp0000644000076500000000000000333013063017611021011 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/RuntimeException.h" namespace java { namespace lang { enum { mid_printStackTrace, max_mid }; Class *RuntimeException::class$ = NULL; jmethodID *RuntimeException::_mids = NULL; jclass RuntimeException::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/RuntimeException"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_RuntimeException__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(RuntimeException, t_RuntimeException, Object, java::lang::RuntimeException, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Float.cpp0000644000076500000000000000411213063017611016553 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Float.h" namespace java { namespace lang { enum { mid__init_, mid_floatValue, max_mid }; Class *Float::class$ = NULL; jmethodID *Float::_mids = NULL; jclass Float::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Float"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(F)V"); _mids[mid_floatValue] = env->getMethodID(cls, "floatValue", "()F"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Float::Float(jfloat f) : Object(env->newObject(initializeClass, &_mids, mid__init_, f)) { } jfloat Float::floatValue() const { return env->callFloatMethod(this$, _mids[mid_floatValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Float__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Float, t_Float, Object, java::lang::Float, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Throwable.h0000644000076500000000000000312113063017611017101 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Throwable_H #define _Throwable_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace io { class PrintWriter; } namespace lang { class String; class Throwable : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Throwable(jobject obj) : Object(obj) { initializeClass(false); } void printStackTrace() const; void printStackTrace(java::io::PrintWriter) const; String getMessage() const; }; extern PyTypeObject PY_TYPE(Throwable); class t_Throwable { public: PyObject_HEAD Throwable object; static PyObject *wrap_Object(const Throwable& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Throwable_H */ JCC-3.6/_jcc2/java/lang/Short.cpp0000644000076500000000000000411213063017611016605 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Short.h" namespace java { namespace lang { enum { mid__init_, mid_shortValue, max_mid }; Class *Short::class$ = NULL; jmethodID *Short::_mids = NULL; jclass Short::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Short"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(S)V"); _mids[mid_shortValue] = env->getMethodID(cls, "shortValue", "()S"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Short::Short(jshort n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jshort Short::shortValue() const { return env->callShortMethod(this$, _mids[mid_shortValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Short__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Short, t_Short, Object, java::lang::Short, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Class.h0000644000076500000000000000614413063017611016227 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Class_H #define _Class_H #include #include "JArray.h" #include "java/lang/Object.h" namespace java { namespace lang { namespace reflect { class Method; class Constructor; class Field; #ifdef _java_generics class Type; class TypeVariable; #endif } using namespace reflect; class Class : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Class(jobject obj) : Object(obj) { initializeClass(false); } Class(const Class& obj) : Object(obj) {} static Class forName(const String& className); JArray getDeclaredMethods() const; JArray getMethods() const; Method getMethod(const String &name, const JArray& params) const; Method getDeclaredMethod(const String &name, const JArray& params) const; JArray getDeclaredConstructors() const; JArray getDeclaredFields() const; JArray getDeclaredClasses() const; int isArray() const; int isPrimitive() const; int isInterface() const; int isAssignableFrom(const Class& obj) const; Class getComponentType() const; Class getSuperclass() const; Class getDeclaringClass() const; Class getEnclosingClass() const; JArray getInterfaces() const; String getName() const; int getModifiers() const; int isInstance(const Object &obj) const; #ifdef _java_generics JArray getTypeParameters() const; JArray getGenericInterfaces() const; Type getGenericSuperclass() const; #endif }; extern PyTypeObject PY_TYPE(Class); class t_Class { public: PyObject_HEAD Class object; #ifdef _java_generics PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_Class *self) { return (PyTypeObject **) &(self->parameters); } #endif static PyObject *wrap_Object(const Class& object); #ifdef _java_generics static PyObject *wrap_Object(const Class& object, PyTypeObject *T); #endif static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Class_H */ JCC-3.6/_jcc2/java/lang/Double.h0000644000076500000000000000261413063017611016372 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Double_H #define _Double_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Double : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Double(jobject obj) : Object(obj) { initializeClass(false); } Double(jdouble); jdouble doubleValue() const; }; extern PyTypeObject PY_TYPE(Double); class t_Double { public: PyObject_HEAD Double object; static PyObject *wrap_Object(const Double& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Double_H */ JCC-3.6/_jcc2/java/lang/Object.h0000644000076500000000000000301613063017611016363 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Object_H #define _Object_H #include #include "JObject.h" namespace java { namespace lang { class Class; class String; class Object : public JObject { public: static Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Object(); explicit Object(jobject obj) : JObject(obj) { initializeClass(false); } String toString() const; Class getClass() const; int hashCode() const; jboolean equals(const Object& obj) const; }; extern PyTypeObject PY_TYPE(Object); class t_Object { public: PyObject_HEAD Object object; static PyObject *wrap_Object(const Object& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Object_H */ JCC-3.6/_jcc2/java/lang/Integer.cpp0000644000076500000000000000413213063017611017105 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Integer.h" namespace java { namespace lang { enum { mid__init_, mid_intValue, max_mid }; Class *Integer::class$ = NULL; jmethodID *Integer::_mids = NULL; jclass Integer::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Integer"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(I)V"); _mids[mid_intValue] = env->getMethodID(cls, "intValue", "()I"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Integer::Integer(jint n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jint Integer::intValue() const { return env->callIntMethod(this$, _mids[mid_intValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Integer__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Integer, t_Integer, Object, java::lang::Integer, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Class.cpp0000644000076500000000000005421213063017611016561 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "JArray.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "java/lang/reflect/Method.h" #include "java/lang/reflect/Constructor.h" #include "java/lang/reflect/Field.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #include "java/lang/reflect/TypeVariable.h" #endif namespace java { namespace lang { using namespace reflect; enum { mid_forName, mid_getDeclaredMethods, mid_getMethods, mid_getMethod, mid_getDeclaredMethod, mid_getDeclaredConstructors, mid_getDeclaredFields, mid_getDeclaredClasses, mid_isArray, mid_isPrimitive, mid_isInterface, mid_isAssignableFrom, mid_getComponentType, mid_getSuperclass, mid_getDeclaringClass, mid_getEnclosingClass, mid_getInterfaces, mid_getName, mid_getModifiers, mid_isInstance, #ifdef _java_generics mid_getTypeParameters, mid_getGenericInterfaces, mid_getGenericSuperclass, #endif max_mid }; Class *Class::class$ = NULL; jmethodID *Class::_mids = NULL; jclass Class::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Class"); _mids = new jmethodID[max_mid]; _mids[mid_forName] = env->getStaticMethodID(cls, "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); _mids[mid_getDeclaredMethods] = env->getMethodID(cls, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"); _mids[mid_getMethods] = env->getMethodID(cls, "getMethods", "()[Ljava/lang/reflect/Method;"); _mids[mid_getMethod] = env->getMethodID(cls, "getMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"); _mids[mid_getDeclaredMethod] = env->getMethodID(cls, "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"); _mids[mid_getDeclaredConstructors] = env->getMethodID(cls, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"); _mids[mid_getDeclaredFields] = env->getMethodID(cls, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"); _mids[mid_getDeclaredClasses] = env->getMethodID(cls, "getDeclaredClasses", "()[Ljava/lang/Class;"); _mids[mid_isArray] = env->getMethodID(cls, "isArray", "()Z"); _mids[mid_isPrimitive] = env->getMethodID(cls, "isPrimitive", "()Z"); _mids[mid_isInterface] = env->getMethodID(cls, "isInterface", "()Z"); _mids[mid_isAssignableFrom] = env->getMethodID(cls, "isAssignableFrom", "(Ljava/lang/Class;)Z"); _mids[mid_getComponentType] = env->getMethodID(cls, "getComponentType", "()Ljava/lang/Class;"); _mids[mid_getSuperclass] = env->getMethodID(cls, "getSuperclass", "()Ljava/lang/Class;"); _mids[mid_getDeclaringClass] = env->getMethodID(cls, "getDeclaringClass", "()Ljava/lang/Class;"); _mids[mid_getEnclosingClass] = env->getMethodID(cls, "getEnclosingClass", "()Ljava/lang/Class;"); _mids[mid_getInterfaces] = env->getMethodID(cls, "getInterfaces", "()[Ljava/lang/Class;"); _mids[mid_getName] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_isInstance] = env->getMethodID(cls, "isInstance", "(Ljava/lang/Object;)Z"); #ifdef _java_generics _mids[mid_getTypeParameters] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); _mids[mid_getGenericInterfaces] = env->getMethodID(cls, "getGenericInterfaces", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericSuperclass] = env->getMethodID(cls, "getGenericSuperclass", "()Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Class Class::forName(const String& className) { jclass cls = initializeClass(false); jobject obj = env->callStaticObjectMethod(cls, _mids[mid_forName], className.this$); return Class((jclass) obj); } JArray Class::getDeclaredMethods() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredMethods]); return JArray(array); } JArray Class::getMethods() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getMethods]); return JArray(array); } Method Class::getMethod(const String& name, const JArray& params) const { return Method(env->callObjectMethod(this$, _mids[mid_getMethod], name.this$, params.this$)); } Method Class::getDeclaredMethod(const String& name, const JArray& params) const { return Method(env->callObjectMethod(this$, _mids[mid_getDeclaredMethod], name.this$, params.this$)); } JArray Class::getDeclaredConstructors() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredConstructors]); return JArray(array); } JArray Class::getDeclaredFields() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredFields]); return JArray(array); } JArray Class::getDeclaredClasses() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredClasses]); return JArray(array); } int Class::isArray() const { return (int) env->callBooleanMethod(this$, _mids[mid_isArray]); } int Class::isPrimitive() const { return (int) env->callBooleanMethod(this$, _mids[mid_isPrimitive]); } int Class::isInterface() const { return (int) env->callBooleanMethod(this$, _mids[mid_isInterface]); } int Class::isAssignableFrom(const Class& obj) const { return (int) env->callBooleanMethod(this$, _mids[mid_isAssignableFrom], obj.this$); } Class Class::getComponentType() const { return Class(env->callObjectMethod(this$, _mids[mid_getComponentType])); } Class Class::getSuperclass() const { return Class(env->callObjectMethod(this$, _mids[mid_getSuperclass])); } Class Class::getDeclaringClass() const { return Class(env->callObjectMethod(this$, _mids[mid_getDeclaringClass])); } Class Class::getEnclosingClass() const { return Class(env->callObjectMethod(this$, _mids[mid_getEnclosingClass])); } JArray Class::getInterfaces() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getInterfaces]); return JArray(array); } String Class::getName() const { return String(env->callObjectMethod(this$, _mids[mid_getName])); } int Class::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } int Class::isInstance(const Object &obj) const { return env->callBooleanMethod(this$, _mids[mid_isInstance], obj.this$); } #ifdef _java_generics JArray Class::getTypeParameters() const { return JArray(env->callObjectMethod(this$, _mids[mid_getTypeParameters])); } JArray Class::getGenericInterfaces() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericInterfaces])); } Type Class::getGenericSuperclass() const { return Type(env->callObjectMethod(this$, _mids[mid_getGenericSuperclass])); } #endif } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { using namespace reflect; static PyObject *t_Class_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_Class_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_Class_forName(PyTypeObject *type, PyObject *arg); static PyObject *t_Class_getDeclaredConstructors(t_Class *self); static PyObject *t_Class_getDeclaredMethods(t_Class *self); static PyObject *t_Class_getMethods(t_Class *self); static PyObject *t_Class_getMethod(t_Class *self, PyObject *args); static PyObject *t_Class_getDeclaredMethod(t_Class *self, PyObject *args); static PyObject *t_Class_getDeclaredFields(t_Class *self); static PyObject *t_Class_getDeclaredClasses(t_Class *self); static PyObject *t_Class_isArray(t_Class *self); static PyObject *t_Class_isPrimitive(t_Class *self); static PyObject *t_Class_isInterface(t_Class *self); static PyObject *t_Class_isAssignableFrom(t_Class *self, PyObject *arg); static PyObject *t_Class_getComponentType(t_Class *self); static PyObject *t_Class_getSuperclass(t_Class *self); static PyObject *t_Class_getDeclaringClass(t_Class *self); static PyObject *t_Class_getEnclosingClass(t_Class *self); static PyObject *t_Class_getInterfaces(t_Class *self); static PyObject *t_Class_getName(t_Class *self); static PyObject *t_Class_getModifiers(t_Class *self); #ifdef _java_generics static PyObject *t_Class_getTypeParameters(t_Class *self); static PyObject *t_Class_getGenericInterfaces(t_Class *self); static PyObject *t_Class_getGenericSuperclass(t_Class *self); static PyObject *t_Class_get__parameters_(t_Class *self, void *data); static PyGetSetDef t_Class__fields_[] = { DECLARE_GET_FIELD(t_Class, parameters_), { NULL, NULL, NULL, NULL, NULL } }; #else static PyGetSetDef t_Class__fields_[] = { { NULL, NULL, NULL, NULL, NULL } }; #endif static PyMethodDef t_Class__methods_[] = { DECLARE_METHOD(t_Class, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_Class, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_Class, forName, METH_O | METH_CLASS), DECLARE_METHOD(t_Class, getDeclaredConstructors, METH_NOARGS), DECLARE_METHOD(t_Class, getDeclaredMethods, METH_NOARGS), DECLARE_METHOD(t_Class, getMethods, METH_NOARGS), DECLARE_METHOD(t_Class, getMethod, METH_VARARGS), DECLARE_METHOD(t_Class, getDeclaredMethod, METH_VARARGS), DECLARE_METHOD(t_Class, getDeclaredFields, METH_NOARGS), DECLARE_METHOD(t_Class, getDeclaredClasses, METH_NOARGS), DECLARE_METHOD(t_Class, isArray, METH_NOARGS), DECLARE_METHOD(t_Class, isPrimitive, METH_NOARGS), DECLARE_METHOD(t_Class, isInterface, METH_NOARGS), DECLARE_METHOD(t_Class, isAssignableFrom, METH_O), DECLARE_METHOD(t_Class, getComponentType, METH_NOARGS), DECLARE_METHOD(t_Class, getSuperclass, METH_NOARGS), DECLARE_METHOD(t_Class, getDeclaringClass, METH_NOARGS), DECLARE_METHOD(t_Class, getEnclosingClass, METH_NOARGS), DECLARE_METHOD(t_Class, getInterfaces, METH_NOARGS), DECLARE_METHOD(t_Class, getName, METH_NOARGS), DECLARE_METHOD(t_Class, getModifiers, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Class, getTypeParameters, METH_NOARGS), DECLARE_METHOD(t_Class, getGenericInterfaces, METH_NOARGS), DECLARE_METHOD(t_Class, getGenericSuperclass, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Class, t_Class, Object, java::lang::Class, abstract_init, 0, 0, t_Class__fields_, 0, 0); #ifdef _java_generics PyObject *t_Class::wrap_Object(const Class& object, PyTypeObject *T) { PyObject *obj = t_Class::wrap_Object(object); if (obj != Py_None) { t_Class *self = (t_Class *) obj; self->parameters[0] = T; } return obj; } #endif static PyObject *t_Class_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, Class::initializeClass, 1))) return NULL; return t_Class::wrap_Object(Class(((t_Class *) arg)->object.this$)); } static PyObject *t_Class_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, Class::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_Class_forName(PyTypeObject *type, PyObject *arg) { if (!PyString_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } try { char *className = PyString_AsString(arg); String name = String(env->fromUTF(className)); return t_Class::wrap_Object(Class::forName(name)); } catch (int e) { switch (e) { case _EXC_JAVA: return PyErr_SetJavaError(); default: throw; } } } static PyObject *t_Class_getDeclaredConstructors(t_Class *self) { JArray constructors((jobject) NULL); OBJ_CALL(constructors = self->object.getDeclaredConstructors()); return constructors.toSequence(t_Constructor::wrap_Object); } static PyObject *t_Class_getDeclaredMethods(t_Class *self) { JArray methods((jobject) NULL); OBJ_CALL(methods = self->object.getDeclaredMethods()); return methods.toSequence(t_Method::wrap_Object); } static PyObject *t_Class_getMethods(t_Class *self) { JArray methods((jobject) NULL); OBJ_CALL(methods = self->object.getMethods()); return methods.toSequence(t_Method::wrap_Object); } static PyObject *t_Class_getMethod(t_Class *self, PyObject *args) { String name((jobject) NULL); JArray params((jobject) NULL); Method method((jobject) NULL); if (!parseArgs(args, "s[j", Class::class$, &name, ¶ms)) { OBJ_CALL(method = self->object.getMethod(name, params)); return t_Method::wrap_Object(method); } return PyErr_SetArgsError((PyObject *) self, "getMethod", args); } static PyObject *t_Class_getDeclaredMethod(t_Class *self, PyObject *args) { String name((jobject) NULL); JArray params((jobject) NULL); Method method((jobject) NULL); if (!parseArgs(args, "s[j", Class::class$, &name, ¶ms)) { OBJ_CALL(method = self->object.getDeclaredMethod(name, params)); return t_Method::wrap_Object(method); } return PyErr_SetArgsError((PyObject *) self, "getMethod", args); } static PyObject *t_Class_getDeclaredFields(t_Class *self) { JArray fields((jobject) NULL); OBJ_CALL(fields = self->object.getDeclaredFields()); return fields.toSequence(t_Field::wrap_Object); } static PyObject *t_Class_getDeclaredClasses(t_Class *self) { JArray array((jobject) NULL); OBJ_CALL(array = self->object.getDeclaredClasses()); return array.toSequence(t_Class::wrap_Object); } static PyObject *t_Class_isArray(t_Class *self) { int isArray; OBJ_CALL(isArray = self->object.isArray()); Py_RETURN_BOOL(isArray); } static PyObject *t_Class_isPrimitive(t_Class *self) { int isPrimitive; OBJ_CALL(isPrimitive = self->object.isPrimitive()); Py_RETURN_BOOL(isPrimitive); } static PyObject *t_Class_isInterface(t_Class *self) { int isInterface; OBJ_CALL(isInterface = self->object.isInterface()); Py_RETURN_BOOL(isInterface); } static PyObject *t_Class_isAssignableFrom(t_Class *self, PyObject *arg) { if (!PyObject_TypeCheck(arg, &PY_TYPE(Class))) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } try { Class cls = ((t_Class *) arg)->object; int isAssignableFrom = self->object.isAssignableFrom(cls); Py_RETURN_BOOL(isAssignableFrom); } catch (int e) { switch (e) { case _EXC_JAVA: return PyErr_SetJavaError(); default: throw; } } } static PyObject *t_Class_getComponentType(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getComponentType()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getSuperclass(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getSuperclass()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getDeclaringClass(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getDeclaringClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getEnclosingClass(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getEnclosingClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getInterfaces(t_Class *self) { JArray interfaces((jobject) NULL); OBJ_CALL(interfaces = self->object.getInterfaces()); return interfaces.toSequence(t_Class::wrap_Object); } static PyObject *t_Class_getName(t_Class *self) { String name((jobject) NULL); OBJ_CALL(name = self->object.getName()); return j2p(name); } static PyObject *t_Class_getModifiers(t_Class *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyInt_FromLong(modifiers); } #ifdef _java_generics static PyObject *t_Class_getTypeParameters(t_Class *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } static PyObject *t_Class_getGenericInterfaces(t_Class *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericInterfaces()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Class_getGenericSuperclass(t_Class *self) { Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericSuperclass()); return t_Type::wrap_Object(result); } static PyObject *t_Class_get__parameters_(t_Class *self, void *data) { return typeParameters(self->parameters, sizeof(self->parameters)); } #endif } } JCC-3.6/_jcc2/java/lang/Boolean.cpp0000644000076500000000000000462413063017611017075 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Boolean.h" namespace java { namespace lang { enum { mid__init_, mid_booleanValue, max_mid }; Class *Boolean::class$ = NULL; jmethodID *Boolean::_mids = NULL; Boolean *Boolean::TRUE = NULL; Boolean *Boolean::FALSE = NULL; jclass Boolean::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Boolean"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(Z)V"); _mids[mid_booleanValue] = env->getMethodID(cls, "booleanValue", "()Z"); class$ = (Class *) new JObject(cls); FALSE = new Boolean(env->getStaticObjectField(cls, "FALSE", "Ljava/lang/Boolean;")); TRUE = new Boolean(env->getStaticObjectField(cls, "TRUE", "Ljava/lang/Boolean;")); } return (jclass) class$->this$; } Boolean::Boolean(jboolean b) : Object(env->newObject(initializeClass, &_mids, mid__init_, b)) { } int Boolean::booleanValue() const { return (int) env->callBooleanMethod(this$, _mids[mid_booleanValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Boolean__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Boolean, t_Boolean, Object, java::lang::Boolean, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Exception.h0000644000076500000000000000257513063017611017124 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Exception_H #define _Exception_H #include #include "java/lang/Class.h" #include "java/lang/Throwable.h" #include "JArray.h" namespace java { namespace lang { class Exception : public Throwable { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Exception(jobject obj) : Throwable(obj) { initializeClass(false); } }; extern PyTypeObject PY_TYPE(Exception); class t_Exception { public: PyObject_HEAD Exception object; static PyObject *wrap_Object(const Exception& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Exception_H */ JCC-3.6/_jcc2/java/lang/Integer.h0000644000076500000000000000261513063017611016556 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Integer_H #define _Integer_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Integer : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Integer(jobject obj) : Object(obj) { initializeClass(false); } Integer(jint); jint intValue() const; }; extern PyTypeObject PY_TYPE(Integer); class t_Integer { public: PyObject_HEAD Integer object; static PyObject *wrap_Object(const Integer& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Integer_H */ JCC-3.6/_jcc2/java/lang/Double.cpp0000644000076500000000000000414613063017611016727 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Double.h" namespace java { namespace lang { enum { mid__init_, mid_doubleValue, max_mid }; Class *Double::class$ = NULL; jmethodID *Double::_mids = NULL; jclass Double::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Double"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(D)V"); _mids[mid_doubleValue] = env->getMethodID(cls, "doubleValue", "()D"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Double::Double(jdouble n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jdouble Double::doubleValue() const { return env->callDoubleMethod(this$, _mids[mid_doubleValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Double__methods_[] = { { NULL, NULL, 0, NULL } }; DECLARE_TYPE(Double, t_Double, Object, java::lang::Double, abstract_init, 0, 0, 0, 0, 0); } } JCC-3.6/_jcc2/java/lang/Byte.h0000644000076500000000000000256213063017611016065 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Byte_H #define _Byte_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Byte : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Byte(jobject obj) : Object(obj) { initializeClass(false); } Byte(jbyte); jbyte byteValue() const; }; extern PyTypeObject PY_TYPE(Byte); class t_Byte { public: PyObject_HEAD Byte object; static PyObject *wrap_Object(const Byte& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Byte_H */ JCC-3.6/_jcc2/java/lang/String.h0000644000076500000000000000303113063017611016420 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _String_H #define _String_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { class String : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit String(jobject obj) : Object(obj) { initializeClass(false); } String(); String(const String& obj) : Object(obj) {} String toString() const { return *this; } int length() const; }; extern PyTypeObject PY_TYPE(String); class t_String { public: PyObject_HEAD String object; static PyObject *wrap_Object(const String& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _String_H */ JCC-3.6/JCC.egg-info/0000755000076500000000000000000013536235634014267 5ustar vajdawheel00000000000000JCC-3.6/JCC.egg-info/PKG-INFO0000644000076500000000000000554613536235633015375 0ustar vajdawheel00000000000000Metadata-Version: 1.1 Name: JCC Version: 3.6 Summary: a C++ code generator for calling Java from C++/Python Home-page: UNKNOWN Author: Andi Vajda Author-email: vajda@apache.org License: UNKNOWN Description: For changes since earlier releases, see: http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc/CHANGES JCC is a C++ code generator for producing the code necessary to call into Java classes from CPython via Java's Native Invocation Interface (JNI). JCC generates C++ wrapper classes that hide all the gory details of JNI access as well Java memory and object reference management. JCC generates CPython types that make these C++ classes accessible from a Python interpreter. JCC attempts to make these Python types pythonic by detecting iterators and property accessors. Iterators and mappings may also be declared to JCC. JCC has been built on Python 2.3 to 2.7, on Python 3.6, and has been used with various Java Runtime Environments such as Sun Java 1.5 and 1.6, Apple's Java 1.5 and 1.6 on Mac OS X, open source Java OpenJDK 1.7 builds as well as Oracle Java 1.7 and 1.8. JCC is supported on Mac OS X, Linux, Solaris and Windows. JCC is written in C++ and Python. It uses Java's reflection API to do its job and needs a Java Runtime Environment to be present to operate. JCC is built with distutils or setuptools:: python setup.py build sudo python setup.py install Setuptools is required to build JCC on Python 2.3. JCC's setup.py file needs to be edited before building JCC to specify the location of the Java Runtime Environment's header files and libraries. The svn sources for JCC are available at: http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc/ For more information about JCC see: http://lucene.apache.org/pylucene/jcc/index.html JCC comes with an Apache 2.0 copyright license: http://www.apache.org/licenses/LICENSE-2.0 Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: C++ Classifier: Programming Language :: Java Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Software Development :: Code Generators Classifier: Topic :: Software Development :: Libraries :: Java Libraries JCC-3.6/JCC.egg-info/not-zip-safe0000644000076500000000000000000111350716504016505 0ustar vajdawheel00000000000000 JCC-3.6/JCC.egg-info/SOURCES.txt0000644000076500000000000001234413536235633016156 0ustar vajdawheel00000000000000CHANGES DESCRIPTION INSTALL LICENSE MANIFEST.in NOTICE README setup.py JCC.egg-info/PKG-INFO JCC.egg-info/SOURCES.txt JCC.egg-info/dependency_links.txt JCC.egg-info/not-zip-safe JCC.egg-info/top_level.txt _jcc2/boot.cpp _jcc2/java/io/PrintWriter.cpp _jcc2/java/io/PrintWriter.h _jcc2/java/io/StringWriter.cpp _jcc2/java/io/StringWriter.h _jcc2/java/io/Writer.cpp _jcc2/java/io/Writer.h _jcc2/java/io/__init__.cpp _jcc2/java/lang/Boolean.cpp _jcc2/java/lang/Boolean.h _jcc2/java/lang/Byte.cpp _jcc2/java/lang/Byte.h _jcc2/java/lang/Character.cpp _jcc2/java/lang/Character.h _jcc2/java/lang/Class.cpp _jcc2/java/lang/Class.h _jcc2/java/lang/Double.cpp _jcc2/java/lang/Double.h _jcc2/java/lang/Exception.cpp _jcc2/java/lang/Exception.h _jcc2/java/lang/Float.cpp _jcc2/java/lang/Float.h _jcc2/java/lang/Integer.cpp _jcc2/java/lang/Integer.h _jcc2/java/lang/Long.cpp _jcc2/java/lang/Long.h _jcc2/java/lang/Object.cpp _jcc2/java/lang/Object.h _jcc2/java/lang/RuntimeException.cpp _jcc2/java/lang/RuntimeException.h _jcc2/java/lang/Short.cpp _jcc2/java/lang/Short.h _jcc2/java/lang/String.cpp _jcc2/java/lang/String.h _jcc2/java/lang/Throwable.cpp _jcc2/java/lang/Throwable.h _jcc2/java/lang/__init__.cpp _jcc2/java/lang/reflect/Constructor.cpp _jcc2/java/lang/reflect/Constructor.h _jcc2/java/lang/reflect/Field.cpp _jcc2/java/lang/reflect/Field.h _jcc2/java/lang/reflect/GenericArrayType.cpp _jcc2/java/lang/reflect/GenericArrayType.h _jcc2/java/lang/reflect/GenericDeclaration.cpp _jcc2/java/lang/reflect/GenericDeclaration.h _jcc2/java/lang/reflect/Method.cpp _jcc2/java/lang/reflect/Method.h _jcc2/java/lang/reflect/Modifier.cpp _jcc2/java/lang/reflect/Modifier.h _jcc2/java/lang/reflect/ParameterizedType.cpp _jcc2/java/lang/reflect/ParameterizedType.h _jcc2/java/lang/reflect/Type.cpp _jcc2/java/lang/reflect/Type.h _jcc2/java/lang/reflect/TypeVariable.cpp _jcc2/java/lang/reflect/TypeVariable.h _jcc2/java/lang/reflect/WildcardType.cpp _jcc2/java/lang/reflect/WildcardType.h _jcc2/java/lang/reflect/__init__.cpp _jcc2/java/util/Enumeration.cpp _jcc2/java/util/Enumeration.h _jcc2/java/util/Iterator.cpp _jcc2/java/util/Iterator.h _jcc3/boot.cpp _jcc3/java/io/PrintWriter.cpp _jcc3/java/io/PrintWriter.h _jcc3/java/io/StringWriter.cpp _jcc3/java/io/StringWriter.h _jcc3/java/io/Writer.cpp _jcc3/java/io/Writer.h _jcc3/java/io/__init__.cpp _jcc3/java/lang/Boolean.cpp _jcc3/java/lang/Boolean.h _jcc3/java/lang/Byte.cpp _jcc3/java/lang/Byte.h _jcc3/java/lang/Character.cpp _jcc3/java/lang/Character.h _jcc3/java/lang/Class.cpp _jcc3/java/lang/Class.h _jcc3/java/lang/Double.cpp _jcc3/java/lang/Double.h _jcc3/java/lang/Exception.cpp _jcc3/java/lang/Exception.h _jcc3/java/lang/Float.cpp _jcc3/java/lang/Float.h _jcc3/java/lang/Integer.cpp _jcc3/java/lang/Integer.h _jcc3/java/lang/Long.cpp _jcc3/java/lang/Long.h _jcc3/java/lang/Object.cpp _jcc3/java/lang/Object.h _jcc3/java/lang/RuntimeException.cpp _jcc3/java/lang/RuntimeException.h _jcc3/java/lang/Short.cpp _jcc3/java/lang/Short.h _jcc3/java/lang/String.cpp _jcc3/java/lang/String.h _jcc3/java/lang/Throwable.cpp _jcc3/java/lang/Throwable.h _jcc3/java/lang/__init__.cpp _jcc3/java/lang/reflect/Constructor.cpp _jcc3/java/lang/reflect/Constructor.h _jcc3/java/lang/reflect/Field.cpp _jcc3/java/lang/reflect/Field.h _jcc3/java/lang/reflect/GenericArrayType.cpp _jcc3/java/lang/reflect/GenericArrayType.h _jcc3/java/lang/reflect/GenericDeclaration.cpp _jcc3/java/lang/reflect/GenericDeclaration.h _jcc3/java/lang/reflect/Method.cpp _jcc3/java/lang/reflect/Method.h _jcc3/java/lang/reflect/Modifier.cpp _jcc3/java/lang/reflect/Modifier.h _jcc3/java/lang/reflect/ParameterizedType.cpp _jcc3/java/lang/reflect/ParameterizedType.h _jcc3/java/lang/reflect/Type.cpp _jcc3/java/lang/reflect/Type.h _jcc3/java/lang/reflect/TypeVariable.cpp _jcc3/java/lang/reflect/TypeVariable.h _jcc3/java/lang/reflect/WildcardType.cpp _jcc3/java/lang/reflect/WildcardType.h _jcc3/java/lang/reflect/__init__.cpp _jcc3/java/util/Enumeration.cpp _jcc3/java/util/Enumeration.h _jcc3/java/util/Iterator.cpp _jcc3/java/util/Iterator.h helpers2/__init__.py helpers2/build.py helpers2/darwin.py helpers2/linux.py helpers2/mingw32.py helpers2/windows.py helpers3/__init__.py helpers3/build.py helpers3/darwin.py helpers3/linux.py helpers3/mingw32.py helpers3/windows.py java/org/apache/jcc/PythonException.java java/org/apache/jcc/PythonVM.java jcc2/__init__.py jcc2/__main__.py jcc2/cpp.py jcc2/python.py jcc2/windows.py jcc2/classes/org/apache/jcc/PythonException.class jcc2/classes/org/apache/jcc/PythonVM.class jcc2/patches/patch.4195 jcc2/patches/patch.43.0.6c11 jcc2/patches/patch.43.0.6c7 jcc2/sources/JArray.cpp jcc2/sources/JArray.h jcc2/sources/JCCEnv.cpp jcc2/sources/JCCEnv.h jcc2/sources/JObject.cpp jcc2/sources/JObject.h jcc2/sources/functions.cpp jcc2/sources/functions.h jcc2/sources/jcc.cpp jcc2/sources/jccfuncs.h jcc2/sources/macros.h jcc2/sources/types.cpp jcc3/__init__.py jcc3/__main__.py jcc3/cpp.py jcc3/python.py jcc3/windows.py jcc3/classes/org/apache/jcc/PythonException.class jcc3/classes/org/apache/jcc/PythonVM.class jcc3/sources/JArray.cpp jcc3/sources/JArray.h jcc3/sources/JCCEnv.cpp jcc3/sources/JCCEnv.h jcc3/sources/JObject.cpp jcc3/sources/JObject.h jcc3/sources/functions.cpp jcc3/sources/functions.h jcc3/sources/jcc.cpp jcc3/sources/jccfuncs.h jcc3/sources/macros.h jcc3/sources/types.cppJCC-3.6/JCC.egg-info/top_level.txt0000644000076500000000000000001113536235633017010 0ustar vajdawheel00000000000000jcc jcc3 JCC-3.6/JCC.egg-info/dependency_links.txt0000644000076500000000000000000113536235633020334 0ustar vajdawheel00000000000000 JCC-3.6/jcc3/0000755000076500000000000000000013536235634013020 5ustar vajdawheel00000000000000JCC-3.6/jcc3/classes/0000755000076500000000000000000013536235634014455 5ustar vajdawheel00000000000000JCC-3.6/jcc3/classes/org/0000755000076500000000000000000013536235634015244 5ustar vajdawheel00000000000000JCC-3.6/jcc3/classes/org/apache/0000755000076500000000000000000013536235634016465 5ustar vajdawheel00000000000000JCC-3.6/jcc3/classes/org/apache/jcc/0000755000076500000000000000000013536235634017224 5ustar vajdawheel00000000000000JCC-3.6/jcc3/classes/org/apache/jcc/PythonVM.class0000644000076500000000000000176013536235632022001 0ustar vajdawheel00000000000000Êþº¾1. !" # $ % #& '()vmLorg/apache/jcc/PythonVM;start@(Ljava/lang/String;[Ljava/lang/String;)Lorg/apache/jcc/PythonVM;CodeLineNumberTable-(Ljava/lang/String;)Lorg/apache/jcc/PythonVM;get()Lorg/apache/jcc/PythonVM;()Vinit((Ljava/lang/String;[Ljava/lang/String;)V instantiate8(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; Exceptions*acquireThreadState()IreleaseThreadState SourceFile PythonVM.java org/apache/jcc/PythonVM   jcc+ ,-java/lang/Objectorg/apache/jcc/PythonExceptionjava/lang/System loadLibrary(Ljava/lang/String;)V!  @²Ç»Y·³²*+¶²°(*+. *¸°> ²°I!*·± MN"¸±  JCC-3.6/jcc3/classes/org/apache/jcc/PythonException.class0000644000076500000000000000174713536235632023422 0ustar vajdawheel00000000000000Êþº¾1; ' ( ) * + , -. / 01 2 3 456 withTraceZpy_error_stateJ(Ljava/lang/String;)VCodeLineNumberTablefinalize()V Exceptions7 getMessage(Z)Ljava/lang/String;()Ljava/lang/String; pythonDecRef getErrorNamegetErrorMessagegetErrorTracebacksaveErrorState SourceFilePythonException.java    $   "java/lang/StringBuilder  89 # : org/apache/jcc/PythonExceptionjava/lang/RuntimeExceptionjava/lang/Throwableappend-(Ljava/lang/String;)Ljava/lang/StringBuilder;toString! <*+·*µ* µ*¶± !*¶±  !`4*´ ”š*·°*¶M™»Y· ,¶  ¶ *¶ ¶ ¶ °,°% &(*+2-! **´¶°2 !"#$%&JCC-3.6/jcc3/__init__.py0000644000076500000000000000244713063321177015131 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # jcc package import os, sys if sys.platform == 'win32': if '--find-jvm-dll' in sys.argv: from .windows import add_jvm_dll_directory_to_path add_jvm_dll_directory_to_path() from jcc.config import SHARED if SHARED: path = os.environ['Path'].split(os.pathsep) eggpath = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if eggpath not in path: path.insert(0, eggpath) os.environ['Path'] = os.pathsep.join(path) import jcc._jcc3 as _jcc3 # used when jcc is invoked with -m if __name__ == '__main__': import jcc.__main__ else: from ._jcc3 import initVM CLASSPATH=os.path.join(os.path.abspath(os.path.dirname(__file__)), "classes") _jcc3.CLASSPATH = CLASSPATH JCC-3.6/jcc3/cpp.py0000644000076500000000000013307013457454564014167 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, sys, zipfile from . import _jcc3 class JavaError(Exception): def getJavaException(self): return self.args[0] if self.args else None def __str__(self): exc = self.getJavaException() if exc is None: return "Java Error" else: writer = StringWriter() exc.printStackTrace(PrintWriter(writer)) return '\n'.join((super(JavaError, self).__str__(), "Java stacktrace:", str(writer))) class InvalidArgsError(Exception): pass _jcc3._set_exception_types(JavaError, InvalidArgsError) from ._jcc3 import findClass as _findClass from ._jcc3 import * def findClass(className): try: cls = _findClass(className) except: print("While loading", className, file=sys.stderr) raise if cls is None: raise ValueError(className) return cls # fix for PYLUCENE-47: method overloads need to be sorted deterministically # and heuristically by the so-called rank of their parameter types, trying # to match parameters whose classes are deeper in the class hierarchy first def sortSignatures(signatures, groupByName=False): class Parameters(object): def __init__(self, signature): self.signature = signature self.types = signature.getParameterTypes() if groupByName: self.name = signature.getName() def __lt__(self, other): # group signatures by name, lexicographically if groupByName: if self.name < other.name: return True if self.name > other.name: return False # group signatures by number of parameters, lowest first diff = len(self.types) - len(other.types) if diff < 0: return True if diff > 0: return False # sort signatures of equal length by the sum of class ranks # so that deepest classes are considered first during calls, # thus sort highest rank number first diff = self.getRank() - other.getRank() if diff > 0: return True if diff < 0: return False # sort signatures of equal rank by the names of their classes # lexicographically for (t_self, t_other) in zip(self.types, other.types): if t_self.getName() < t_other.getName(): return True # give up, other must be larger ;-) return False def getRank(self): rank = 0 for item in self.types: while item is not None: rank += 1 item = item.getSuperclass() return rank parameters = [Parameters(signature) for signature in signatures] parameters.sort() signatures[:] = [params.signature for params in parameters] INDENT = ' ' HALF_INDENT = ' ' PRIMITIVES = { 'boolean': 'Z', 'byte': 'B', 'char': 'C', 'double': 'D', 'float': 'F', 'int': 'I', 'long': 'J', 'short': 'S', 'void': 'V' } RESERVED = set(['delete', 'and', 'or', 'not', 'xor', 'union', 'register', 'const', 'bool', 'operator', 'typeof', 'asm', 'mutable', 'inline', 'typedef', 'struct', 'extern', 'NULL', 'DOMAIN', 'IGNORE', 'min', 'max', 'PREFIX', 'NAN']) RENAME_METHOD_SUFFIX = '_' RENAME_FIELD_SUFFIX = '__' def cppname(name): if name in RESERVED: return name + '$' return name def cppnames(names): return [cppname(name) for name in names] def absname(names): if names: return "::%s" %('::'.join(names)) return '' def typename(cls, current, const): if cls.isArray(): componentType = cls.getComponentType() name = 'JArray< %s >' %(typename(componentType, current, False)) elif cls.isPrimitive(): name = cls.getName() if name != 'void': name = 'j' + name const = False elif cls == current: name = cppname(cls.getName().split('.')[-1]) else: name = absname([cppname(name) for name in cls.getName().split('.')]) if const: return "const %s &" %(name) return name def argnames(params, cls): if not params: return '', '' count = len(params) decls = ', '.join(["%s a%d" %(typename(params[i], cls, True), i) for i in range(count)]) args = ', '.join(['a%d%s' %(i, not params[i].isPrimitive() and '.this$' or '') for i in range(count)]) return decls, ', ' + args def line(out, indent=0, string='', *args): out.write(INDENT * indent) out.write(string % args) out.write('\n') def known(cls, typeset, declares, packages, excludes, generics): if generics: if Class.instance_(cls): cls = Class.cast_(cls) elif ParameterizedType.instance_(cls): pt = ParameterizedType.cast_(cls) if not known(pt.getRawType(), typeset, declares, packages, excludes, True): return False for ta in pt.getActualTypeArguments(): if TypeVariable.instance_(ta): continue if not known(ta, typeset, declares, packages, excludes, True): return False return True elif WildcardType.instance_(cls): wc = WildcardType.cast_(cls) for ub in wc.getUpperBounds(): if not known(ub, typeset, declares, packages, excludes, True): return False return True elif TypeVariable.instance_(cls): for bounds in TypeVariable.cast_(cls).getBounds(): if not known(bounds, typeset, declares, packages, excludes, True): return False return True elif GenericArrayType.instance_(cls): return known(GenericArrayType.cast_(cls).getGenericComponentType(), typeset, declares, packages, excludes, True) else: raise TypeError(cls, cls.getClass()) while cls.isArray(): cls = cls.getComponentType() className = cls.getName() if className.split('$', 1)[0] in excludes or className in excludes: return False if cls.isPrimitive(): return True if cls in typeset: declares.add(cls) return True if className.rsplit('.', 1)[0] in packages: typeset.add(cls) declares.add(cls) cls = cls.getSuperclass() while cls and cls not in typeset: typeset.add(cls) cls = cls.getSuperclass() return True return False def addRequiredTypes(cls, typeset, generics): if generics: if Class.instance_(cls): cls = Class.cast_(cls) if not (cls.isPrimitive() or cls in typeset): if cls.isArray(): addRequiredTypes(cls.getComponentType(), typeset, True) else: typeset.add(cls) cls = cls.getGenericSuperclass() if cls is not None: addRequiredTypes(cls, typeset, True) elif ParameterizedType.instance_(cls): pt = ParameterizedType.cast_(cls) addRequiredTypes(pt.getRawType(), typeset, True) for ta in pt.getActualTypeArguments(): addRequiredTypes(ta, typeset, True) elif GenericArrayType.instance_(cls): gat = GenericArrayType.cast_(cls) addRequiredTypes(gat.getGenericComponentType(), typeset, True) elif not (TypeVariable.instance_(cls) or WildcardType.instance_(cls)): raise NotImplementedError(repr(cls)) else: if cls not in typeset: typeset.add(cls) cls = cls.getSuperclass() if cls is not None: addRequiredTypes(cls, typeset, False) def getActualTypeArguments(pt): while True: arguments = pt.getActualTypeArguments() if arguments: return arguments pt = pt.getOwnerType() if pt is None or not ParameterizedType.instance_(pt): return [] pt = ParameterizedType.cast_(pt) def getTypeParameters(cls): if cls is None: return [] parameters = cls.getTypeParameters() if parameters: return parameters superCls = cls.getGenericSuperclass() if Class.instance_(superCls): parameters = getTypeParameters(Class.cast_(superCls)) if parameters: return parameters elif ParameterizedType.instance_(superCls): parameters = getActualTypeArguments(ParameterizedType.cast_(superCls)) if parameters: return parameters parameters = getTypeParameters(cls.getDeclaringClass()) if parameters: return parameters return [] def find_method(cls, name, params): declared = False while True: try: if declared: method = cls.getDeclaredMethod(name, params) else: method = cls.getMethod(name, params) break except JavaError as e: if (e.getJavaException().getClass().getName() == 'java.lang.NoSuchMethodException'): if not declared: declared = True else: cls = cls.getSuperclass() if not cls: return None continue raise modifiers = method.getModifiers() if Modifier.isAbstract(modifiers): return None if Modifier.isPrivate(modifiers): return None return method def signature(fn, argsOnly=False): def typename(cls): array = '' while cls.isArray(): array += '[' cls = cls.getComponentType() if cls.isPrimitive(): return array + PRIMITIVES[cls.getName()] return '%sL%s;' %(array, cls.getName().replace('.', '/')) if isinstance(fn, Constructor): returnType = 'V' elif isinstance(fn, Method): returnType = typename(fn.getReturnType()) elif isinstance(fn, Field): return typename(fn.getType()) if argsOnly: return '(%s)' %(''.join([typename(param) for param in fn.getParameterTypes()])) return '(%s)%s' %(''.join([typename(param) for param in fn.getParameterTypes()]), returnType) def forward(out, namespace, indent): for name, entries in namespace.items(): if entries is True: line(out, indent, 'class %s;', cppname(name)) else: line(out, indent, 'namespace %s {', cppname(name)) forward(out, entries, indent + 1) line(out, indent, '}') def expandjar(path): jar = zipfile.ZipFile(path, 'r') for member in jar.infolist(): f = member.filename if not f.startswith('META-INF/') and f.endswith('.class'): yield f.split('.')[0].replace('/', '.') jar.close() def jcc(args): classNames = set() listedClassNames = set() listedMethodOrFieldNames = {} packages = set() jars = [] classpath = [_jcc3.CLASSPATH] libpath = [] vmargs = ['-Djava.awt.headless=true'] moduleName = None modules = [] build = False install = False recompile = False egg_info = False output = 'build' debug = False excludes = [] version = '' mappings = {} sequences = {} renames = {} use_full_names = False env = None wrapperFiles = 1 prefix = None root = None install_dir = None home_dir = None use_distutils = False shared = False dist = False wininst = False find_jvm_dll = False compiler = None generics = hasattr(_jcc3, "Type") arch = [] resources = [] imports = {} extra_setup_args = [] initvm_args = {} i = 1 while i < len(args): arg = args[i] if arg.startswith('-'): if arg == '--jar': i += 1 classpath.append(args[i]) classNames.update(expandjar(args[i])) jars.append(args[i]) elif arg == '--include': i += 1 classpath.append(args[i]) jars.append(args[i]) elif arg == '--package': i += 1 packages.add(args[i]) elif arg == '--classpath': i += 1 classpath.append(args[i]) elif arg == '--libpath': i += 1 libpath.append(args[i]) elif arg == '--vmarg': i += 1 vmargs.append(args[i]) elif arg == '--maxheap': i += 1 initvm_args['maxheap'] = args[i] elif arg == '--python': from .python import python, module i += 1 moduleName = args[i] elif arg == '--module': i += 1 modules.append(args[i]) elif arg == '--build': from .python import compile build = True elif arg == '--install': from .python import compile install = True elif arg == '--compile': from .python import compile recompile = True elif arg == '--egg-info': from .python import compile egg_info = True elif arg == '--extra-setup-arg': i += 1 extra_setup_args.append(args[i]) elif arg == '--output': i += 1 output = args[i] elif arg == '--debug': debug = True elif arg == '--exclude': i += 1 excludes.append(args[i]) elif arg == '--version': i += 1 version = args[i] elif arg == '--mapping': mappings[args[i + 1]] = args[i + 2] i += 2 elif arg == '--sequence': sequences[args[i + 1]] = (args[i + 2], args[i + 3]) i += 3 elif arg == '--rename': i += 1 renames.update(dict([arg.split('=') for arg in args[i].split(',')])) elif arg == '--use_full_names': use_full_names = True elif arg == '--files': i += 1 wrapperFiles = args[i] if wrapperFiles != 'separate': wrapperFiles = int(wrapperFiles) elif arg == '--prefix': i += 1 prefix = args[i] elif arg == '--root': i += 1 root = args[i] elif arg == '--install-dir': i += 1 install_dir = args[i] elif arg == '--home': i += 1 home_dir = args[i] elif arg == '--use-distutils': use_distutils = True elif arg == '--shared': shared = True elif arg == '--bdist': from .python import compile dist = True elif arg == '--wininst': from .python import compile wininst = True dist = True elif arg == '--compiler': i += 1 compiler = args[i] elif arg == '--reserved': i += 1 RESERVED.update(args[i].split(',')) elif arg == '--arch': i += 1 arch.append(args[i]) elif arg == '--no-generics': generics = False elif arg == '--find-jvm-dll': find_jvm_dll = True elif arg == '--resources': i += 1 resources.append(args[i]) elif arg == '--import': i += 1 imports[args[i]] = () else: raise ValueError("Invalid argument: %s" %(arg)) else: if ':' in arg: arg, method = arg.split(':', 1) listedMethodOrFieldNames.setdefault(arg, set()).add(method) classNames.add(arg) listedClassNames.add(arg) i += 1 if libpath: vmargs.append('-Djava.library.path=' + os.pathsep.join(libpath)) initvm_args['maxstack'] = '512k' initvm_args['vmargs'] = vmargs env = initVM(os.pathsep.join(classpath) or None, **initvm_args) typeset = set() excludes = set(excludes) if imports: if shared: imports = dict((__import__(import_), set()) for import_ in imports) else: raise ValueError("--shared must be used when using --import") if recompile or not build and (install or dist or egg_info): if moduleName is None: raise ValueError('module name not specified (use --python)') else: compile(env, os.path.dirname(args[0]), output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, home_dir, use_distutils, shared, compiler, modules, wininst, find_jvm_dll, arch, generics, resources, imports, use_full_names, egg_info, extra_setup_args) else: if imports: def walk(args, dirname, names): (include, importset) = args for name in names: if name.endswith('.h'): className = os.path.join(dirname[len(include) + 1:], name[:-2]) if os.path.sep != '/': className = className.replace(os.path.sep, '/') importset.add(findClass(className)) for import_, importset in imports.items(): env._addClassPath(import_.CLASSPATH) include = os.path.join(import_.__module_dir__, 'include') os.path.walk(include, walk, (include, importset)) typeset.update(importset) typeset.add(findClass('java/lang/Object')) typeset.add(findClass('java/lang/Class')) typeset.add(findClass('java/lang/String')) typeset.add(findClass('java/lang/Throwable')) typeset.add(findClass('java/lang/Exception')) typeset.add(findClass('java/lang/RuntimeException')) if moduleName: typeset.add(findClass('java/lang/Number')) typeset.add(findClass('java/lang/Boolean')) typeset.add(findClass('java/lang/Byte')) typeset.add(findClass('java/lang/Character')) typeset.add(findClass('java/lang/Double')) typeset.add(findClass('java/lang/Float')) typeset.add(findClass('java/lang/Integer')) typeset.add(findClass('java/lang/Long')) typeset.add(findClass('java/lang/Short')) typeset.add(findClass('java/util/Iterator')) typeset.add(findClass('java/util/Enumeration')) typeset.add(findClass('java/io/StringWriter')) typeset.add(findClass('java/io/PrintWriter')) typeset.add(findClass('java/io/Writer')) packages.add('java.lang') for className in classNames: if className.split('$', 1)[0] in excludes or className in excludes: continue cls = findClass(className.replace('.', '/')) if (Modifier.isPublic(cls.getModifiers()) or className in listedClassNames): addRequiredTypes(cls, typeset, generics) _dll_export = '' if moduleName: cppdir = os.path.join(output, '_%s' %(moduleName)) if shared and sys.platform == 'win32': _dll_export = "_dll_%s " %(moduleName) else: cppdir = output allInOne = wrapperFiles != 'separate' if allInOne: if not os.path.isdir(cppdir): os.makedirs(cppdir) if wrapperFiles <= 1: out_cpp = open(os.path.join(cppdir, '__wrap__.cpp'), 'w') else: fileCount = 1 fileName = '__wrap%02d__.cpp' %(fileCount) out_cpp = open(os.path.join(cppdir, fileName), 'w') done = set() pythonNames = {} for importset in imports.values(): done.update(importset) if moduleName: for cls in importset: name = cls.getName().rsplit('.', 1)[-1] if not use_full_names: if name in pythonNames: raise ValueError(cls, 'python class name already in use, use --rename', name, pythonNames[name]) else: pythonNames[name] = cls todo = typeset - done if allInOne and wrapperFiles > 1: classesPerFile = max(1, len(todo) / wrapperFiles) classCount = 0 while todo: for cls in todo: classCount += 1 className = cls.getName() names = className.split('.') dir = os.path.join(cppdir, *names[:-1]) if not os.path.isdir(dir): os.makedirs(dir) fileName = os.path.join(dir, names[-1]) out_h = open(fileName + '.h', "w") line(out_h, 0, '#ifndef %s_H', '_'.join(names)) line(out_h, 0, '#define %s_H', '_'.join(names)) (superClasses, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares) = \ header(env, out_h, cls, typeset, packages, excludes, generics, listedMethodOrFieldNames.get(cls.getName(), ()), _dll_export) if not allInOne: out_cpp = open(fileName + '.cpp', 'w') names, superNames = code(env, out_cpp, cls, superClasses, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares, typeset) if moduleName: name = renames.get(className) or names[-1] if not use_full_names: if name in pythonNames: raise ValueError(cls, 'python class name already in use, use --rename', name, pythonNames[name]) else: pythonNames[name] = cls python(env, out_h, out_cpp, cls, superClasses, names, superNames, constructors, methods, protectedMethods, methodNames, fields, instanceFields, mappings.get(className), sequences.get(className), renames.get(className), declares, typeset, moduleName, generics, _dll_export) line(out_h) line(out_h, 0, '#endif') out_h.close() if not allInOne: out_cpp.close() elif wrapperFiles > 1: if classCount >= classesPerFile: out_cpp.close() fileCount += 1 fileName = '__wrap%02d__.cpp' %(fileCount) out_cpp = open(os.path.join(cppdir, fileName), 'w') classCount = 0 done.update(todo) todo = typeset - done if allInOne: out_cpp.close() if moduleName: out = open(os.path.join(cppdir, moduleName) + '.cpp', 'w') module(out, allInOne, done, imports, cppdir, moduleName, shared, generics, use_full_names) out.close() if build or install or dist or egg_info: compile(env, os.path.dirname(args[0]), output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, home_dir, use_distutils, shared, compiler, modules, wininst, find_jvm_dll, arch, generics, resources, imports, use_full_names, egg_info, extra_setup_args) def header(env, out, cls, typeset, packages, excludes, generics, listedMethodOrFieldNames, _dll_export): names = cls.getName().split('.') superCls = cls.getSuperclass() superClasses = [superCls] if superCls else [] declares = set([cls.getClass()]) interfaces = [] if generics: for interface in cls.getGenericInterfaces(): if Class.instance_(interface): pt = None interface = Class.cast_(interface) elif ParameterizedType.instance_(interface): pt = ParameterizedType.cast_(interface) interface = Class.cast_(pt.getRawType()) else: raise NotImplementedError(repr(interface)) if superCls and interface.isAssignableFrom(superCls): continue if known(interface, typeset, declares, packages, excludes, False): interfaces.append(interface) if pt is not None: for ta in pt.getActualTypeArguments(): addRequiredTypes(ta, typeset, True) else: for interface in cls.getInterfaces(): if superCls and interface.isAssignableFrom(superCls): continue if known(interface, typeset, declares, packages, excludes, False): interfaces.append(interface) if cls.isInterface(): if interfaces: superClasses = interfaces[:1] else: superClasses = [findClass('java/lang/Object')] superClsNames = [superCls.getName() for superCls in superClasses] or ['JObject'] elif superClasses: superClsNames = [superCls.getName() for superCls in superClasses] if generics: for clsParam in getTypeParameters(cls): if Class.instance_(clsParam): addRequiredTypes(clsParam, typeset, True) known(clsParam, typeset, declares, packages, excludes, True) else: superClsNames = ['JObject'] constructors = [] for constructor in cls.getDeclaredConstructors(): if Modifier.isPublic(constructor.getModifiers()): if generics: genericParams = constructor.getGenericParameterTypes() params = constructor.getParameterTypes() # It appears that the implicit instance-of-the-declaring-class # parameter of a non-static inner class is missing from # getGenericParameterTypes() if len(params) == len(genericParams) + 1: params[1:] = genericParams else: params = genericParams if len(params) == 1: if params[0] == cls: continue if ParameterizedType.instance_(params[0]): param = ParameterizedType.cast_(params[0]) if param.getRawType() == cls: continue else: params = constructor.getParameterTypes() if len(params) == 1 and params[0] == cls: continue for param in params: if not known(param, typeset, declares, packages, excludes, generics): break else: constructors.append(constructor) sortSignatures(constructors) methods = {} protectedMethods = [] for method in cls.getDeclaredMethods(): if method.isSynthetic(): continue modifiers = method.getModifiers() if (Modifier.isPublic(modifiers) or method.getName() in listedMethodOrFieldNames): if generics: returnType = method.getGenericReturnType() else: returnType = method.getReturnType() if not known(returnType, typeset, declares, packages, excludes, generics): continue sig = "%s:%s" %(method.getName(), signature(method, True)) # Apparently, overridden clone() methods are still returned via # getDeclaredMethods(), so keep the one with the more precise # return type, equal to cls. if sig in methods and returnType != cls: continue if generics: params = method.getGenericParameterTypes() else: params = method.getParameterTypes() for param in params: if not known(param, typeset, declares, packages, excludes, generics): break else: methods[sig] = method elif Modifier.isProtected(modifiers): protectedMethods.append(method) methods = list(methods.values()) sortSignatures(methods, groupByName=True) methodNames = set([cppname(method.getName()) for method in methods]) for constructor in constructors: if generics: exceptions = constructor.getGenericExceptionTypes() else: exceptions = constructor.getExceptionTypes() for exception in exceptions: known(exception, typeset, declares, packages, excludes, generics) for method in methods: if generics: exceptions = method.getGenericExceptionTypes() else: exceptions = method.getExceptionTypes() for exception in exceptions: known(exception, typeset, declares, packages, excludes, generics) fields = [] instanceFields = [] for field in cls.getDeclaredFields(): modifiers = field.getModifiers() if (Modifier.isPublic(modifiers) or field.getName() in listedMethodOrFieldNames): if generics: fieldType = field.getGenericType() else: fieldType = field.getType() if not known(fieldType, typeset, declares, packages, excludes, generics): continue if Modifier.isStatic(modifiers): fields.append(field) else: instanceFields.append(field) fields.sort(key=lambda x: x.getName()) instanceFields.sort(key=lambda x: x.getName()) line(out) for superClsName in superClsNames: superNames = superClsName.split('.') line(out, 0, '#include "%s.h"', '/'.join(superNames)) line(out, 0) namespaces = {} for declare in declares: namespace = namespaces if declare is not cls and declare not in superClasses: declareNames = declare.getName().split('.') for declareName in declareNames[:-1]: namespace = namespace.setdefault(declareName, {}) namespace[declareNames[-1]] = True forward(out, namespaces, 0) line(out, 0, 'template class JArray;') indent = 0; line(out) for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out) virtual = '' line(out, indent, 'class %s%s : %s {', _dll_export, cppname(names[-1]), ', '.join(["public%s %s" %(virtual, absname(cppnames(superClsName.split('.')))) for superClsName in superClsNames])) line(out, indent, ' public:') indent += 1 if methods or protectedMethods or constructors: line(out, indent, 'enum {') for constructor in constructors: line(out, indent + 1, 'mid_init$_%s,', env.strhash(signature(constructor))) for method in methods: line(out, indent + 1, 'mid_%s_%s,', method.getName(), env.strhash(signature(method))) for method in protectedMethods: line(out, indent + 1, 'mid_%s_%s,', method.getName(), env.strhash(signature(method))) line(out, indent + 1, 'max_mid') line(out, indent, '};') if instanceFields: line(out) line(out, indent, 'enum {') for field in instanceFields: line(out, indent + 1, 'fid_%s,', field.getName()) line(out, indent + 1, 'max_fid') line(out, indent, '};') line(out) line(out, indent, 'static ::java::lang::Class *class$;'); line(out, indent, 'static jmethodID *mids$;'); if instanceFields: line(out, indent, 'static jfieldID *fids$;'); line(out, indent, 'static bool live$;'); line(out, indent, 'static jclass initializeClass(bool);'); line(out) line(out, indent, 'explicit %s(jobject obj) : %s {', cppname(names[-1]), ', '.join(['%s(obj)' %(absname(cppnames(superConstructorName.split('.')))) for superConstructorName in superClsNames])) line(out, indent + 1, 'if (obj != NULL && mids$ == NULL)'); line(out, indent + 2, 'env->getClass(initializeClass);') line(out, indent, '}') line(out, indent, '%s(const %s& obj) : %s {}', cppname(names[-1]), cppname(names[-1]), ', '.join(['%s(obj)' %(absname(cppnames(superConstructorName.split('.')))) for superConstructorName in superClsNames])) if fields: line(out) for field in fields: fieldType = field.getType() fieldName = cppname(field.getName()) if fieldName in methodNames: print(" Warning: renaming static variable '%s' on class %s to '%s%s' since it is shadowed by a method of same name." %(fieldName, '.'.join(names), fieldName, RENAME_FIELD_SUFFIX), file=sys.stderr) fieldName += RENAME_FIELD_SUFFIX if fieldType.isPrimitive(): line(out, indent, 'static %s %s;', typename(fieldType, cls, False), fieldName) else: line(out, indent, 'static %s *%s;', typename(fieldType, cls, False), fieldName) if instanceFields: line(out) for field in instanceFields: fieldType = field.getType() fieldName = field.getName() modifiers = field.getModifiers() line(out, indent, '%s _get_%s() const;', typename(fieldType, cls, False), fieldName) if not Modifier.isFinal(modifiers): line(out, indent, 'void _set_%s(%s) const;', fieldName, typename(fieldType, cls, True)) if constructors: line(out) for constructor in constructors: params = [typename(param, cls, True) for param in constructor.getParameterTypes()] line(out, indent, '%s(%s);', cppname(names[-1]), ', '.join(params)) if methods: line(out) for method in methods: modifiers = method.getModifiers() if Modifier.isStatic(modifiers): prefix = 'static ' const = '' else: prefix = '' const = ' const' params = [typename(param, cls, True) for param in method.getParameterTypes()] methodName = cppname(method.getName()) line(out, indent, '%s%s %s(%s)%s;', prefix, typename(method.getReturnType(), cls, False), methodName, ', '.join(params), const) indent -= 1 line(out, indent, '};') while indent: indent -= 1 line(out, indent, '}') return (superClasses, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares) def code(env, out, cls, superClasses, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares, typeset): className = cls.getName() names = className.split('.') if superClasses: superClsNames = [superCls.getName() for superCls in superClasses] else: superClsNames = ['JObject'] superNames = [superClsName.split('.') for superClsName in superClsNames] line(out, 0, '#include ') line(out, 0, '#include "JCCEnv.h"') line(out, 0, '#include "%s.h"', className.replace('.', '/')) for declare in declares: if declare is not cls and declare not in superClasses: line(out, 0, '#include "%s.h"', declare.getName().replace('.', '/')) line(out, 0, '#include "JArray.h"') indent = 0 line(out) for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out) line(out, indent, '::java::lang::Class *%s::class$ = NULL;', cppname(names[-1])) line(out, indent, 'jmethodID *%s::mids$ = NULL;', cppname(names[-1])) if instanceFields: line(out, indent, 'jfieldID *%s::fids$ = NULL;', cppname(names[-1])) line(out, indent, 'bool %s::live$ = false;', cppname(names[-1])) for field in fields: fieldType = field.getType() fieldName = cppname(field.getName()) if fieldName in methodNames: fieldName += RENAME_FIELD_SUFFIX typeName = typename(fieldType, cls, False) if fieldType.isPrimitive(): line(out, indent, '%s %s::%s = (%s) 0;', typeName, cppname(names[-1]), fieldName, typeName) else: line(out, indent, '%s *%s::%s = NULL;', typeName, cppname(names[-1]), fieldName) line(out) line(out, indent, 'jclass %s::initializeClass(bool getOnly)', cppname(names[-1])) line(out, indent, '{') line(out, indent + 1, 'if (getOnly)') line(out, indent + 2, 'return (jclass) (live$ ? class$->this$ : NULL);') line(out, indent + 1, 'if (class$ == NULL)') line(out, indent + 1, '{') line(out, indent + 2, 'jclass cls = (jclass) env->findClass("%s");', className.replace('.', '/')) if methods or protectedMethods or constructors: line(out) line(out, indent + 2, 'mids$ = new jmethodID[max_mid];') for constructor in constructors: sig = signature(constructor) line(out, indent + 2, 'mids$[mid_init$_%s] = env->getMethodID(cls, "", "%s");', env.strhash(sig), sig) isExtension = False for method in methods: methodName = method.getName() if methodName == 'pythonExtension': isExtension = True sig = signature(method) line(out, indent + 2, 'mids$[mid_%s_%s] = env->get%sMethodID(cls, "%s", "%s");', methodName, env.strhash(sig), Modifier.isStatic(method.getModifiers()) and 'Static' or '', methodName, sig) for method in protectedMethods: methodName = method.getName() sig = signature(method) line(out, indent + 2, 'mids$[mid_%s_%s] = env->get%sMethodID(cls, "%s", "%s");', methodName, env.strhash(sig), Modifier.isStatic(method.getModifiers()) and 'Static' or '', methodName, sig) if instanceFields: line(out) line(out, indent + 2, 'fids$ = new jfieldID[max_fid];') for field in instanceFields: fieldName = field.getName() line(out, indent + 2, 'fids$[fid_%s] = env->getFieldID(cls, "%s", "%s");', fieldName, fieldName, signature(field)) line(out) line(out, indent + 2, 'class$ = new ::java::lang::Class(cls);') if fields: line(out, indent + 2, 'cls = (jclass) class$->this$;') line(out) for field in fields: fieldType = field.getType() fieldName = field.getName() cppFieldName = cppname(fieldName) if cppFieldName in methodNames: cppFieldName += RENAME_FIELD_SUFFIX if fieldType.isPrimitive(): line(out, indent + 2, '%s = env->getStatic%sField(cls, "%s");', cppFieldName, fieldType.getName().capitalize(), fieldName) else: line(out, indent + 2, '%s = new %s(env->getStaticObjectField(cls, "%s", "%s"));', cppFieldName, typename(fieldType, cls, False), fieldName, signature(field)) line(out, indent + 2, "live$ = true;") line(out, indent + 1, '}') line(out, indent + 1, 'return (jclass) class$->this$;') line(out, indent, '}') for constructor in constructors: line(out) sig = signature(constructor) decls, args = argnames(constructor.getParameterTypes(), cls) line(out, indent, "%s::%s(%s) : %s(env->newObject(initializeClass, &mids$, mid_init$_%s%s)) {}", cppname(names[-1]), cppname(names[-1]), decls, absname(cppnames(superNames[0])), env.strhash(sig), args) for method in methods: modifiers = method.getModifiers() returnType = method.getReturnType() params = method.getParameterTypes() methodName = method.getName() superMethod = None isStatic = Modifier.isStatic(modifiers) if (isExtension and not isStatic and superClasses and Modifier.isNative(modifiers)): superMethod = find_method(superClasses[0], methodName, params) if superMethod is None: continue if isStatic: qualifier = 'Static' this = 'cls' midns = '' const = '' sig = signature(method) else: isStatic = False if superMethod is not None: qualifier = 'Nonvirtual' this = 'this$, (jclass) %s::class$->this$' %(absname(cppnames(superNames[0]))) declaringClass = superMethod.getDeclaringClass() midns = '%s::' %(typename(declaringClass, cls, False)) sig = signature(superMethod) else: qualifier = '' this = 'this$' midns = '' sig = signature(method) const = ' const' decls, args = argnames(params, cls) line(out) line(out, indent, '%s %s::%s(%s)%s', typename(returnType, cls, False), cppname(names[-1]), cppname(methodName), decls, const) line(out, indent, '{') if isStatic: line(out, indent + 1, 'jclass cls = env->getClass(initializeClass);'); if returnType.isPrimitive(): line(out, indent + 1, '%senv->call%s%sMethod(%s, %smids$[%smid_%s_%s]%s);', not returnType.getName() == 'void' and 'return ' or '', qualifier, returnType.getName().capitalize(), this, midns, midns, methodName, env.strhash(sig), args) else: line(out, indent + 1, 'return %s(env->call%sObjectMethod(%s, %smids$[%smid_%s_%s]%s));', typename(returnType, cls, False), qualifier, this, midns, midns, methodName, env.strhash(sig), args) line(out, indent, '}') if instanceFields: for field in instanceFields: fieldType = field.getType() fieldName = field.getName() line(out) line(out, indent, '%s %s::_get_%s() const', typename(fieldType, cls, False), cppname(names[-1]), fieldName) line(out, indent, '{') if fieldType.isPrimitive(): line(out, indent + 1, 'return env->get%sField(this$, fids$[fid_%s]);', fieldType.getName().capitalize(), fieldName) else: line(out, indent + 1, 'return %s(env->getObjectField(this$, fids$[fid_%s]));', typename(fieldType, cls, False), fieldName) line(out, indent, '}') if not Modifier.isFinal(field.getModifiers()): line(out) line(out, indent, 'void %s::_set_%s(%s a0) const', cppname(names[-1]), fieldName, typename(fieldType, cls, True)) line(out, indent, '{') if fieldType.isPrimitive(): line(out, indent + 1, 'env->set%sField(this$, fids$[fid_%s], a0);', fieldType.getName().capitalize(), fieldName) else: line(out, indent + 1, 'env->setObjectField(this$, fids$[fid_%s], a0.this$);', fieldName) line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') return names, superNames if __name__ == '__main__': jcc(sys.argv) JCC-3.6/jcc3/python.py0000644000076500000000000022403313457643051014715 0ustar vajdawheel00000000000000# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os, sys, platform, shutil from . import _jcc3 from .cpp import PRIMITIVES, INDENT, HALF_INDENT from .cpp import RENAME_METHOD_SUFFIX, RENAME_FIELD_SUFFIX from .cpp import cppname, cppnames, absname, typename, findClass from .cpp import line, signature, find_method, sortSignatures from .cpp import Modifier, Class, Method from .cpp import getActualTypeArguments, getTypeParameters from .config import INCLUDES, CFLAGS, DEBUG_CFLAGS, LFLAGS, IMPLIB_LFLAGS, \ SHARED, VERSION as JCC_VER try: from .cpp import ParameterizedType, TypeVariable except ImportError: pass RESULTS = { 'boolean': 'Py_RETURN_BOOL(%s);', 'byte': 'return PyLong_FromLong((long) %s);', 'char': 'return c2p(%s);', 'double': 'return PyFloat_FromDouble((double) %s);', 'float': 'return PyFloat_FromDouble((double) %s);', 'int': 'return PyLong_FromLong((long) %s);', 'long': 'return PyLong_FromLongLong((PY_LONG_LONG) %s);', 'short': 'return PyLong_FromLong((long) %s);', 'java.lang.String': 'return j2p(%s);' } CALLARGS = { 'boolean': ('O', '(%s ? Py_True : Py_False)', False), 'byte': ('O', 'PyLong_FromLong(%s)', True), 'char': ('O', 'c2p(%s);', True), 'double': ('d', '(double) %s', False), 'float': ('f', '(float) %s', False), 'int': ('i', '(int) %s', False), 'long': ('L', '(long long) %s', False), 'short': ('i', '(int) %s', False), 'java.lang.String': ('O', 'env->fromJString((jstring) %s, 0)', True) } BOXED = { 'java.lang.Boolean': (True, True), 'java.lang.Byte': (True, True), 'java.lang.Character': (True, True), 'java.lang.CharSequence': (True, False), 'java.lang.Double': (True, True), 'java.lang.Float': (True, True), 'java.lang.Integer': (True, True), 'java.lang.Long': (True, True), 'java.lang.Number': (True, False), 'java.lang.Short': (True, True), 'java.lang.String': (True, True) } def is_boxed(clsName): return BOXED.get(clsName, (False, False))[0] def is_unboxed(clsName): return BOXED.get(clsName, (False, False))[1] def parseArgs(params, current, generics, genericParams=None): def signature(cls, genericPT=None): if generics and TypeVariable.instance_(genericPT): if cls.getName() == 'java.lang.Object': gd = TypeVariable.cast_(genericPT).getGenericDeclaration() if gd == current: for clsParam in getTypeParameters(gd): if genericPT == clsParam: return 'O' array = '' while cls.isArray(): array += '[' cls = cls.getComponentType() clsName = cls.getName() if cls.isPrimitive(): return array + PRIMITIVES[clsName] if clsName == 'java.lang.String': return array + 's' if clsName == 'java.lang.Object': return array + 'o' if is_boxed(clsName): return array + 'O' if generics and getTypeParameters(cls): return array + 'K' else: return array + 'k' def checkarg(cls, genericPT=None): if generics and TypeVariable.instance_(genericPT): if cls.getName() == 'java.lang.Object': gd = TypeVariable.cast_(genericPT).getGenericDeclaration() if gd == current: i = 0 for clsParam in getTypeParameters(gd): if genericPT == clsParam: return ', self->parameters[%d]' %(i) i += 1 while cls.isArray(): cls = cls.getComponentType() clsName = cls.getName() if (cls.isPrimitive() or clsName in ('java.lang.String', 'java.lang.Object')): return '' if is_boxed(clsName): clsNames = clsName.split('.') return ', %s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) return ', %s::initializeClass' %(typename(cls, current, False)) def callarg(cls, i): if generics: while cls.isArray(): cls = cls.getComponentType() if getTypeParameters(cls): ns, sep, n = typename(cls, current, False).rpartition('::') return ', &a%d, &p%d, %s%st_%s::parameters_' %(i, i, ns, sep, n) return ', &a%d' %(i) if genericParams: sig = ''.join([signature(param, genericParam) for param, genericParam in zip(params, genericParams)]) chk = ''.join([checkarg(param, genericParam) for param, genericParam in zip(params, genericParams)]) else: sig = ''.join([signature(param) for param in params]) chk = ''.join([checkarg(param) for param in params]) return (sig, chk, ''.join([callarg(params[i], i) for i in range(len(params))])) def declareVars(out, indent, params, current, generics, typeParams): for i in range(len(params)): param = params[i] line(out, indent, '%s a%d%s;', typename(param, current, False), i, not param.isPrimitive() and '((jobject) NULL)' or '') if generics: while param.isArray(): param = param.getComponentType() if getTypeParameters(param): line(out, indent, 'PyTypeObject **p%d;', i) typeParams.add(i) def construct(out, indent, cls, inCase, constructor, names, generics): if inCase: line(out, indent, '{') indent += 1 params = constructor.getParameterTypes() if generics: typeParams = set() else: typeParams = None count = len(params) declareVars(out, indent, params, cls, generics, typeParams) line(out, indent, '%s object((jobject) NULL);', cppname(names[-1])) line(out) if count: line(out, indent, 'if (!parseArgs(args, "%s"%s%s))', *parseArgs(params, cls, generics)) line(out, indent, '{') indent += 1 line(out, indent, 'INT_CALL(object = %s(%s));', cppname(names[-1]), ', '.join(['a%d' %(i) for i in range(count)])) line(out, indent, 'self->object = object;') if generics: clsParams = getTypeParameters(cls) i = 0 for clsParam in clsParams: if Class.instance_(clsParam): cls = Class.cast_(clsParam) if cls.isArray(): cls = cls.getComponentType() if cls.isArray(): clsNames = 'java.lang.Object'.split('.') clsArg = '%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) elif cls.isPrimitive(): clsArg = 'PY_TYPE(JArray%s)' %(cls.getName().capitalize()) else: clsArg = 'PY_TYPE(JArrayObject)' else: clsNames = cls.getName().split('.') clsArg = '%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) line(out, indent, 'self->parameters[%d] = %s;', i, clsArg) i += 1 if inCase: line(out, indent, 'break;') if count: indent -= 1 line(out, indent, '}') if inCase: indent -= 1 line(out, indent, '}') def fieldValue(cls, value, fieldType): if fieldType.isArray(): fieldType = fieldType.getComponentType() if fieldType.isArray(): result = 'JArray(%s->this$).wrap(NULL)' elif fieldType.isPrimitive(): result = '%s->wrap()' elif fieldType.getName() == 'java.lang.String': result = 'JArray(%s->this$).wrap()' else: parts = typename(fieldType, cls, False).rpartition('::') result = 'JArray(%%s->this$).wrap(%s%st_%s::wrap_jobject)' %(parts) elif fieldType.getName() == 'java.lang.String': result = 'j2p(*%s)' elif not fieldType.isPrimitive(): parts = typename(fieldType, cls, False).rpartition('::') result = '%s%st_%s::wrap_Object(*%%s)' %(parts) else: return value return result %(value) def returnValue(cls, returnType, value, genericRT=None, typeParams=None): result = RESULTS.get(returnType.getName()) if result: return result %(value) if returnType.isArray(): returnType = returnType.getComponentType() depth = 1 while returnType.isArray(): returnType = returnType.getComponentType() depth += 1 if depth > 1: return 'return JArray(%s.this$).wrap(NULL);' %(value) elif returnType.isPrimitive(): return 'return %s.wrap();' %(value) elif returnType.getName() == 'java.lang.String': return 'return JArray(%s.this$).wrap();' %(value) ns, sep, n = typename(returnType, cls, False).rpartition('::') return 'return JArray(%s.this$).wrap(%s%st_%s::wrap_jobject);' %(value, ns, sep, n) ns, sep, n = typename(returnType, cls, False).rpartition('::') if genericRT is not None: if ParameterizedType.instance_(genericRT): genericRT = ParameterizedType.cast_(genericRT) clsArgs = [] for clsArg in getActualTypeArguments(genericRT): if Class.instance_(clsArg): clsArg = Class.cast_(clsArg) if clsArg.isArray(): clsArg = Class.forName('java.lang.Object') clsNames = clsArg.getName().split('.') clsArg = '%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) clsArgs.append(clsArg) elif TypeVariable.instance_(clsArg): gd = TypeVariable.cast_(clsArg).getGenericDeclaration() if Class.instance_(gd): i = 0 for clsParam in getTypeParameters(gd): if clsArg == clsParam: clsArgs.append('self->parameters[%d]' %(i)) break i += 1 else: break else: break else: break else: return 'return %s%st_%s::wrap_Object(%s, %s);' %(ns, sep, n, value, ', '.join(clsArgs)) elif TypeVariable.instance_(genericRT): gd = TypeVariable.cast_(genericRT).getGenericDeclaration() i = 0 if Class.instance_(gd): for clsParam in getTypeParameters(gd): if genericRT == clsParam: return 'return self->parameters[%d] != NULL ? wrapType(self->parameters[%d], %s.this$) : %s%st_%s::wrap_Object(%s);' %(i, i, value, ns, sep, n, value) i += 1 elif Method.instance_(gd): for clsParam in getTypeParameters(gd): if genericRT == clsParam and i in typeParams: return 'return p%d != NULL && p%d[0] != NULL ? wrapType(p%d[0], %s.this$) : %s%st_%s::wrap_Object(%s);' %(i, i, i, value, ns, sep, n, value) i += 1 return 'return %s%st_%s::wrap_Object(%s);' %(ns, sep, n, value) def call(out, indent, cls, inCase, method, names, cardinality, isExtension, generics): if inCase: line(out, indent, '{') indent += 1 name = method.getName() modifiers = method.getModifiers() params = method.getParameterTypes() returnType = method.getReturnType() if generics: genericRT = method.getGenericReturnType() genericParams = method.getGenericParameterTypes() typeParams = set() else: genericRT = None genericParams = None typeParams = None count = len(params) declareVars(out, indent, params, cls, generics, typeParams) returnName = returnType.getName() if returnName != 'void': line(out, indent, '%s result%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') result = 'result = ' else: result = '' if cardinality and (count or not inCase): s = cardinality > 1 and 's' or '' line(out) if isExtension and name == 'clone' and Modifier.isNative(modifiers): line(out, indent, 'if (arg)') else: line(out, indent, 'if (!parseArg%s(arg%s, "%s"%s%s))', s, s, *parseArgs(params, cls, generics, genericParams)) line(out, indent, '{') indent += 1 name = cppname(name) if Modifier.isStatic(modifiers): line(out, indent, 'OBJ_CALL(%s%s::%s(%s));', result, absname(cppnames(names)), name, ', '.join(['a%d' %(i) for i in range(count)])) else: line(out, indent, 'OBJ_CALL(%sself->object.%s(%s));', result, name, ', '.join(['a%d' %(i) for i in range(count)])) if isExtension and name == 'clone' and Modifier.isNative(modifiers): line(out) line(out, indent, '%s object(result.this$);', typename(cls, cls, False)) line(out, indent, 'if (PyObject_TypeCheck(arg, PY_TYPE(FinalizerProxy)) &&') line(out, indent, ' PyObject_TypeCheck(((t_fp *) arg)->object, Py_TYPE(self)))') line(out, indent, '{') line(out, indent + 1, 'PyObject *_arg = ((t_fp *) arg)->object;') line(out, indent + 1, '((t_JObject *) _arg)->object = object;') line(out, indent + 1, 'Py_INCREF(_arg);') line(out, indent + 1, 'object.pythonExtension((jlong) (Py_intptr_t) (void *) _arg);') line(out, indent + 1, 'Py_INCREF(arg);') line(out, indent + 1, 'return arg;') line(out, indent, '}') line(out, indent, 'return PyErr_SetArgsError("%s", arg);' %(name)) elif returnName != 'void': line(out, indent, returnValue(cls, returnType, 'result', genericRT, typeParams)) else: line(out, indent, 'Py_RETURN_NONE;') if cardinality and (count or not inCase): indent -= 1 line(out, indent, '}') if inCase: indent -= 1 line(out, indent, '}') def methodargs(methods, superMethods): if len(methods) == 1 and methods[0].getName() not in superMethods: count = len(methods[0].getParameterTypes()) if count == 0: return '', '', 0 elif count == 1: return ', PyObject *arg', ', arg', 1 return ', PyObject *args', ', args', 2 def jniname(cls): if cls.isPrimitive(): name = cls.getName() if name != 'void': name = 'j' + name else: name = 'jobject' return name def jniargs(params): count = len(params) decls = ', '.join(['%s a%d' %(jniname(params[i]), i) for i in range(count)]) if decls: return ', ' + decls return '' def wrapper_typename(returnType, cls): if returnType.isArray(): componentType = returnType.getComponentType() componentName = typename(componentType, cls, False) if componentType.isPrimitive(): return "t_JArrayWrapper< %s >" %(componentName) ns, sep, n = componentName.rpartition('::') return "t_JArrayWrapper< jobject,%s%st_%s >" %(ns, sep, n) returnName = typename(returnType, cls, False) ns, sep, n = returnName.rpartition('::') return "%s%st_%s" %(ns, sep, n) def extension(env, out, indent, cls, names, name, count, method, generics): line(out, indent, 'jlong ptr = jenv->CallLongMethod(jobj, %s::mids$[%s::mid_pythonExtension_%s]);', cppname(names[-1]), cppname(names[-1]), env.strhash('()J')) line(out, indent, 'PyObject *obj = (PyObject *) (Py_intptr_t) ptr;') if name == 'pythonDecRef': line(out) line(out, indent, 'if (obj != NULL)') line(out, indent, '{') line(out, indent + 1, 'jenv->CallVoidMethod(jobj, %s::mids$[%s::mid_pythonExtension_%s], (jlong) 0);', cppname(names[-1]), cppname(names[-1]), env.strhash('(J)V')) line(out, indent + 1, 'env->finalizeObject(jenv, obj);') line(out, indent, '}') return line(out, indent, 'PythonGIL gil(jenv);') returnType = method.getReturnType() returnName = returnType.getName() if returnName != 'void': line(out, indent, '%s value%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') sigs = [] decrefs = [] args = [] i = 0 for param in method.getParameterTypes(): typeName = param.getName() if typeName in CALLARGS: sig, code, decref = CALLARGS[typeName] elif param.isArray(): param = param.getComponentType() if param.isPrimitive(): code = 'JArray(%%s).wrap()' %(param.getName()) elif param.isArray(): code = 'JArray(%s).wrap(NULL)' elif param.getName() == 'java.lang.String': code = 'JArray(%s).wrap()' else: parts = typename(param, cls, False).rpartition('::') code = 'JArray(%%s).wrap(%s%st_%s::wrap_jobject)' %(parts) sig, decref = 'O', True elif param.getName() == 'java.lang.String': sig, code, decref = 'O', 'j2p(%%s))', True else: parts = typename(param, cls, False).rpartition('::') sig, code, decref = 'O', '%s%st_%s::wrap_Object(%s%s%s(%%s))' %(parts*2), True if sig == 'O': line(out, indent, 'PyObject *o%d = %s;', i, code %('a%d' %(i))) args.append('o%d' %(i)) else: args.append(code %('a%d' %(i))) sigs.append(sig) decrefs.append(decref) i += 1 args = ', '.join(args) if args: args = ', ' + args line(out, indent, 'PyObject *result = PyObject_CallMethod(obj, "%s", "%s"%s);', name, ''.join(sigs), args) i = 0 for decref in decrefs: if decref: line(out, indent, 'Py_DECREF(o%d);', i) i += 1 line(out, indent, 'if (!result)') line(out, indent + 1, 'throwPythonError();') if returnName == 'void': line(out, indent, 'else') line(out, indent + 1, 'Py_DECREF(result);') else: signature, check, x = parseArgs([returnType], cls, False) line(out, indent, 'else if (parseArg(result, "%s"%s, &value))', signature, check) line(out, indent, '{') line(out, indent + 1, 'throwTypeError("%s", result);', name) line(out, indent + 1, 'Py_DECREF(result);') line(out, indent, '}') line(out, indent, 'else') line(out, indent, '{') if not returnType.isPrimitive(): line(out, indent + 1, 'jobj = jenv->NewLocalRef(value.this$);') line(out, indent + 1, 'Py_DECREF(result);') if returnType.isPrimitive(): line(out, indent + 1, 'return value;') else: line(out, indent + 1, 'return jobj;') line(out, indent, '}') line(out) if returnType.isPrimitive(): line(out, indent, 'return (j%s) 0;', returnName) else: line(out, indent, 'return (jobject) NULL;') def python(env, out_h, out, cls, superClasses, names, superNames, constructors, methods, protectedMethods, methodNames, fields, instanceFields, mapping, sequence, rename, declares, typeset, moduleName, generics, _dll_export): line(out_h) line(out_h, 0, '#include ') line(out_h) indent = 0 for name in names[:-1]: line(out_h, indent, 'namespace %s {', cppname(name)) indent += 1 line(out_h, indent, '%sextern PyType_Def PY_TYPE_DEF(%s);', _dll_export, names[-1]) line(out_h, indent, '%sextern PyTypeObject *PY_TYPE(%s);', _dll_export, names[-1]) if generics: clsParams = getTypeParameters(cls) else: clsParams = None line(out_h) line(out_h, indent, 'class %st_%s {', _dll_export, names[-1]) line(out_h, indent, 'public:') line(out_h, indent + 1, 'PyObject_HEAD') line(out_h, indent + 1, '%s object;', cppname(names[-1])) if clsParams: line(out_h, indent + 1, 'PyTypeObject *parameters[%d];', len(clsParams)) line(out_h, indent + 1, 'static PyTypeObject **parameters_(t_%s *self)', cppname(names[-1])) line(out_h, indent + 1, '{') line(out_h, indent + 2, 'return (PyTypeObject **) &(self->parameters);') line(out_h, indent + 1, '}') line(out_h, indent + 1, 'static PyObject *wrap_Object(const %s&);', cppname(names[-1])) line(out_h, indent + 1, 'static PyObject *wrap_jobject(const jobject&);') if clsParams: _clsParams = ', '.join(['PyTypeObject *'] * len(clsParams)) line(out_h, indent + 1, 'static PyObject *wrap_Object(const %s&, %s);', cppname(names[-1]), _clsParams) line(out_h, indent + 1, 'static PyObject *wrap_jobject(const jobject&, %s);', _clsParams) line(out_h, indent + 1, 'static void install(PyObject *module);') line(out_h, indent + 1, 'static void initialize(PyObject *module);') line(out_h, indent, '};') if env.java_version >= '1.5': iterable = findClass('java/lang/Iterable') iterator = findClass('java/util/Iterator') else: iterable = iterator = None enumeration = findClass('java/util/Enumeration') while indent: indent -= 1 line(out_h, indent, '}') line(out) line(out, 0, '#include "structmember.h"') line(out, 0, '#include "functions.h"') line(out, 0, '#include "macros.h"') for inner in cls.getDeclaredClasses(): if inner in typeset and not inner in declares: if Modifier.isStatic(inner.getModifiers()): line(out, 0, '#include "%s.h"', inner.getName().replace('.', '/')) for method in methods: if method.getName() == 'pythonExtension': isExtension = True break else: isExtension = False line(out) indent = 0 for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out, indent, 'static PyObject *t_%s_cast_(PyTypeObject *type, PyObject *arg);', names[-1]) line(out, indent, 'static PyObject *t_%s_instance_(PyTypeObject *type, PyObject *arg);', names[-1]) if clsParams: line(out, indent, 'static PyObject *t_%s_of_(t_%s *self, PyObject *args);', names[-1], names[-1]) if constructors: line(out, indent, 'static int t_%s_init_(t_%s *self, PyObject *args, PyObject *kwds);', names[-1], names[-1]) constructorName = 't_%s_init_' %(names[-1]) else: constructorName = 'abstract_init' if superClasses: superMethods = set([method.getName() for superCls in superClasses for method in superCls.getMethods()]) else: superMethods = () allMethods = {} extMethods = {} propMethods = {} if methods: for method in methods: modifiers = method.getModifiers() name = method.getName() params = method.getParameterTypes() superMethod = None isNative = Modifier.isNative(modifiers) isStatic = Modifier.isStatic(modifiers) if (isExtension and not isStatic and superClasses and isNative): superMethod = find_method(superClasses[0], name, params) if isExtension and isNative and not isStatic: extMethods.setdefault(name, []).append(method) if superMethod or not (isExtension and isNative and not isStatic): if isStatic: if name in allMethods: if Modifier.isStatic(allMethods[name][0].getModifiers()): allMethods[name].append(method) elif name + RENAME_METHOD_SUFFIX in allMethods: allMethods[name + RENAME_METHOD_SUFFIX].append(method) else: print(" Warning: renaming static method '%s' on class %s to '%s%s' since it is shadowed by non-static method of same name." %(name, '.'.join(names), name, RENAME_METHOD_SUFFIX), file=sys.stderr) allMethods[name + RENAME_METHOD_SUFFIX] = [method] else: allMethods[name] = [method] else: if name in allMethods: if Modifier.isStatic(allMethods[name][0].getModifiers()): print(" Warning: renaming static method '%s' on class %s to '%s%s' since it is shadowed by non-static method of same name." %(name, '.'.join(names), name, RENAME_METHOD_SUFFIX), file=sys.stderr) allMethods[name + RENAME_METHOD_SUFFIX] = allMethods[name] allMethods[name] = [method] else: allMethods[name].append(method) else: allMethods[name] = [method] if not (isExtension and isNative): nameLen = len(name) paramsLen = len(params) if nameLen > 3 and paramsLen == 0 and name.startswith('get'): if method.getReturnType().getName() != 'void': propMethods.setdefault(name[3].lower() + name[4:], []).append(method) elif nameLen > 3 and paramsLen == 1 and name.startswith('set'): propMethods.setdefault(name[3].lower() + name[4:], []).append(method) elif nameLen > 2 and paramsLen == 0 and name.startswith('is'): if method.getReturnType().getName() != 'void': propMethods.setdefault(name[2].lower() + name[3:], []).append(method) properties = set([name for name in propMethods.keys() if name not in allMethods]) propMethods = [(name, propMethods[name]) for name in properties] propMethods.sort(key=lambda x: x[0]) extMethods = list(extMethods.items()) extMethods.sort(key=lambda x: x[0]) allMethods = list(allMethods.items()) allMethods.sort(key=lambda x: x[0]) iteratorMethod = None iteratorExt = False nextMethod = None nextExt = False nextElementMethod = None nextElementExt = False mappingMethod = None if mapping: mappingName, mappingSig = mapping.split(':') sequenceLenMethod = None sequenceGetMethod = None if sequence: sequenceLenName, sequenceLenSig = sequence[0].split(':') sequenceGetName, sequenceGetSig = sequence[1].split(':') for name, methods in allMethods: args, x, cardinality = methodargs(methods, superMethods) sortSignatures(methods) method = methods[0] modifiers = method.getModifiers() if name == 'iterator' and iteratorMethod is None: if (iterable is not None and not method.getParameterTypes() and iterable.isAssignableFrom(cls) and iterator.isAssignableFrom(method.getReturnType())): iteratorMethod = method elif name == 'next' and nextMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextMethod = method elif name == 'nextElement' and nextElementMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextElementMethod = method elif mapping and name == mappingName and mappingMethod is None: if signature(method) == mappingSig: mappingMethod = (method, cardinality) elif sequence and name == sequenceLenName and sequenceLenMethod is None: if signature(method) == sequenceLenSig: sequenceLenMethod = (method, cardinality) elif sequence and name == sequenceGetName and sequenceGetMethod is None: if signature(method) == sequenceGetSig: sequenceGetMethod = (method, cardinality) elif isExtension and name == 'clone' and Modifier.isNative(modifiers): args, x, cardinality = ', PyObject *arg', ', arg', 1 if Modifier.isStatic(modifiers): line(out, indent, 'static PyObject *t_%s_%s(PyTypeObject *type%s);', names[-1], name, args) else: line(out, indent, 'static PyObject *t_%s_%s(t_%s *self%s);', names[-1], name, names[-1], args) for name, methods in extMethods: args, x, cardinality = methodargs(methods, superMethods) sortSignatures(methods) method = methods[0] modifiers = method.getModifiers() if name == 'iterator' and iteratorMethod is None: if (iterable is not None and not method.getParameterTypes() and iterable.isAssignableFrom(cls) and iterator.isAssignableFrom(method.getReturnType())): iteratorMethod = method iteratorExt = True elif name == 'next' and nextMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextMethod = method nextExt = True elif name == 'nextElement' and nextElementMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextElementMethod = method nextElementExt = True if isExtension: count = 0 for name, methods in extMethods: for method in methods: line(out, indent, 'static %s JNICALL t_%s_%s%d(JNIEnv *jenv, jobject jobj%s);', jniname(method.getReturnType()), names[-1], name, count, jniargs(method.getParameterTypes())) count += 1 line(out, indent, 'static PyObject *t_%s_get__self(t_%s *self, void *data);', names[-1], names[-1]) if instanceFields: for field in instanceFields: fieldName = field.getName() if fieldName not in properties: line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data);', names[-1], fieldName, names[-1]) if not Modifier.isFinal(field.getModifiers()): line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data);', names[-1], field.getName(), names[-1]) line(out) for fieldName, methods in propMethods: getter = False setter = False for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = True line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data);', names[-1], fieldName, names[-1]) elif not setter and methodName.startswith('set'): setter = True line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data);', names[-1], fieldName, names[-1]) if clsParams: line(out, indent, 'static PyObject *t_%s_get__parameters_(t_%s *self, void *data);', names[-1], names[-1]) if instanceFields or propMethods or isExtension or clsParams: line(out, indent, 'static PyGetSetDef t_%s__fields_[] = {', names[-1]) for field in instanceFields: fieldName = field.getName() if fieldName not in properties: if Modifier.isFinal(field.getModifiers()): line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, %s),', names[-1], fieldName) else: line(out, indent + 1, 'DECLARE_GETSET_FIELD(t_%s, %s),', names[-1], fieldName) for fieldName, methods in propMethods: getter = False setter = False for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = True elif not setter and methodName.startswith('set'): setter = True if getter and setter: op = 'GETSET' elif getter: op = 'GET' elif setter: op = 'SET' line(out, indent + 1, 'DECLARE_%s_FIELD(t_%s, %s),', op, names[-1], fieldName) if isExtension: line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, self),', names[-1]) if clsParams: line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, parameters_),', names[-1]) line(out, indent + 1, '{ NULL, NULL, NULL, NULL, NULL }') line(out, indent, '};') line(out) line(out, indent, 'static PyMethodDef t_%s__methods_[] = {', names[-1]) line(out, indent + 1, 'DECLARE_METHOD(t_%s, cast_, METH_O | METH_CLASS),', names[-1]) line(out, indent + 1, 'DECLARE_METHOD(t_%s, instance_, METH_O | METH_CLASS),', names[-1]) if clsParams: line(out, indent + 1, 'DECLARE_METHOD(t_%s, of_, METH_VARARGS),', names[-1]) for name, methods in allMethods: modifiers = methods[0].getModifiers() if len(methods) == 1 and not name in superMethods: count = len(methods[0].getParameterTypes()) if count == 0: args = 'METH_NOARGS' elif count == 1: args = 'METH_O' else: args = 'METH_VARARGS' elif isExtension and name == 'clone' and Modifier.isNative(modifiers): args = 'METH_O' else: args = 'METH_VARARGS' if Modifier.isStatic(modifiers): args += ' | METH_CLASS' line(out, indent + 1, 'DECLARE_METHOD(t_%s, %s, %s),', names[-1], name, args) line(out, indent + 1, '{ NULL, NULL, 0, NULL }') line(out, indent, '};') if instanceFields or propMethods or isExtension or clsParams: tp_getset = 't_%s__fields_' %(names[-1]) else: tp_getset = None if iteratorMethod: if iteratorExt: tp_iter = 'get_extension_iterator' else: tp_iter = '((PyObject *(*)(t_%s *)) get_%siterator< t_%s >)' %(names[-1], clsParams and 'generic_' or '', names[-1]) tp_iternext = '0' elif nextMethod and iterable is not None and iterator.isAssignableFrom(cls): tp_iter = 'PyObject_SelfIter' if nextExt: tp_iternext = 'get_extension_next' else: tp_iternext = '((PyObject *(*)(::java::util::t_Iterator *)) get_%siterator_next< ::java::util::t_Iterator,%s >)' %(clsParams and 'generic_' or '', wrapper_typename(nextMethod.getReturnType(), cls)) elif nextElementMethod and enumeration.isAssignableFrom(cls): tp_iter = 'PyObject_SelfIter' returnName = typename(nextElementMethod.getReturnType(), cls, False) ns, sep, n = returnName.rpartition('::') if nextElementExt: tp_iternext = 'get_extension_nextElement' else: tp_iternext = '((PyObject *(*)(::java::util::t_Enumeration *)) get_%senumeration_next< ::java::util::t_Enumeration,%s >)' %(clsParams and 'generic_' or '', wrapper_typename(nextElementMethod.getReturnType(), cls)) elif nextMethod: tp_iter = 'PyObject_SelfIter' if nextExt: tp_iternext = 'get_extension_next' else: returnType = nextMethod.getReturnType() tp_iternext = '((PyObject *(*)(t_%s *)) get_%snext< t_%s,%s,%s >)' %(names[-1], clsParams and 'generic_' or '', names[-1], wrapper_typename(returnType, cls), typename(returnType, cls, False)) else: tp_iter = None tp_iternext = None if mappingMethod: method, cardinality = mappingMethod if cardinality > 1: mp_subscript = 't_%s_%s_map_' %(names[-1], method.getName()) line(out, indent, 'static PyObject *%s(t_%s *self, PyObject *key);', mp_subscript, names[-1]) else: mp_subscript = 't_%s_%s' %(names[-1], method.getName()) else: mp_subscript = None if sequenceLenMethod: method, cardinality = sequenceLenMethod sq_length = 't_%s_%s_seq_' %(names[-1], method.getName()) line(out, indent, 'static int %s(t_%s *self);', sq_length, names[-1]) else: sq_length = None if sequenceGetMethod: method, cardinality = sequenceGetMethod sq_item = 't_%s_%s_seq_' %(names[-1], method.getName()) line(out, indent, 'static PyObject *%s(t_%s *self, int n);', sq_item, names[-1]) else: sq_item = None line(out) line(out, indent, 'static PyType_Slot PY_TYPE_SLOTS(%s)[] = {', names[-1]) line(out, indent + 1, '{ Py_tp_methods, t_%s__methods_ },', names[-1]) line(out, indent + 1, '{ Py_tp_init, (void *) %s },', constructorName) if tp_getset is not None: line(out, indent + 1, '{ Py_tp_getset, %s },', tp_getset) if tp_iter is not None: line(out, indent + 1, '{ Py_tp_iter, (void *) %s },', tp_iter) line(out, indent + 1, '{ Py_tp_iternext, (void *) %s },', tp_iternext) if mp_subscript is not None: line(out, indent + 1, '{ Py_mp_subscript, (void *) %s },', mp_subscript) if sq_length is not None: line(out, indent + 1, '{ Py_sq_length, (void *) %s },', sq_length) if sq_item is not None: line(out, indent + 1, '{ Py_sq_item, (void *) %s },', sq_item) line(out, indent + 1, '{ 0, NULL }') line(out, indent, '};') line(out) line(out, indent, 'static PyType_Def *PY_TYPE_BASES(%s)[] = {', names[-1]) for superName in superNames: if len(superName) > 1: base = '::'.join((absname(cppnames(superName[:-1])), superName[-1])) else: base = superName[-1] line(out, indent + 1, '&PY_TYPE_DEF(%s),', base) line(out, indent + 1, 'NULL') line(out, indent, '};') line(out) line(out, indent, 'DEFINE_TYPE(%s, t_%s, %s);', names[-1], names[-1], cppname(names[-1])) if clsParams: clsArgs = [] i = 0 for clsParam in clsParams: clsArgs.append("PyTypeObject *p%d" %(i)) i += 1 line(out, indent, "PyObject *t_%s::wrap_Object(const %s& object, %s)", cppname(names[-1]), names[-1], ', '.join(clsArgs)) line(out, indent, "{") line(out, indent + 1, "PyObject *obj = t_%s::wrap_Object(object);", names[-1]) line(out, indent + 1, "if (obj != NULL && obj != Py_None)") line(out, indent + 1, "{") line(out, indent + 2, "t_%s *self = (t_%s *) obj;", names[-1], names[-1]) i = 0; for clsParam in clsParams: line(out, indent + 2, "self->parameters[%d] = p%d;", i, i) i += 1 line(out, indent + 1, "}") line(out, indent + 1, "return obj;"); line(out, indent, "}") line(out) line(out, indent, "PyObject *t_%s::wrap_jobject(const jobject& object, %s)", cppname(names[-1]), ', '.join(clsArgs)) line(out, indent, "{") line(out, indent + 1, "PyObject *obj = t_%s::wrap_jobject(object);", names[-1]) line(out, indent + 1, "if (obj != NULL && obj != Py_None)") line(out, indent + 1, "{") line(out, indent + 2, "t_%s *self = (t_%s *) obj;", names[-1], names[-1]) i = 0; for clsParam in clsParams: line(out, indent + 2, "self->parameters[%d] = p%d;", i, i) i += 1 line(out, indent + 1, "}") line(out, indent + 1, "return obj;"); line(out, indent, "}") line(out) line(out, indent, 'void t_%s::install(PyObject *module)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'installType(&PY_TYPE(%s), &PY_TYPE_DEF(%s), module, "%s", %d);', names[-1], names[-1], rename or names[-1], isExtension and 1 or 0) for inner in cls.getDeclaredClasses(): if inner in typeset: if Modifier.isStatic(inner.getModifiers()): innerName = inner.getName().split('.')[-1] line(out, indent + 1, 'PyObject_SetAttrString((PyObject *) PY_TYPE(%s), "%s", make_descriptor(&PY_TYPE_DEF(%s)));', names[-1], innerName[len(names[-1])+1:], innerName) line(out, indent, '}') line(out) line(out, indent, 'void t_%s::initialize(PyObject *module)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'PyObject_SetAttrString((PyObject *) PY_TYPE(%s), "class_", make_descriptor(%s::initializeClass, %s));', names[-1], cppname(names[-1]), generics and 1 or 0) if is_unboxed(cls.getName()): wrapfn_ = "unbox%s" %(names[-1]) boxfn_ = "box%s" %(names[-1]) else: wrapfn_ = "t_%s::wrap_jobject" %(names[-1]) boxfn_ = "boxObject" line(out, indent + 1, 'PyObject_SetAttrString((PyObject *) PY_TYPE(%s), "wrapfn_", make_descriptor(%s));', names[-1], wrapfn_) line(out, indent + 1, 'PyObject_SetAttrString((PyObject *) PY_TYPE(%s), "boxfn_", make_descriptor(%s));', names[-1], boxfn_) if isExtension: line(out, indent + 1, 'jclass cls = env->getClass(%s::initializeClass);', cppname(names[-1])) elif fields: line(out, indent + 1, 'env->getClass(%s::initializeClass);', cppname(names[-1])) if isExtension: count = 0 line(out, indent + 1, 'JNINativeMethod methods[] = {') for name, methods in extMethods: for method in methods: line(out, indent + 2, '{ "%s", "%s", (void *) t_%s_%s%d },', name, signature(method), names[-1], name, count) count += 1 line(out, indent + 1, '};') line(out, indent + 1, 'env->registerNatives(cls, methods, %d);', count) for field in fields: fieldType = field.getType() fieldName = field.getName() cppFieldName = cppname(fieldName) if cppFieldName in methodNames: fieldName += RENAME_FIELD_SUFFIX cppFieldName += RENAME_FIELD_SUFFIX value = '%s::%s' %(cppname(names[-1]), cppFieldName) value = fieldValue(cls, value, fieldType) line(out, indent + 1, 'PyObject_SetAttrString((PyObject *) PY_TYPE(%s), "%s", make_descriptor(%s));', names[-1], fieldName, value) line(out, indent, '}') line(out) line(out, indent, 'static PyObject *t_%s_cast_(PyTypeObject *type, PyObject *arg)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!(arg = castCheck(arg, %s::initializeClass, 1)))', cppname(names[-1])) line(out, indent + 2, 'return NULL;') line(out, indent + 1, 'return t_%s::wrap_Object(%s(((t_%s *) arg)->object.this$));', names[-1], cppname(names[-1]), names[-1]) line(out, indent, '}') line(out, indent, 'static PyObject *t_%s_instance_(PyTypeObject *type, PyObject *arg)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!castCheck(arg, %s::initializeClass, 0))', cppname(names[-1])) line(out, indent + 2, 'Py_RETURN_FALSE;') line(out, indent + 1, 'Py_RETURN_TRUE;') line(out, indent, '}') if clsParams: line(out) line(out, indent, 'static PyObject *t_%s_of_(t_%s *self, PyObject *args)', names[-1], names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!parseArg(args, "T", %d, &(self->parameters)))', len(clsParams)) line(out, indent + 2, 'Py_RETURN_SELF;'); line(out, indent + 1, 'return PyErr_SetArgsError((PyObject *) self, "of_", args);') line(out, indent, '}') if constructors: line(out) line(out, indent, 'static int t_%s_init_(t_%s *self, PyObject *args, PyObject *kwds)', names[-1], names[-1]) line(out, indent, '{') if len(constructors) > 1: currLen = -1 line(out, indent + 1, 'switch (PyTuple_GET_SIZE(args)) {') withErr = False for constructor in constructors: params = constructor.getParameterTypes() if len(params) != currLen: if currLen > 0: withErr = True line(out, indent + 2, 'goto err;') currLen = len(params) line(out, indent + 1, '%scase %d:', HALF_INDENT, currLen) construct(out, indent + 2, cls, True, constructor, names, generics) line(out, indent + 1, '%sdefault:', HALF_INDENT) if withErr: line(out, indent + 1, '%serr:', HALF_INDENT) line(out, indent + 2, 'PyErr_SetArgsError((PyObject *) self, "__init__", args);') line(out, indent + 2, 'return -1;') line(out, indent + 1, '}') else: construct(out, indent + 1, cls, False, constructors[0], names, generics) if constructors[0].getParameterTypes(): line(out, indent + 1, 'else') line(out, indent + 1, '{') line(out, indent + 2, 'PyErr_SetArgsError((PyObject *) self, "__init__", args);') line(out, indent + 2, 'return -1;') line(out, indent + 1, '}') if isExtension: line(out) line(out, indent + 1, 'Py_INCREF((PyObject *) self);') line(out, indent + 1, 'self->object.pythonExtension((jlong) (Py_intptr_t) (void *) self);') line(out) line(out, indent + 1, 'return 0;') line(out, indent , '}') for name, methods in allMethods: line(out) modifiers = methods[0].getModifiers() if isExtension and name == 'clone' and Modifier.isNative(modifiers): declargs, args, cardinality = ', PyObject *arg', ', arg', 1 else: declargs, args, cardinality = methodargs(methods, superMethods) static = Modifier.isStatic(modifiers) if static: line(out, indent, 'static PyObject *t_%s_%s(PyTypeObject *type%s)', names[-1], name, declargs) else: line(out, indent, 'static PyObject *t_%s_%s(t_%s *self%s)', names[-1], name, names[-1], declargs) line(out, indent, '{') if len(methods) > 1: currLen = -1 line(out, indent + 1, 'switch (PyTuple_GET_SIZE(args)) {') for method in methods: params = method.getParameterTypes() if len(params) != currLen: if currLen >= 0: line(out, indent + 2, 'break;') currLen = len(params) line(out, indent + 1, '%scase %d:', HALF_INDENT, currLen) call(out, indent + 2, cls, True, method, names, cardinality, isExtension, generics) line(out, indent + 1, '}') else: call(out, indent + 1, cls, False, methods[0], names, cardinality, isExtension, generics) if args: line(out) if name in superMethods: if static: line(out, indent + 1, 'return callSuper(type, "%s"%s, %d);', name, args, cardinality) else: line(out, indent + 1, 'return callSuper(PY_TYPE(%s), (PyObject *) self, "%s"%s, %d);', names[-1], name, args, cardinality) else: line(out, indent + 1, 'PyErr_SetArgsError(%s, "%s"%s);', static and 'type' or '(PyObject *) self', name, args) line(out, indent + 1, 'return NULL;') line(out, indent, '}') if isExtension: count = 0 for name, methods in extMethods: for method in methods: line(out) line(out, indent, 'static %s JNICALL t_%s_%s%d(JNIEnv *jenv, jobject jobj%s)', jniname(method.getReturnType()), names[-1], name, count, jniargs(method.getParameterTypes())) count += 1 line(out, indent, '{') extension(env, out, indent + 1, cls, names, name, count, method, generics) line(out, indent, '}') line(out) line(out, indent, 'static PyObject *t_%s_get__self(t_%s *self, void *data)', names[-1], names[-1]) line(out, indent, '{') indent += 1 line(out, indent, 'jlong ptr;') line(out, indent, 'OBJ_CALL(ptr = self->object.pythonExtension());') line(out, indent, 'PyObject *obj = (PyObject *) (Py_intptr_t) ptr;') line(out) line(out, indent, 'if (obj != NULL)') line(out, indent, '{') line(out, indent + 1, 'Py_INCREF(obj);') line(out, indent + 1, 'return obj;') line(out, indent, '}') line(out, indent, 'else') line(out, indent + 1, 'Py_RETURN_NONE;') indent -= 1 line(out, indent, '}') if clsParams: line(out, indent, 'static PyObject *t_%s_get__parameters_(t_%s *self, void *data)', names[-1], names[-1]) line(out, indent, '{') line(out, indent + 1, 'return typeParameters(self->parameters, sizeof(self->parameters));') line(out, indent, '}') if instanceFields: for field in instanceFields: fieldName = field.getName() if fieldName not in properties: line(out) fieldType = field.getType() typeName = typename(fieldType, cls, False) line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not fieldType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(value = self->object._get_%s());', fieldName) line(out, indent + 1, returnValue(cls, fieldType, 'value')) line(out, indent, '}') if not Modifier.isFinal(field.getModifiers()): line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not fieldType.isPrimitive() and '((jobject) NULL)' or '') sig, check, x = parseArgs([fieldType], cls, False) line(out, indent + 1, 'if (!parseArg(arg, "%s"%s, &value))', sig, check) line(out, indent + 1, '{') line(out, indent + 2, 'INT_CALL(self->object._set_%s(value));', fieldName) line(out, indent + 2, 'return 0;') line(out, indent + 1, '}') line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', fieldName) line(out, indent + 1, 'return -1;') line(out, indent, '}') if propMethods: for fieldName, methods in propMethods: line(out) getter = None setters = [] methods.sort(key=lambda x: x.getName()) for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = method elif methodName.startswith('set'): setters.append(method) if getter: methodName = getter.getName() returnType = getter.getReturnType() typeName = typename(returnType, cls, False) line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not returnType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(value = self->object.%s());', methodName) line(out, indent + 1, returnValue(cls, returnType, 'value')) line(out, indent, '}') if setters: line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') methodName = setters[0].getName() for method in setters: argType = method.getParameterTypes()[0] typeName = typename(argType, cls, False) line(out, indent + 1, '{') line(out, indent + 2, '%s value%s;', typeName, not argType.isPrimitive() and '((jobject) NULL)' or '') sig, check, x = parseArgs([argType], cls, False) line(out, indent + 2, 'if (!parseArg(arg, "%s"%s, &value))', sig, check) line(out, indent + 2, '{') line(out, indent + 3, 'INT_CALL(self->object.%s(value));', methodName) line(out, indent + 3, 'return 0;') line(out, indent + 2, '}') line(out, indent + 1, '}') line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', fieldName) line(out, indent + 1, 'return -1;') line(out, indent, '}') if mappingMethod: method, cardinality = mappingMethod if cardinality > 1: methodName = method.getName() getName = 't_%s_%s_map_' %(names[-1], methodName) line(out) line(out, indent, 'static PyObject *%s(t_%s *self, PyObject *arg)', getName, names[-1]) line(out, indent, '{') call(out, indent + 1, cls, False, method, names, 1, isExtension, generics) line(out) line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', methodName) line(out, indent + 1, 'return NULL;') line(out, indent, '}') if sequenceLenMethod: method, cardinality = sequenceLenMethod methodName = method.getName() lenName = 't_%s_%s_seq_' %(names[-1], methodName) line(out) line(out, indent, 'static int %s(t_%s *self)', lenName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s len;', typename(method.getReturnType(), cls, False)) line(out, indent + 1, 'INT_CALL(len = self->object.%s());', methodName) line(out, indent + 1, 'return (int) len;') line(out, indent, '}') if sequenceGetMethod: method, cardinality = sequenceGetMethod methodName = method.getName() returnType = method.getReturnType() getName = 't_%s_%s_seq_' %(names[-1], methodName) line(out) line(out, indent, 'static PyObject *%s(t_%s *self, int n)', getName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s result%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(result = self->object.%s((%s) n));', methodName, typename(method.getParameterTypes()[0], cls, False)) if generics: line(out, indent + 1, returnValue(cls, returnType, 'result', method.getGenericReturnType())) else: line(out, indent + 1, returnValue(cls, returnType, 'result')) line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') def package(out, allInOne, cppdir, namespace, names, use_full_names): if not allInOne: out = open(os.path.join(os.path.join(cppdir, *names), '__init__.cpp'), 'w') if allInOne and not names or not allInOne: line(out, 0, '#include ') line(out, 0, '#include ') line(out, 0, '#include "JCCEnv.h"') line(out, 0, '#include "functions.h"') if not names or not allInOne: line(out) line(out, 0, 'PyObject *initVM(PyObject *module, PyObject *args, PyObject *kwds);') if use_full_names: line(out, 0, 'PyObject *getJavaModule(PyObject *module, const char *parent, const char *name);') packages = [] types = [] namespaces = list(namespace.items()) namespaces.sort(key=lambda x: x[0]) for name, entries in namespaces: if entries is True: if names: line(out, 0, '#include "%s/%s.h"', '/'.join(names), name) else: line(out, 0, '#include "%s.h"', name) types.append(name) else: packages.append((name, entries)) indent = 0 if names: line(out) for name in names: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out); for name, entries in packages: line(out, indent, 'namespace %s {', cppname(name)) line(out, indent + 1, 'void __install__(PyObject *module);') line(out, indent + 1, 'void __initialize__(PyObject *module);') line(out, indent, '}') line(out) line(out, indent, 'void __install__(PyObject *module)') line(out, indent, '{') if use_full_names and names: parent_name = '.'.join(names[:-1]) line(out, indent + 1, 'module = getJavaModule(module, "%s", "%s");', parent_name, names[-1]) line(out) for name in types: line(out, indent + 1, 't_%s::install(module);', name) for name, entries in packages: line(out, indent + 1, '%s::__install__(module);', cppname(name)) line(out, indent, '}') line(out) if not names: line(out, indent, 'PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds)') line(out, indent, '{') line(out, indent + 1, 'PyObject *env = initVM(module, args, kwds);') line(out) line(out, indent + 1, 'if (env == NULL)') line(out, indent + 2, 'return NULL;') line(out) line(out, indent + 1, 'try {'); indent += 1 else: line(out, indent, 'void __initialize__(PyObject *module)') line(out, indent, '{') if use_full_names and names: line(out, indent + 1, 'module = getJavaModule(module, "%s", "%s");', parent_name, names[-1]) line(out) for name in types: line(out, indent + 1, 't_%s::initialize(module);', name) for name, entries in packages: line(out, indent + 1, '%s::__initialize__(module);', cppname(name)) if not names: line(out, indent + 1, 'return env;') indent -= 1 line(out, indent + 1, '} catch (int e) {') line(out, indent + 2, 'switch(e) {') line(out, indent + 2, ' case _EXC_JAVA:') line(out, indent + 3, 'return PyErr_SetJavaError();') line(out, indent + 2, ' default:') line(out, indent + 3, 'throw;') line(out, indent + 2, '}') line(out, indent + 1, '}') line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') if not allInOne: out.close() else: line(out) for name, entries in packages: package(out, allInOne, cppdir, entries, names + (name,), use_full_names) def module(out, allInOne, classes, imports, cppdir, moduleName, shared, generics, use_full_names): extname = '_%s' %(moduleName) line(out, 0, '#include ') line(out, 0, '#include "macros.h"') line(out, 0, '#include "jccfuncs.h"') if allInOne: out_init = open(os.path.join(cppdir, '__init__.cpp'), 'w') namespaces = {} for cls in classes: for importset in imports.values(): if cls in importset: break else: namespace = namespaces classNames = cls.getName().split('.') for className in classNames[:-1]: namespace = namespace.setdefault(className, {}) namespace[classNames[-1]] = True if allInOne: package(out_init, True, cppdir, namespaces, (), use_full_names) out_init.close() else: package(None, False, cppdir, namespaces, (), use_full_names) line(out) line(out, 0, 'PyObject *initJCC(PyObject *module);') line(out, 0, 'void __install__(PyObject *module);') line(out, 0, 'extern PyTypeObject *PY_TYPE(JObject), *PY_TYPE(ConstVariableDescriptor), *PY_TYPE(FinalizerClass), *PY_TYPE(FinalizerProxy);') line(out, 0, 'extern PyType_Def PY_TYPE_DEF(JObject);') line(out, 0, 'extern void _install_jarray(PyObject *);') line(out) line(out, 0, 'extern "C" {') line(out, 1, 'static struct PyModuleDef %s_def = {', extname) line(out, 2, 'PyModuleDef_HEAD_INIT,') line(out, 2, '"%s",', extname); line(out, 2, '"%s module",', extname); line(out, 2, '0,') line(out, 2, 'jcc_funcs,'); line(out, 1, '};') line(out) line(out, 1, 'PyObject *PyInit_%s(void)', extname) line(out, 1, '{') line(out, 2, 'PyObject *module = PyModule_Create(&%s_def);', extname); line(out) line(out, 2, 'initJCC(module);') line(out) line(out, 2, 'INSTALL_STATIC_TYPE(JObject, module);') line(out, 2, 'PY_TYPE_DEF(JObject).type = PY_TYPE(JObject);') line(out, 2, 'INSTALL_STATIC_TYPE(ConstVariableDescriptor, module);') line(out, 2, 'INSTALL_STATIC_TYPE(FinalizerClass, module);') line(out, 2, 'INSTALL_STATIC_TYPE(FinalizerProxy, module);') line(out, 2, '__install__(module);') line(out, 2, '_install_jarray(module);') line(out) line(out, 2, 'return module;') line(out, 1, '}') line(out, 0, '}') def compile(env, jccPath, output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, home_dir, use_distutils, shared, compiler, modules, wininst, find_jvm_dll, arch, generics, resources, imports, use_full_names, egg_info, extra_setup_args): try: if use_distutils: raise ImportError from setuptools import setup, Extension with_setuptools = True if shared and not SHARED: raise NotImplementedError("JCC was not built with --shared mode support, see JCC's INSTALL file for more information") except ImportError: if shared: raise ImportError('setuptools is required when using --shared') from distutils.core import setup, Extension with_setuptools = False extname = '_%s' %(moduleName) modulePath = os.path.join(output, moduleName) if not os.path.isdir(modulePath): os.makedirs(modulePath) out = open(os.path.join(modulePath, '__init__.py'), 'w') line(out) if shared: line(out, 0, "import os, sys") line(out) line(out, 0, "if sys.platform == 'win32':") if find_jvm_dll: line(out, 1, "from jcc.windows import add_jvm_dll_directory_to_path") line(out, 1, "add_jvm_dll_directory_to_path()") line(out, 1, "import jcc") line(out, 0, "from . import %s", extname) else: line(out, 0, "import os") line(out, 0, "from . import %s", extname) line(out) line(out, 0, '__module_dir__ = os.path.abspath(os.path.dirname(__file__))') package_data = [] for jar in jars: shutil.copy2(jar, modulePath) package_data.append(os.path.basename(jar)) if resources: def copytree(src, dst): _dst = os.path.join(modulePath, dst) if not os.path.exists(_dst): os.mkdir(_dst) for name in os.listdir(src): if name.startswith('.'): continue _src = os.path.join(src, name) if os.path.islink(_src): continue _dst = os.path.join(dst, name) if os.path.isdir(_src): copytree(_src, _dst) else: shutil.copy2(_src, os.path.join(modulePath, _dst)) package_data.append(_dst) for resource in resources: copytree(resource, os.path.split(resource)[-1]) packages = [moduleName] package = [moduleName] if modules: for module in modules: if os.path.isdir(module): def copytree(src, dst, is_package): if is_package: packages.append('.'.join(package)) if not os.path.exists(dst): os.mkdir(dst) for name in os.listdir(src): if name.startswith('.'): continue _src = os.path.join(src, name) if os.path.islink(_src): continue _dst = os.path.join(dst, name) if os.path.isdir(_src): package.append(os.path.basename(_src)) copytree(_src, _dst, os.path.exists(os.path.join(_src, '__init__.py'))) package.pop() elif not is_package or name.endswith('.py'): shutil.copy2(_src, _dst) dst = modulePath if os.path.exists(os.path.join(module, '__init__.py')): dst = os.path.join(modulePath, os.path.basename(module)) package.append(os.path.basename(module)) copytree(module, dst, True) package.pop() else: copytree(module, dst, False) else: shutil.copy2(module.rpartition('.')[0] + '.py', modulePath) line(out) line(out, 0, 'class JavaError(Exception):') line(out, 1, 'def getJavaException(self):') line(out, 2, 'return self.args[0]') line(out, 1, 'def __str__(self):') line(out, 2, 'writer = StringWriter()') line(out, 2, 'self.getJavaException().printStackTrace(PrintWriter(writer))') line(out, 2, 'return "\\n".join((str(super(JavaError, self)), " Java stacktrace:", str(writer)))') line(out) line(out, 0, 'class InvalidArgsError(Exception):') line(out, 1, 'pass') line(out) line(out, 0, '%s._set_exception_types(JavaError, InvalidArgsError)', extname) if version: line(out) line(out, 0, 'VERSION = "%s"', version) line(out, 0, 'CLASSPATH = [%s]' %(', '.join(['os.path.join(__module_dir__, "%s")' %(os.path.basename(jar)) for jar in jars]))) line(out, 0, 'CLASSPATH = os.pathsep.join(CLASSPATH)') line(out, 0, '%s.CLASSPATH = CLASSPATH', extname) line(out, 0, '%s._set_function_self(%s.initVM, %s)', extname, extname, extname) line(out) for import_ in imports: line(out, 0, 'from %s._%s import *', import_.__name__, import_.__name__) line(out, 0, 'from .%s import *', extname) if use_full_names: line(out, 0, 'from java.io import PrintWriter, StringWriter') out.close() includes = [os.path.join(output, extname), os.path.join(jccPath, 'sources')] for import_ in imports: includes.append(os.path.join(import_.__module_dir__, 'include')) sources = ['JObject.cpp', 'JArray.cpp', 'functions.cpp', 'types.cpp'] if not shared: sources.append('jcc.cpp') sources.append('JCCEnv.cpp') for source in sources: shutil.copy2(os.path.join(jccPath, 'sources', source), os.path.join(output, extname)) if shared: def copytree(src, dst): _dst = os.path.join(modulePath, dst) if not os.path.exists(_dst): os.mkdir(_dst) for name in os.listdir(src): if name.startswith('.'): continue _src = os.path.join(src, name) if os.path.islink(_src): continue _dst = os.path.join(dst, name) if os.path.isdir(_src): copytree(_src, _dst) elif name.endswith('.h'): shutil.copy2(_src, os.path.join(modulePath, _dst)) package_data.append(_dst) copytree(os.path.join(output, extname), 'include') sources = [] for path, dirs, names in os.walk(os.path.join(output, extname)): for name in names: if name.endswith('.cpp'): sources.append(os.path.join(path, name)) if egg_info: script_args = ['egg_info'] else: script_args = ['build_ext'] includes[0:0] = INCLUDES compile_args = CFLAGS link_args = LFLAGS defines=[('PYTHON', None), ('JCC_VER', '"%s"' %(JCC_VER))] if shared: defines.append(('_jcc_shared', None)) if generics: defines.append(('_java_generics', None)) if compiler: script_args.append('--compiler=%s' %(compiler)) if debug: script_args.append('--debug') compile_args += DEBUG_CFLAGS elif sys.platform == 'win32': pass elif sys.platform == 'sunos5': link_args.append('-Wl,-s') else: link_args.append('-Wl,-S') if install: script_args.append('install') if prefix: script_args.append('--prefix=%s' % prefix) if root: script_args.append('--root=%s' % root) if install_dir: script_args.append('--install-lib=%s' % install_dir) if home_dir: script_args.append('--home=%s' % home_dir) if dist: if wininst: script_args.append('bdist_wininst') elif with_setuptools: script_args.append('bdist_egg') else: script_args.append('bdist') args = { 'extra_compile_args': compile_args, 'extra_link_args': link_args, 'include_dirs': includes, 'sources': sources, 'define_macros': defines } if shared: shlibdir = os.path.dirname(os.path.dirname(_jcc3.__file__)) if sys.platform == 'darwin': # distutils no good with -R machine = platform.machine() if machine.startswith('iPod') or machine.startswith('iPhone'): args['extra_link_args'] += ['-L' + shlibdir] else: args['extra_link_args'] += ['-Wl,-rpath', shlibdir] args['library_dirs'] = [shlibdir] args['libraries'] = ['jcc3'] elif sys.platform == 'linux': # distutils no good with -R args['extra_link_args'] += ['-Wl,-rpath', shlibdir] args['library_dirs'] = [shlibdir] args['libraries'] = ['jcc3'] args['extra_link_args'] += [ getattr(import_, "_%s" %(import_.__name__)).__file__ for import_ in imports ] elif sys.platform == 'win32': _d = debug and '_d' or '' libdir = os.path.join(modulePath, 'lib') if not os.path.exists(libdir): os.mkdir(libdir) extlib = os.path.join('lib', "%s%s.lib" %(extname, _d)) package_data.append(extlib) args['extra_link_args'] += [ os.path.join(shlibdir, 'jcc3', 'jcc3%s.lib' %(_d)), ' '.join(IMPLIB_LFLAGS) %(os.path.join(modulePath, extlib)) ] args['libraries'] = [ os.path.join(import_.__module_dir__, 'lib', '_%s%s' %(import_.__name__, _d)) for import_ in imports ] args['define_macros'] += [ ("_dll_%s" %(import_.__name__), '__declspec(dllimport)') for import_ in imports ] + [("_dll_%s" %(moduleName), '__declspec(dllexport)')] else: raise NotImplementedError("shared mode on %s" %(sys.platform)) if arch and sys.platform == 'darwin': from distutils import sysconfig config_vars = sysconfig.get_config_vars() cflags = config_vars['CFLAGS'].split(' ') count = len(cflags) i = 0 while i < count - 1: if cflags[i] == '-arch' and cflags[i + 1] not in arch: del cflags[i:i+2] count -= 2 else: i += 1 config_vars['CFLAGS'] = ' '.join(cflags) extensions = [Extension('.'.join([moduleName, extname]), **args)] script_args.extend(extra_setup_args) args = { 'name': moduleName, 'packages': packages, 'package_dir': {moduleName: modulePath}, 'package_data': {moduleName: package_data}, 'ext_modules': extensions, 'script_args': script_args } if version: args['version'] = version if with_setuptools: args['zip_safe'] = False print("setup args = %s" % args) setup(**args) JCC-3.6/jcc3/sources/0000755000076500000000000000000013536235634014503 5ustar vajdawheel00000000000000JCC-3.6/jcc3/sources/jcc.cpp0000644000076500000000000006735113360510615015750 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include #ifdef linux #include #endif #include #include "structmember.h" #include "JObject.h" #include "JCCEnv.h" #include "macros.h" _DLL_EXPORT JCCEnv *env; /* JCCEnv */ class t_jccenv { public: PyObject_HEAD JCCEnv *env; }; static void t_jccenv_dealloc(t_jccenv *self); static PyObject *t_jccenv_attachCurrentThread(PyObject *self, PyObject *args); static PyObject *t_jccenv_detachCurrentThread(PyObject *self); static PyObject *t_jccenv_isCurrentThreadAttached(PyObject *self); static PyObject *t_jccenv_isShared(PyObject *self); static PyObject *t_jccenv_strhash(PyObject *self, PyObject *arg); static PyObject *t_jccenv__dumpRefs(PyObject *self, PyObject *args, PyObject *kwds); static PyObject *t_jccenv__addClassPath(PyObject *self, PyObject *args); static PyObject *t_jccenv__get_jni_version(PyObject *self, void *data); static PyObject *t_jccenv__get_java_version(PyObject *self, void *data); static PyObject *t_jccenv__get_classpath(PyObject *self, void *data); static PyGetSetDef t_jccenv_properties[] = { { "jni_version", (getter) t_jccenv__get_jni_version, NULL, NULL, NULL }, { "java_version", (getter) t_jccenv__get_java_version, NULL, NULL, NULL }, { "classpath", (getter) t_jccenv__get_classpath, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static PyMemberDef t_jccenv_members[] = { { NULL, 0, 0, 0, NULL } }; static PyMethodDef t_jccenv_methods[] = { { "attachCurrentThread", (PyCFunction) t_jccenv_attachCurrentThread, METH_VARARGS, NULL }, { "detachCurrentThread", (PyCFunction) t_jccenv_detachCurrentThread, METH_NOARGS, NULL }, { "isCurrentThreadAttached", (PyCFunction) t_jccenv_isCurrentThreadAttached, METH_NOARGS, NULL }, { "isShared", (PyCFunction) t_jccenv_isShared, METH_NOARGS, NULL }, { "strhash", (PyCFunction) t_jccenv_strhash, METH_O, NULL }, { "_dumpRefs", (PyCFunction) t_jccenv__dumpRefs, METH_VARARGS | METH_KEYWORDS, NULL }, { "_addClassPath", (PyCFunction) t_jccenv__addClassPath, METH_VARARGS, NULL }, { NULL, NULL, 0, NULL } }; static PyTypeObject JCCEnv_type = { PyVarObject_HEAD_INIT(NULL, 0) "jcc.JCCEnv", /* tp_name */ sizeof(t_jccenv), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_jccenv_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "JCCEnv", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ t_jccenv_methods, /* tp_methods */ t_jccenv_members, /* tp_members */ t_jccenv_properties, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; PyTypeObject *PY_TYPE(JCCEnv) = &JCCEnv_type; static void t_jccenv_dealloc(t_jccenv *self) { self->ob_base.ob_type->tp_free((PyObject *) self); } static void add_option(char *name, const char *value, JavaVMOption *option) { char *buf = (char *) malloc(strlen(name) + strlen(value) + 1); sprintf(buf, "%s%s", name, value); option->optionString = buf; } #ifdef _jcc_lib static void add_paths(char *name, const char *p0, const char *p1, JavaVMOption *option) { #if defined(_MSC_VER) || defined(__WIN32) char pathsep = ';'; #else char pathsep = ':'; #endif char *buf = (char *) malloc(strlen(name) + strlen(p0) + strlen(p1) + 4); sprintf(buf, "%s%s%c%s", name, p0, pathsep, p1); option->optionString = buf; } #endif static PyObject *t_jccenv_attachCurrentThread(PyObject *self, PyObject *args) { char *name = NULL; int asDaemon = 0, result; if (!PyArg_ParseTuple(args, "|si", &name, &asDaemon)) return NULL; result = env->attachCurrentThread(name, asDaemon); return PyLong_FromLong(result); } static PyObject *t_jccenv_detachCurrentThread(PyObject *self) { int result = env->vm->DetachCurrentThread(); env->set_vm_env(NULL); return PyLong_FromLong(result); } static PyObject *t_jccenv_isCurrentThreadAttached(PyObject *self) { if (env->get_vm_env() != NULL) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyObject *t_jccenv_isShared(PyObject *self) { #ifdef _jcc_lib Py_RETURN_TRUE; #else Py_RETURN_FALSE; #endif } #ifdef _MSC_VER static PyObject *t_jccenv_strhash(PyObject *self, PyObject *arg) { static const size_t hexdig = sizeof(unsigned long long) * 2; unsigned long long hash = (unsigned long long) PyObject_Hash(arg); char buffer[hexdig + 1]; sprintf(buffer, "%0*llx", (int) hexdig, hash); return PyUnicode_FromStringAndSize(buffer, hexdig); } #else static PyObject *t_jccenv_strhash(PyObject *self, PyObject *arg) { static const size_t hexdig = sizeof(uintmax_t) * 2; uintmax_t hash = (uintmax_t) PyObject_Hash(arg); char buffer[hexdig + 1]; sprintf(buffer, "%0*" PRIxMAX, (int) hexdig, hash); return PyUnicode_FromStringAndSize(buffer, hexdig); } #endif static PyObject *t_jccenv__dumpRefs(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwnames[] = { "classes", "values", NULL }; int classes = 0, values = 0; PyObject *result; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwnames, &classes, &values)) return NULL; if (classes) result = PyDict_New(); else result = PyList_New(env->refs.size()); int count = 0; for (std::multimap::iterator iter = env->refs.begin(); iter != env->refs.end(); iter++) { if (classes) // return dict of { class name: instance count } { PyObject *key = env->getClassName(iter->second.global); PyObject *value = PyDict_GetItem(result, key); if (value == NULL) value = PyLong_FromLong(1); else value = PyLong_FromLong(PyLong_AsLong(value) + 1); PyDict_SetItem(result, key, value); Py_DECREF(key); Py_DECREF(value); } else if (values) // return list of (value string, ref count) { PyObject *key = env->toPyUnicode(iter->second.global); PyObject *value = PyLong_FromLong(iter->second.count); PyList_SET_ITEM(result, count++, PyTuple_Pack(2, key, value)); Py_DECREF(key); Py_DECREF(value); } else // return list of (id hash code, ref count) { PyObject *key = PyLong_FromLong(iter->first); PyObject *value = PyLong_FromLong(iter->second.count); PyList_SET_ITEM(result, count++, PyTuple_Pack(2, key, value)); Py_DECREF(key); Py_DECREF(value); } } return result; } static PyObject *t_jccenv__addClassPath(PyObject *self, PyObject *args) { const char *classpath; if (!PyArg_ParseTuple(args, "s", &classpath)) return NULL; env->setClassPath(classpath); Py_RETURN_NONE; } static PyObject *t_jccenv__get_jni_version(PyObject *self, void *data) { return PyLong_FromLong(env->getJNIVersion()); } static PyObject *t_jccenv__get_java_version(PyObject *self, void *data) { return env->fromJString(env->getJavaVersion(), 1); } static PyObject *t_jccenv__get_classpath(PyObject *self, void *data) { char *classpath = env->getClassPath(); if (classpath) { PyObject *result = PyUnicode_FromString(classpath); free(classpath); return result; } Py_RETURN_NONE; } _DLL_EXPORT PyObject *getVMEnv(PyObject *self) { if (env->vm != NULL) { t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv)->tp_alloc(PY_TYPE(JCCEnv), 0); jccenv->env = env; return (PyObject *) jccenv; } Py_RETURN_NONE; } #ifdef _jcc_lib static void registerNatives(JNIEnv *vm_env); #endif _DLL_EXPORT PyObject *initJCC(PyObject *module) { static int _once_only = 1; #if defined(_MSC_VER) || defined(__WIN32) #define verstring(n) #n PyObject *ver = PyUnicode_FromString(verstring(JCC_VER)); #else PyObject *ver = PyUnicode_FromString(JCC_VER); #endif PyObject_SetAttrString(module, "JCC_VERSION", ver); Py_DECREF(ver); if (_once_only) { PyEval_InitThreads(); INSTALL_STATIC_TYPE(JCCEnv, module); if (env == NULL) env = new JCCEnv(NULL, NULL); _once_only = 0; Py_RETURN_TRUE; } Py_RETURN_FALSE; } _DLL_EXPORT PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwnames[] = { "classpath", "initialheap", "maxheap", "maxstack", "vmargs", NULL }; const char *classpath = NULL; char *initialheap = NULL, *maxheap = NULL, *maxstack = NULL; PyObject *vmargs = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zzzzO", kwnames, &classpath, &initialheap, &maxheap, &maxstack, &vmargs)) return NULL; if (env->vm) { PyObject *module_cp = NULL; if (initialheap || maxheap || maxstack || vmargs) { PyErr_SetString(PyExc_ValueError, "JVM is already running, options are ineffective"); return NULL; } if (classpath == NULL && self != NULL) { module_cp = PyObject_GetAttrString(self, "CLASSPATH"); if (module_cp) classpath = PyUnicode_AsUTF8(module_cp); } if (classpath && classpath[0]) env->setClassPath(classpath); Py_XDECREF(module_cp); return getVMEnv(self); } else { JavaVMInitArgs vm_args; JavaVMOption vm_options[32]; JNIEnv *vm_env; JavaVM *vm; unsigned int nOptions = 0; PyObject *module_cp = NULL; vm_args.version = JNI_VERSION_1_4; JNI_GetDefaultJavaVMInitArgs(&vm_args); if (classpath == NULL && self != NULL) { module_cp = PyObject_GetAttrString(self, "CLASSPATH"); if (module_cp) classpath = PyUnicode_AsUTF8(module_cp); } #ifdef _jcc_lib PyObject *jcc = PyImport_ImportModule("jcc"); PyObject *cp = PyObject_GetAttrString(jcc, "CLASSPATH"); if (classpath) add_paths("-Djava.class.path=", PyUnicode_AsUTF8(cp), classpath, &vm_options[nOptions++]); else add_option("-Djava.class.path=", PyUnicode_AsUTF8(cp), &vm_options[nOptions++]); Py_DECREF(cp); Py_DECREF(jcc); #else if (classpath) add_option("-Djava.class.path=", classpath, &vm_options[nOptions++]); #endif Py_XDECREF(module_cp); if (initialheap) add_option("-Xms", initialheap, &vm_options[nOptions++]); if (maxheap) add_option("-Xmx", maxheap, &vm_options[nOptions++]); if (maxstack) add_option("-Xss", maxstack, &vm_options[nOptions++]); if (vmargs != NULL && PyUnicode_Check(vmargs)) { #ifdef _MSC_VER char *buf = _strdup(PyUnicode_AsUTF8(vmargs)); #else char *buf = strdup(PyUnicode_AsUTF8(vmargs)); #endif char *sep = ","; char *option; for (option = strtok(buf, sep); option != NULL; option = strtok(NULL, sep)) { if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption)) add_option("", option, &vm_options[nOptions++]); else { free(buf); for (unsigned int i = 0; i < nOptions; i++) free(vm_options[i].optionString); PyErr_Format(PyExc_ValueError, "Too many options (> %d)", nOptions); return NULL; } } free(buf); } else if (vmargs != NULL && PySequence_Check(vmargs)) { PyObject *fast = PySequence_Fast(vmargs, "error converting vmargs to a tuple"); if (fast == NULL) return NULL; for (int i = 0; i < PySequence_Fast_GET_SIZE(fast); ++i) { PyObject *arg = PySequence_Fast_GET_ITEM(fast, i); if (PyUnicode_Check(arg)) { const char *option = PyUnicode_AsUTF8(arg); if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption)) add_option("", option, &vm_options[nOptions++]); else { for (unsigned int j = 0; j < nOptions; j++) free(vm_options[j].optionString); PyErr_Format(PyExc_ValueError, "Too many options (> %d)", nOptions); Py_DECREF(fast); return NULL; } } else { for (unsigned int j = 0; j < nOptions; j++) free(vm_options[j].optionString); PyErr_Format(PyExc_TypeError, "vmargs arg %d is not a string", i); Py_DECREF(fast); return NULL; } } Py_DECREF(fast); } else if (vmargs != NULL) { PyErr_SetString(PyExc_TypeError, "vmargs is not a string or sequence"); return NULL; } //vm_options[nOptions++].optionString = "-verbose:gc"; //vm_options[nOptions++].optionString = "-Xcheck:jni"; vm_args.nOptions = nOptions; vm_args.ignoreUnrecognized = JNI_FALSE; vm_args.options = vm_options; if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0) { for (unsigned int i = 0; i < nOptions; i++) free(vm_options[i].optionString); PyErr_Format(PyExc_ValueError, "An error occurred while creating Java VM"); return NULL; } env->set_vm(vm, vm_env); for (unsigned int i = 0; i < nOptions; i++) free(vm_options[i].optionString); t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv)->tp_alloc(PY_TYPE(JCCEnv), 0); jccenv->env = env; #ifdef _jcc_lib registerNatives(vm_env); #endif return (PyObject *) jccenv; } } /* returns borrowed reference */ _DLL_EXPORT PyObject *getJavaModule(PyObject *module, const char *parent, const char *name) { PyObject *modules = PyImport_GetModuleDict(); PyObject *parent_module, *full_name; if (parent[0] == '\0') { parent_module = NULL; full_name = PyUnicode_FromString(name); } else if ((parent_module = PyDict_GetItemString(modules, parent)) == NULL) { PyErr_Format(PyExc_ValueError, "Parent module '%s' not found", parent); return NULL; } else full_name = PyUnicode_FromFormat("%s.%s", parent, name); PyObject *child_module = PyDict_GetItem(modules, full_name); if (child_module == NULL) { child_module = PyModule_New(PyUnicode_AsUTF8(full_name)); if (child_module != NULL) { if (parent_module != NULL) PyDict_SetItemString(PyModule_GetDict(parent_module), name, child_module); PyDict_SetItem(modules, full_name, child_module); Py_DECREF(child_module); /* borrow reference */ } } Py_DECREF(full_name); /* During __install__ pass, __file__ is not yet set on module. * During __initialize__ pass, __file__ is passed down to child_module. */ if (child_module != NULL) { PyObject *__file__ = PyUnicode_FromString("__file__"); PyObject *file = PyDict_GetItem(PyModule_GetDict(module), __file__); if (file != NULL) PyDict_SetItem(PyModule_GetDict(child_module), __file__, file); Py_DECREF(__file__); } return child_module; } #ifdef _jcc_lib #if PY_VERSION_HEX < 0x03050000 #define Py_DecodeLocale(arg, size) _Py_char2wchar((arg), (size)) #endif static void raise_error(JNIEnv *vm_env, const char *message) { jclass cls = vm_env->FindClass("org/apache/jcc/PythonException"); vm_env->ThrowNew(cls, message); } static void _PythonVM_init(JNIEnv *vm_env, jobject self, jstring programName, jobjectArray args) { const char *str = vm_env->GetStringUTFChars(programName, JNI_FALSE); #ifdef linux char buf[32]; // load python runtime for other .so modules to link (such as _time.so) sprintf(buf, "libpython%d.%d.so", PY_MAJOR_VERSION, PY_MINOR_VERSION); dlopen(buf, RTLD_NOW | RTLD_GLOBAL); #endif Py_SetProgramName(Py_DecodeLocale(str, NULL)); // leaked to python vm vm_env->ReleaseStringUTFChars(programName, str); PyEval_InitThreads(); Py_Initialize(); if (args) { int argc = vm_env->GetArrayLength(args); wchar_t **argv = (wchar_t **) calloc(argc + 1, sizeof(wchar_t *)); argv[0] = Py_GetProgramName(); for (int i = 0; i < argc; i++) { jstring arg = (jstring) vm_env->GetObjectArrayElement(args, i); const char *str = vm_env->GetStringUTFChars(arg, JNI_FALSE); argv[i + 1] = Py_DecodeLocale(str, NULL); // leaked to python vm vm_env->ReleaseStringUTFChars(arg, str); } PySys_SetArgv(argc + 1, argv); free(argv); } else { wchar_t *py_program_name = Py_GetProgramName(); PySys_SetArgv(1, &py_program_name); } PyEval_ReleaseLock(); } static jobject _PythonVM_instantiate(JNIEnv *vm_env, jobject self, jstring moduleName, jstring className) { PythonGIL gil(vm_env); const char *modStr = vm_env->GetStringUTFChars(moduleName, JNI_FALSE); PyObject *module = PyImport_ImportModule(modStr); vm_env->ReleaseStringUTFChars(moduleName, modStr); if (!module) { raise_error(vm_env, "import failed"); return NULL; } const char *clsStr = vm_env->GetStringUTFChars(className, JNI_FALSE); PyObject *cls = PyObject_GetAttrString(module, clsStr); PyObject *obj; jobject jobj; vm_env->ReleaseStringUTFChars(className, clsStr); Py_DECREF(module); if (!cls) { raise_error(vm_env, "class not found"); return NULL; } obj = PyObject_CallFunctionObjArgs(cls, NULL); Py_DECREF(cls); if (!obj) { raise_error(vm_env, "instantiation failed"); return NULL; } PyObject *cObj = PyObject_GetAttrString(obj, "_jobject"); if (!cObj) { raise_error(vm_env, "instance does not proxy a java object"); Py_DECREF(obj); return NULL; } jobj = (jobject) PyCapsule_GetPointer(cObj, "jobject"); Py_DECREF(cObj); jobj = vm_env->NewLocalRef(jobj); Py_DECREF(obj); return jobj; } extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *vm_env; if (!vm->GetEnv((void **) &vm_env, JNI_VERSION_1_4)) env = new JCCEnv(vm, vm_env); registerNatives(vm_env); return JNI_VERSION_1_4; } JNIEXPORT void JNICALL Java_org_apache_jcc_PythonVM_init(JNIEnv *vm_env, jobject self, jstring programName, jobjectArray args) { return _PythonVM_init(vm_env, self, programName, args); } JNIEXPORT jobject JNICALL Java_org_apache_jcc_PythonVM_instantiate(JNIEnv *vm_env, jobject self, jstring moduleName, jstring className) { return _PythonVM_instantiate(vm_env, self, moduleName, className); } JNIEXPORT jint JNICALL Java_org_apache_jcc_PythonVM_acquireThreadState(JNIEnv *vm_env) { PyGILState_STATE state = PyGILState_Ensure(); PyThreadState *tstate = PyGILState_GetThisThreadState(); int result = -1; if (tstate != NULL && tstate->gilstate_counter >= 1) result = ++tstate->gilstate_counter; PyGILState_Release(state); return result; } JNIEXPORT jint JNICALL Java_org_apache_jcc_PythonVM_releaseThreadState(JNIEnv *vm_env) { PyGILState_STATE state = PyGILState_Ensure(); PyThreadState *tstate = PyGILState_GetThisThreadState(); int result = -1; if (tstate != NULL && tstate->gilstate_counter >= 1) result = --tstate->gilstate_counter; PyGILState_Release(state); return result; } }; static void JNICALL _PythonException_pythonDecRef(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state != NULL) { PythonGIL gil(vm_env); Py_DECREF(state); vm_env->SetLongField(self, fid, (jlong) 0); } } static void JNICALL _PythonException_saveErrorState(JNIEnv *vm_env, jobject self) { PythonGIL gil(vm_env); PyObject *type, *value, *tb; PyErr_Fetch(&type, &value, &tb); if (type != NULL) { PyObject *state = PyTuple_New(3); PyErr_NormalizeException(&type, &value, &tb); PyTuple_SET_ITEM(state, 0, type); if (value == NULL) { PyTuple_SET_ITEM(state, 1, Py_None); Py_INCREF(Py_None); } else PyTuple_SET_ITEM(state, 1, value); if (tb == NULL) { PyTuple_SET_ITEM(state, 2, Py_None); Py_INCREF(Py_None); } else PyTuple_SET_ITEM(state, 2, tb); jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); vm_env->SetLongField(self, fid, (jlong) state); } } static jstring JNICALL _PythonException_getErrorName(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state == NULL) return NULL; PythonGIL gil(vm_env); PyObject *errorName = PyObject_GetAttrString(PyTuple_GET_ITEM(state, 0), "__name__"); if (errorName != NULL) { jstring str = env->fromPyString(errorName); Py_DECREF(errorName); return str; } return NULL; } static jstring JNICALL _PythonException_getErrorMessage(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state == NULL) return NULL; PythonGIL gil(vm_env); PyObject *value = PyTuple_GET_ITEM(state, 1); if (value != Py_None) { PyObject *message = PyObject_Str(value); if (message != NULL) { jstring str = env->fromPyString(message); Py_DECREF(message); return str; } } return NULL; } static jstring JNICALL _PythonException_getErrorTraceback(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state == NULL) return NULL; PythonGIL gil(vm_env); PyObject *module = NULL, *cls = NULL, *stringIO = NULL, *result = NULL; PyObject *_stderr = PySys_GetObject("stderr"); if (!_stderr) return NULL; module = PyImport_ImportModule("cStringIO"); if (!module) return NULL; cls = PyObject_GetAttrString(module, "StringIO"); Py_DECREF(module); if (!cls) return NULL; stringIO = PyObject_CallObject(cls, NULL); Py_DECREF(cls); if (!stringIO) return NULL; Py_INCREF(_stderr); PySys_SetObject("stderr", stringIO); PyObject *type = PyTuple_GET_ITEM(state, 0); PyObject *value = PyTuple_GET_ITEM(state, 1); PyObject *tb = PyTuple_GET_ITEM(state, 2); jstring str = NULL; Py_INCREF(type); if (value == Py_None) value = NULL; else Py_INCREF(value); if (tb == Py_None) tb = NULL; else Py_INCREF(tb); PyErr_Restore(type, value, tb); PyErr_Print(); result = PyObject_CallMethod(stringIO, "getvalue", NULL); Py_DECREF(stringIO); if (result != NULL) { str = env->fromPyString(result); Py_DECREF(result); } PySys_SetObject("stderr", _stderr); Py_DECREF(_stderr); return str; } static void registerNatives(JNIEnv *vm_env) { jclass cls = vm_env->FindClass("org/apache/jcc/PythonException"); JNINativeMethod methods[] = { { "pythonDecRef", "()V", (void *) _PythonException_pythonDecRef }, { "saveErrorState", "()V", (void *) _PythonException_saveErrorState }, { "getErrorName", "()Ljava/lang/String;", (void *) _PythonException_getErrorName }, { "getErrorMessage", "()Ljava/lang/String;", (void *) _PythonException_getErrorMessage }, { "getErrorTraceback", "()Ljava/lang/String;", (void *) _PythonException_getErrorTraceback }, }; vm_env->RegisterNatives(cls, methods, sizeof(methods) / sizeof(methods[0])); } #endif /* _jcc_lib */ JCC-3.6/jcc3/sources/JArray.cpp0000644000076500000000000007734013361263624016406 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef PYTHON #include #include #include "structmember.h" #include "JArray.h" #include "functions.h" #include "java/lang/Class.h" using namespace java::lang; template class _t_JArray : public t_JArray { public: static PyObject *format; }; template static PyObject *get(U *self, Py_ssize_t n) { return self->array.get(n); } template static PyObject *toSequence(U *self) { return self->array.toSequence(); } template static PyObject *toSequence(U *self, Py_ssize_t lo, Py_ssize_t hi) { return self->array.toSequence(lo, hi); } template class _t_iterator { public: PyObject_HEAD U *obj; Py_ssize_t position; static void dealloc(_t_iterator *self) { Py_XDECREF(self->obj); self->ob_base.ob_type->tp_free((PyObject *) self); } static PyObject *iternext(_t_iterator *self) { if (self->position < (Py_ssize_t) self->obj->array.length) return get(self->obj, self->position++); PyErr_SetNone(PyExc_StopIteration); return NULL; } static PyTypeObject *JArrayIterator; }; template static int init(U *self, PyObject *args, PyObject *kwds) { PyObject *obj; if (!PyArg_ParseTuple(args, "O", &obj)) return -1; if (PySequence_Check(obj)) { self->array = JArray(obj); if (PyErr_Occurred()) return -1; } else if (PyGen_Check(obj)) { PyObject *tuple = PyObject_CallFunctionObjArgs((PyObject *) &PyTuple_Type, obj, NULL); if (!tuple) return -1; self->array = JArray(tuple); Py_DECREF(tuple); if (PyErr_Occurred()) return -1; } else if (PyLong_Check(obj)) { int n = PyLong_AsLong(obj); if (n < 0) { PyErr_SetObject(PyExc_ValueError, obj); return -1; } self->array = JArray(n); } else { PyErr_SetObject(PyExc_TypeError, obj); return -1; } return 0; } template static void dealloc(U *self) { self->array = JArray((jobject) NULL); self->ob_base.ob_type->tp_free((PyObject *) self); } template static PyObject *_format(U *self, PyObject *(*fn)(PyObject *)) { if (self->array.this$) { PyObject *list = toSequence(self); if (list) { PyObject *result = (*fn)(list); Py_DECREF(list); if (result) { PyObject *args = PyTuple_New(1); PyTuple_SET_ITEM(args, 0, result); result = PyUnicode_Format(U::format, args); Py_DECREF(args); return result; } } return NULL; } return PyUnicode_FromString(""); } template static PyObject *repr(U *self) { return _format(self, (PyObject *(*)(PyObject *)) PyObject_Repr); } template static PyObject *str(U *self) { return _format(self, (PyObject *(*)(PyObject *)) PyObject_Str); } template static int _compare(U *self, PyObject *value, int i0, int i1, int op, int *cmp) { PyObject *v0 = get(self, i0); PyObject *v1 = PySequence_Fast_GET_ITEM(value, i1); /* borrowed */ if (!v0) return -1; if (!v1) { Py_DECREF(v0); return -1; } *cmp = PyObject_RichCompareBool(v0, v1, op); Py_DECREF(v0); if (*cmp < 0) return -1; return 0; } template static PyObject *richcompare(U *self, PyObject *value, int op) { PyObject *result = NULL; int s0, s1; if (!PySequence_Check(value)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } value = PySequence_Fast(value, "not a sequence"); if (!value) return NULL; s0 = PySequence_Fast_GET_SIZE(value); s1 = self->array.length; if (s1 < 0) { Py_DECREF(value); return NULL; } if (s0 != s1) { switch (op) { case Py_EQ: result = Py_False; break; case Py_NE: result = Py_True; break; } } if (!result) { int i0, i1, cmp = 1; for (i0 = 0, i1 = 0; i0 < s0 && i1 < s1 && cmp; i0++, i1++) { if (_compare(self, value, i0, i1, Py_EQ, &cmp) < 0) { Py_DECREF(value); return NULL; } } if (cmp) { switch (op) { case Py_LT: cmp = s0 < s1; break; case Py_LE: cmp = s0 <= s1; break; case Py_EQ: cmp = s0 == s1; break; case Py_NE: cmp = s0 != s1; break; case Py_GT: cmp = s0 > s1; break; case Py_GE: cmp = s0 >= s1; break; default: cmp = 0; } result = cmp ? Py_True : Py_False; } else if (op == Py_EQ) result = Py_False; else if (op == Py_NE) result = Py_True; else if (_compare(self, value, i0, i1, op, &cmp) < 0) { Py_DECREF(value); return NULL; } else result = cmp ? Py_True : Py_False; } Py_DECREF(value); Py_INCREF(result); return result; } template static PyObject *iter(U *self) { _t_iterator *it = PyObject_New(_t_iterator, _t_iterator::JArrayIterator); if (it) { it->position = 0; it->obj = self; Py_INCREF((PyObject *) self); } return (PyObject *) it; } template static Py_ssize_t seq_length(U *self) { if (self->array.this$) return self->array.length; return 0; } template static PyObject *seq_get(U *self, Py_ssize_t n) { return get(self, n); } template static int seq_contains(U *self, PyObject *value) { return 0; } template static PyObject *seq_concat(U *self, PyObject *arg) { PyObject *list = toSequence(self); if (list != NULL && PyList_Type.tp_as_sequence->sq_inplace_concat(list, arg) == NULL) { Py_DECREF(list); return NULL; } return list; } template static PyObject *seq_repeat(U *self, Py_ssize_t n) { PyObject *list = toSequence(self); if (list != NULL && PyList_Type.tp_as_sequence->sq_inplace_repeat(list, n) == NULL) { Py_DECREF(list); return NULL; } return list; } template static int seq_set(U *self, Py_ssize_t n, PyObject *value) { return self->array.set(n, value); } template static PyObject *seq_getslice(U *self, Py_ssize_t lo, Py_ssize_t hi) { return toSequence(self, lo, hi); } template static int seq_setslice(U *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *values) { Py_ssize_t length = self->array.length; if (values == NULL) { PyErr_SetString(PyExc_ValueError, "array size cannot change"); return -1; } if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *sequence = PySequence_Fast(values, "not a sequence"); if (!sequence) return -1; Py_ssize_t size = PySequence_Fast_GET_SIZE(sequence); if (size < 0) goto error; if (size != hi - lo) { PyErr_SetString(PyExc_ValueError, "array size cannot change"); goto error; } for (Py_ssize_t i = lo; i < hi; i++) { PyObject *value = PySequence_Fast_GET_ITEM(sequence, i - lo); if (value == NULL) goto error; if (self->array.set(i, value) < 0) goto error; } Py_DECREF(sequence); return 0; error: Py_DECREF(sequence); return -1; } template static PyObject *map_subscript(U *self, PyObject *key) { if (PySlice_Check(key)) { Py_ssize_t from, to, step, slicelength; if (PySlice_GetIndicesEx(key, seq_length(self), &from, &to, &step, &slicelength) < 0) return NULL; if (step != 1) { PyErr_SetString(PyExc_ValueError, "slice step must be 1"); return NULL; } return seq_getslice(self, from, to); } if (PyIndex_Check(key)) { Py_ssize_t at = PyNumber_AsSsize_t(key, PyExc_IndexError); if (at == -1 && PyErr_Occurred()) return NULL; return seq_get(self, at); } PyErr_SetObject(PyExc_TypeError, key); return NULL; } template static int map_ass_subscript(U *self, PyObject *key, PyObject *value) { if (PySlice_Check(key)) { Py_ssize_t from, to, step, slicelength; if (PySlice_GetIndicesEx(key, seq_length(self), &from, &to, &step, &slicelength) < 0) return -1; if (step != 1) { PyErr_SetString(PyExc_ValueError, "slice step must be 1"); return -1; } return seq_setslice(self, from, to, value); } if (PyIndex_Check(key)) { Py_ssize_t at = PyNumber_AsSsize_t(key, PyExc_IndexError); if (at == -1 && PyErr_Occurred()) return -1; return seq_set(self, at, value); } PyErr_SetObject(PyExc_TypeError, key); return -1; } static PyObject *t_JArray_jbyte__get_string_(t_JArray *self, void *data) { return self->array.to_string_(); } static PyObject *t_JArray_jbyte__get_bytes_(t_JArray *self, void *data) { return self->array.to_bytes_(); } static PyGetSetDef t_JArray_jbyte__fields[] = { { "string_", (getter) t_JArray_jbyte__get_string_, NULL, "", NULL }, { "bytes_", (getter) t_JArray_jbyte__get_bytes_, NULL, "", NULL }, { NULL, NULL, NULL, NULL, NULL } }; template static jclass initializeClass(bool getOnly) { return env->get_vm_env()->GetObjectClass(JArray((Py_ssize_t) 0).this$); } template static PyObject *cast_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsObj; if (!PyArg_ParseTuple(args, "O", &arg)) return NULL; if (!PyObject_TypeCheck(arg, PY_TYPE(Object))) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } clsObj = PyObject_GetAttrString((PyObject *) type, "class_"); if (!clsObj) return NULL; Class arrayCls = ((t_Class *) clsObj)->object; if (!arrayCls.isAssignableFrom(argCls)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } return JArray(((t_JObject *) arg)->object.this$).wrap(); } template static PyObject *wrapfn_(const jobject &object) { return JArray(object).wrap(); } template static PyObject *instance_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsObj; if (!PyArg_ParseTuple(args, "O", &arg)) return NULL; if (!PyObject_TypeCheck(arg, PY_TYPE(Object))) Py_RETURN_FALSE; Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) Py_RETURN_FALSE; clsObj = PyObject_GetAttrString((PyObject *) type, "class_"); if (!clsObj) return NULL; Class arrayCls = ((t_Class *) clsObj)->object; if (!arrayCls.isAssignableFrom(argCls)) Py_RETURN_FALSE; Py_RETURN_TRUE; } template static PyObject *assignable_(PyTypeObject *type, PyObject *args, PyObject *kwds) { return instance_(type, args, kwds); } template< typename T, typename U = _t_JArray > class jarray_type { public: PyTypeObject *type_object; class iterator_type { public: PyTypeObject *type_object; void install(char *name, PyObject *module) { PyType_Slot slots[] = { { Py_tp_dealloc, (void *) _t_iterator::dealloc }, { Py_tp_doc, (void *) "JArrayIterator wrapper type" }, { Py_tp_iter, (void *) PyObject_SelfIter }, { Py_tp_iternext, (void *) _t_iterator::iternext }, { 0, NULL } }; PyType_Spec spec = { name, sizeof(_t_iterator), 0, Py_TPFLAGS_DEFAULT, slots }; type_object = (PyTypeObject *) PyType_FromSpec(&spec); if (type_object != NULL) PyModule_AddObject(module, name, (PyObject *) type_object); _t_iterator::JArrayIterator = type_object; } }; iterator_type iterator_type_object; void install(char *name, char *type_name, char *iterator_name, PyObject *module) { static PyMethodDef methods[] = { { "cast_", (PyCFunction) cast_, METH_VARARGS | METH_CLASS, "" }, { "instance_", (PyCFunction) instance_, METH_VARARGS | METH_CLASS, "" }, { "assignable_", (PyCFunction) assignable_, METH_VARARGS | METH_CLASS, "" }, { NULL, NULL, 0, NULL } }; PyType_Slot slots[] = { { Py_tp_dealloc, (void *) dealloc }, { Py_tp_repr, (void *) repr }, { Py_sq_length, (void *) seq_length }, { Py_sq_concat, (void *) seq_concat }, { Py_sq_repeat, (void *) seq_repeat }, { Py_sq_item, (void *) seq_get }, { Py_sq_ass_item, (void *) seq_set }, { Py_sq_contains, (void *) seq_contains }, { Py_mp_length, (void *) seq_length }, { Py_mp_subscript, (void *) map_subscript }, { Py_mp_ass_subscript, (void *) map_ass_subscript }, { Py_tp_str, (void *) str }, { Py_tp_doc, (void *) "JArray wrapper type" }, { Py_tp_richcompare, (void *) richcompare }, { Py_tp_iter, (void *) iter }, { Py_tp_methods, methods }, { Py_tp_init, (void *) init }, { Py_tp_new, (void *) _new }, { 0, NULL }, // to patch in byte[].string_ and bytes_ { 0, NULL } }; if (!strcmp(type_name, "byte")) { slots[(sizeof(slots) / sizeof(PyType_Slot)) - 2] = { Py_tp_getset, (void *) t_JArray_jbyte__fields }; } PyType_Spec spec = { name, sizeof(U), 0, Py_TPFLAGS_DEFAULT, slots }; PyObject *bases = PyTuple_Pack(1, PY_TYPE(Object)); type_object = (PyTypeObject *) PyType_FromSpecWithBases(&spec, bases); Py_DECREF(bases); if (type_object != NULL) { PyDict_SetItemString(type_object->tp_dict, "class_", make_descriptor(initializeClass)); PyDict_SetItemString(type_object->tp_dict, "wrapfn_", make_descriptor(wrapfn_)); PyModule_AddObject(module, name, (PyObject *) type_object); } U::format = PyUnicode_FromFormat("JArray<%s>%%s", type_name); iterator_type_object.install(iterator_name, module); } static PyObject *_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { U *self = (U *) type->tp_alloc(type, 0); if (self) self->array = JArray((jobject) NULL); return (PyObject *) self; } }; template class _t_jobjectarray : public _t_JArray { public: PyObject *(*wrapfn)(const T&); }; template<> PyObject *get(_t_jobjectarray *self, Py_ssize_t n) { return self->array.get(n, self->wrapfn); } template<> PyObject *toSequence(_t_jobjectarray *self) { return self->array.toSequence(self->wrapfn); } template<> PyObject *toSequence(_t_jobjectarray *self, Py_ssize_t lo, Py_ssize_t hi) { return self->array.toSequence(lo, hi, self->wrapfn); } template<> int init< jobject,_t_jobjectarray >(_t_jobjectarray *self, PyObject *args, PyObject *kwds) { PyObject *obj, *clsObj = NULL; PyObject *(*wrapfn)(const jobject &) = NULL; jclass cls; if (!PyArg_ParseTuple(args, "O|O", &obj, &clsObj)) return -1; if (clsObj == NULL) cls = env->findClass("java/lang/Object"); else if (PyObject_TypeCheck(clsObj, PY_TYPE(Class))) cls = (jclass) ((t_Class *) clsObj)->object.this$; else if (PyType_Check(clsObj)) { if (PyType_IsSubtype((PyTypeObject *) clsObj, PY_TYPE(JObject))) { PyObject *cobj = PyObject_GetAttrString(clsObj, "wrapfn_"); if (cobj == NULL) PyErr_Clear(); else { wrapfn = (PyObject *(*)(const jobject &)) PyCapsule_GetPointer(cobj, "wrapfn"); Py_DECREF(cobj); } clsObj = PyObject_GetAttrString(clsObj, "class_"); if (clsObj == NULL) return -1; cls = (jclass) ((t_Class *) clsObj)->object.this$; Py_DECREF(clsObj); } else { PyErr_SetObject(PyExc_ValueError, clsObj); return -1; } } else { PyErr_SetObject(PyExc_TypeError, clsObj); return -1; } if (PySequence_Check(obj)) { self->array = JArray(cls, obj); if (PyErr_Occurred()) return -1; } else if (PyGen_Check(obj)) { PyObject *tuple = PyObject_CallFunctionObjArgs((PyObject *) &PyTuple_Type, obj, NULL); if (!tuple) return -1; self->array = JArray(cls, tuple); Py_DECREF(tuple); if (PyErr_Occurred()) return -1; } else if (PyLong_Check(obj)) { int n = PyLong_AsLong(obj); if (n < 0) { PyErr_SetObject(PyExc_ValueError, obj); return -1; } self->array = JArray(cls, n); } else { PyErr_SetObject(PyExc_TypeError, obj); return -1; } self->wrapfn = wrapfn; return 0; } template<> jclass initializeClass(bool getOnly) { jclass cls = env->findClass("java/lang/Object"); return env->get_vm_env()->GetObjectClass(JArray(cls, (Py_ssize_t) 0).this$); } template<> PyObject *cast_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsArg = NULL; PyObject *(*wrapfn)(const jobject&) = NULL; jclass elementCls; if (!PyArg_ParseTuple(args, "O|O", &arg, &clsArg)) return NULL; if (!PyObject_TypeCheck(arg, PY_TYPE(Object))) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } if (clsArg != NULL) { if (!PyType_Check(clsArg)) { PyErr_SetObject(PyExc_TypeError, clsArg); return NULL; } else if (!PyType_IsSubtype((PyTypeObject *) clsArg, PY_TYPE(JObject))) { PyErr_SetObject(PyExc_ValueError, clsArg); return NULL; } PyObject *cobj = PyObject_GetAttrString(clsArg, "wrapfn_"); if (cobj == NULL) PyErr_Clear(); else { wrapfn = (PyObject *(*)(const jobject &)) PyCapsule_GetPointer(cobj, "wrapfn"); Py_DECREF(cobj); } clsArg = PyObject_GetAttrString(clsArg, "class_"); if (clsArg == NULL) return NULL; elementCls = (jclass) ((t_Class *) clsArg)->object.this$; Py_DECREF(clsArg); } else elementCls = env->findClass("java/lang/Object"); JNIEnv *vm_env = env->get_vm_env(); jobjectArray array = vm_env->NewObjectArray(0, elementCls, NULL); Class arrayCls(vm_env->GetObjectClass((jobject) array)); if (!arrayCls.isAssignableFrom(argCls)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } return JArray(((t_JObject *) arg)->object.this$).wrap(wrapfn); } template<> PyObject *wrapfn_(const jobject &object) { PyObject *cobj = PyObject_GetAttrString( (PyObject *) PY_TYPE(Object), "wrapfn_"); PyObject *(*wrapfn)(const jobject&) = NULL; if (cobj == NULL) PyErr_Clear(); else { wrapfn = (PyObject *(*)(const jobject &)) PyCapsule_GetPointer(cobj, "wrapfn"); Py_DECREF(cobj); } return JArray(object).wrap(wrapfn); } template<> PyObject *instance_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsArg = NULL; jclass elementCls; if (!PyArg_ParseTuple(args, "O|O", &arg, &clsArg)) return NULL; if (!PyObject_TypeCheck(arg, PY_TYPE(Object))) Py_RETURN_FALSE; Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) Py_RETURN_FALSE; if (clsArg != NULL) { if (!PyType_Check(clsArg)) { PyErr_SetObject(PyExc_TypeError, clsArg); return NULL; } else if (!PyType_IsSubtype((PyTypeObject *) clsArg, PY_TYPE(JObject))) { PyErr_SetObject(PyExc_ValueError, clsArg); return NULL; } clsArg = PyObject_GetAttrString(clsArg, "class_"); if (clsArg == NULL) return NULL; elementCls = (jclass) ((t_Class *) clsArg)->object.this$; Py_DECREF(clsArg); } else elementCls = env->findClass("java/lang/Object"); JNIEnv *vm_env = env->get_vm_env(); jobjectArray array = vm_env->NewObjectArray(0, elementCls, NULL); Class arrayCls(vm_env->GetObjectClass((jobject) array)); if (!arrayCls.isAssignableFrom(argCls)) Py_RETURN_FALSE; Py_RETURN_TRUE; } template<> PyObject *assignable_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsArg = NULL; jclass elementCls; if (!PyArg_ParseTuple(args, "O|O", &arg, &clsArg)) return NULL; if (!PyObject_TypeCheck(arg, PY_TYPE(Object))) Py_RETURN_FALSE; Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) Py_RETURN_FALSE; if (clsArg != NULL) { if (!PyType_Check(clsArg)) { PyErr_SetObject(PyExc_TypeError, clsArg); return NULL; } else if (!PyType_IsSubtype((PyTypeObject *) clsArg, PY_TYPE(JObject))) { PyErr_SetObject(PyExc_ValueError, clsArg); return NULL; } clsArg = PyObject_GetAttrString(clsArg, "class_"); if (clsArg == NULL) return NULL; elementCls = (jclass) ((t_Class *) clsArg)->object.this$; Py_DECREF(clsArg); } else elementCls = env->findClass("java/lang/Object"); JNIEnv *vm_env = env->get_vm_env(); jobjectArray array = vm_env->NewObjectArray(0, elementCls, NULL); Class arrayCls(vm_env->GetObjectClass((jobject) array)); if (!argCls.isAssignableFrom(arrayCls)) Py_RETURN_FALSE; Py_RETURN_TRUE; } template PyTypeObject *_t_iterator::JArrayIterator; template PyObject *_t_JArray::format; static jarray_type< jobject, _t_jobjectarray > jarray_jobject; static jarray_type jarray_jstring; static jarray_type jarray_jboolean; static jarray_type jarray_jbyte; static jarray_type jarray_jchar; static jarray_type jarray_jdouble; static jarray_type jarray_jfloat; static jarray_type jarray_jint; static jarray_type jarray_jlong; static jarray_type jarray_jshort; PyObject *JArray::wrap(PyObject *(*wrapfn)(const jobject&)) const { if (this$ != NULL) { _t_jobjectarray *obj = PyObject_New(_t_jobjectarray, jarray_jobject.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; obj->wrapfn = wrapfn; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jstring.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jboolean.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jbyte.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jchar.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jdouble.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jfloat.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jint.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jlong.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, jarray_jshort.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray_Type(PyObject *self, PyObject *arg) { PyObject *type_name = NULL, *type; char const *name = NULL; if (PyType_Check(arg)) { type_name = PyObject_GetAttrString(arg, "__name__"); if (!type_name) return NULL; } else if (PyUnicode_Check(arg)) { type_name = arg; Py_INCREF(type_name); } else if (PyFloat_Check(arg)) { type_name = NULL; name = "double"; } else { PyObject *arg_type = (PyObject *) arg->ob_type; type_name = PyObject_GetAttrString(arg_type, "__name__"); if (!type_name) return NULL; } if (type_name != NULL) { name = PyUnicode_AsUTF8(type_name); if (!name) { Py_DECREF(type_name); return NULL; } } if (!strcmp(name, "object")) type = (PyObject *) jarray_jobject.type_object; else if (!strcmp(name, "string")) type = (PyObject *) jarray_jstring.type_object; else if (!strcmp(name, "bool")) type = (PyObject *) jarray_jboolean.type_object; else if (!strcmp(name, "byte")) type = (PyObject *) jarray_jbyte.type_object; else if (!strcmp(name, "char")) type = (PyObject *) jarray_jchar.type_object; else if (!strcmp(name, "double")) type = (PyObject *) jarray_jdouble.type_object; else if (!strcmp(name, "float")) type = (PyObject *) jarray_jfloat.type_object; else if (!strcmp(name, "int")) type = (PyObject *) jarray_jint.type_object; else if (!strcmp(name, "long")) type = (PyObject *) jarray_jlong.type_object; else if (!strcmp(name, "short")) type = (PyObject *) jarray_jshort.type_object; else { PyErr_SetObject(PyExc_ValueError, arg); Py_XDECREF(type_name); return NULL; } Py_INCREF(type); Py_XDECREF(type_name); return type; } PyTypeObject *PY_TYPE(JArrayObject); PyTypeObject *PY_TYPE(JArrayString); PyTypeObject *PY_TYPE(JArrayBool); PyTypeObject *PY_TYPE(JArrayByte); PyTypeObject *PY_TYPE(JArrayChar); PyTypeObject *PY_TYPE(JArrayDouble); PyTypeObject *PY_TYPE(JArrayFloat); PyTypeObject *PY_TYPE(JArrayInt); PyTypeObject *PY_TYPE(JArrayLong); PyTypeObject *PY_TYPE(JArrayShort); void _install_jarray(PyObject *module) { jarray_jobject.install("JArray_object", "object", "__JArray_object_iterator", module); PY_TYPE(JArrayObject) = jarray_jobject.type_object; jarray_jstring.install("JArray_string", "string", "__JArray_string_iterator", module); PY_TYPE(JArrayString) = jarray_jstring.type_object; jarray_jboolean.install("JArray_bool", "bool", "__JArray_bool_iterator", module); PY_TYPE(JArrayBool) = jarray_jboolean.type_object; jarray_jbyte.install("JArray_byte", "byte", "__JArray_byte_iterator", module); PY_TYPE(JArrayByte) = jarray_jbyte.type_object; jarray_jchar.install("JArray_char", "char", "__JArray_char_iterator", module); PY_TYPE(JArrayChar) = jarray_jchar.type_object; jarray_jdouble.install("JArray_double", "double", "__JArray_double_iterator", module); PY_TYPE(JArrayDouble) = jarray_jdouble.type_object; jarray_jfloat.install("JArray_float", "float", "__JArray_float_iterator", module); PY_TYPE(JArrayFloat) = jarray_jfloat.type_object; jarray_jint.install("JArray_int", "int", "__JArray_int_iterator", module); PY_TYPE(JArrayInt) = jarray_jint.type_object; jarray_jlong.install("JArray_long", "long", "__JArray_long_iterator", module); PY_TYPE(JArrayLong) = jarray_jlong.type_object; jarray_jshort.install("JArray_short", "short", "__JArray_short_iterator", module); PY_TYPE(JArrayShort) = jarray_jshort.type_object; } #endif /* PYTHON */ JCC-3.6/jcc3/sources/types.cpp0000644000076500000000000004303213360756627016362 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "structmember.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "functions.h" using namespace java::lang; /* FinalizerProxy */ static PyObject *t_fc_call(PyObject *self, PyObject *args, PyObject *kwds); static void t_fp_dealloc(t_fp *self); static PyObject *t_fp_getattro(t_fp *self, PyObject *name); static int t_fp_setattro(t_fp *self, PyObject *name, PyObject *value); static int t_fp_traverse(t_fp *self, visitproc visit, void *arg); static int t_fp_clear(t_fp *self); static PyObject *t_fp_repr(t_fp *self); static PyObject *t_fp_iter(t_fp *self); static Py_ssize_t t_fp_map_length(t_fp *self); static PyObject *t_fp_map_get(t_fp *self, PyObject *key); static int t_fp_map_set(t_fp *self, PyObject *key, PyObject *value); static Py_ssize_t t_fp_seq_length(t_fp *self); static PyObject *t_fp_seq_get(t_fp *self, Py_ssize_t n); static int t_fp_seq_contains(t_fp *self, PyObject *value); static PyObject *t_fp_seq_concat(t_fp *self, PyObject *arg); static PyObject *t_fp_seq_repeat(t_fp *self, Py_ssize_t n); static int t_fp_seq_set(t_fp *self, Py_ssize_t i, PyObject *value); static PyObject *t_fp_seq_inplace_concat(t_fp *self, PyObject *arg); static PyObject *t_fp_seq_inplace_repeat(t_fp *self, Py_ssize_t n); static PyTypeObject FinalizerClass_type = { PyVarObject_HEAD_INIT(NULL, 0) "jcc.FinalizerClass", /* tp_name */ PyType_Type.tp_basicsize, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc) t_fc_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "FinalizerClass", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyType_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; PyTypeObject *PY_TYPE(FinalizerClass) = &FinalizerClass_type; static PyMappingMethods t_fp_as_mapping = { (lenfunc)t_fp_map_length, /* mp_length */ (binaryfunc)t_fp_map_get, /* mp_subscript */ (objobjargproc)t_fp_map_set, /* mp_ass_subscript */ }; static PySequenceMethods t_fp_as_sequence = { (lenfunc)t_fp_seq_length, /* sq_length */ (binaryfunc)t_fp_seq_concat, /* sq_concat */ (ssizeargfunc)t_fp_seq_repeat, /* sq_repeat */ (ssizeargfunc)t_fp_seq_get, /* sq_item */ 0, /* was_sq_slice */ (ssizeobjargproc)t_fp_seq_set, /* sq_ass_item */ 0, /* was_sq_ass_slice */ (objobjproc)t_fp_seq_contains, /* sq_contains */ (binaryfunc)t_fp_seq_inplace_concat, /* sq_inplace_concat */ (ssizeargfunc)t_fp_seq_inplace_repeat, /* sq_inplace_repeat */ }; static PyTypeObject FinalizerProxy_type = { PyVarObject_HEAD_INIT(NULL, 0) "jcc.FinalizerProxy", /* tp_name */ sizeof(t_fp), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_fp_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)t_fp_repr, /* tp_repr */ 0, /* tp_as_number */ &t_fp_as_sequence, /* tp_as_sequence */ &t_fp_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)t_fp_getattro, /* tp_getattro */ (setattrofunc)t_fp_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC), /* tp_flags */ "FinalizerProxy", /* tp_doc */ (traverseproc)t_fp_traverse, /* tp_traverse */ (inquiry)t_fp_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)t_fp_iter, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; PyTypeObject *PY_TYPE(FinalizerProxy) = &FinalizerProxy_type; static PyObject *t_fc_call(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *obj = PyType_Type.tp_call(self, args, kwds); if (obj) { t_fp *fp = (t_fp *) PY_TYPE(FinalizerProxy)->tp_alloc(PY_TYPE(FinalizerProxy), 0); fp->object = obj; /* released by t_fp_clear() */ obj = (PyObject *) fp; } return obj; } static void t_fp_dealloc(t_fp *self) { if (self->object) ((t_JObject *) self->object)->object.weaken$(); t_fp_clear(self); self->ob_base.ob_type->tp_free((PyObject *) self); } static int t_fp_traverse(t_fp *self, visitproc visit, void *arg) { Py_VISIT(self->object); return 0; } static int t_fp_clear(t_fp *self) { Py_CLEAR(self->object); return 0; } static PyObject *t_fp_repr(t_fp *self) { return PyObject_Repr(self->object); } static PyObject *t_fp_iter(t_fp *self) { return PyObject_GetIter(self->object); } static PyObject *t_fp_getattro(t_fp *self, PyObject *name) { return PyObject_GetAttr(self->object, name); } static int t_fp_setattro(t_fp *self, PyObject *name, PyObject *value) { return PyObject_SetAttr(self->object, name, value); } static Py_ssize_t t_fp_map_length(t_fp *self) { return PyMapping_Size(self->object); } static PyObject *t_fp_map_get(t_fp *self, PyObject *key) { return PyObject_GetItem(self->object, key); } static int t_fp_map_set(t_fp *self, PyObject *key, PyObject *value) { if (value == NULL) return PyObject_DelItem(self->object, key); return PyObject_SetItem(self->object, key, value); } static Py_ssize_t t_fp_seq_length(t_fp *self) { return PySequence_Length(self->object); } static PyObject *t_fp_seq_get(t_fp *self, Py_ssize_t n) { return PySequence_GetItem(self->object, n); } static int t_fp_seq_contains(t_fp *self, PyObject *value) { return PySequence_Contains(self->object, value); } static PyObject *t_fp_seq_concat(t_fp *self, PyObject *arg) { return PySequence_Concat(self->object, arg); } static PyObject *t_fp_seq_repeat(t_fp *self, Py_ssize_t n) { return PySequence_Repeat(self->object, n); } static int t_fp_seq_set(t_fp *self, Py_ssize_t i, PyObject *value) { return PySequence_SetItem(self->object, i, value); } static PyObject *t_fp_seq_inplace_concat(t_fp *self, PyObject *arg) { return PySequence_InPlaceConcat(self->object, arg); } static PyObject *t_fp_seq_inplace_repeat(t_fp *self, Py_ssize_t n) { return PySequence_InPlaceRepeat(self->object, n); } /* const variable descriptor */ class t_descriptor { public: PyObject_HEAD int flags; union { PyObject *value; getclassfn initializeClass; } access; }; #define DESCRIPTOR_VALUE 0x0001 #define DESCRIPTOR_CLASS 0x0002 #define DESCRIPTOR_GETFN 0x0004 #define DESCRIPTOR_GENERIC 0x0008 static void t_descriptor_dealloc(t_descriptor *self); static PyObject *t_descriptor___get__(t_descriptor *self, PyObject *obj, PyObject *type); static PyMethodDef t_descriptor_methods[] = { { NULL, NULL, 0, NULL } }; static PyTypeObject ConstVariableDescriptor_type = { PyVarObject_HEAD_INIT(NULL, 0) "jcc.ConstVariableDescriptor", /* tp_name */ sizeof(t_descriptor), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_descriptor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "const variable descriptor", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ t_descriptor_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)t_descriptor___get__, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; PyTypeObject *PY_TYPE(ConstVariableDescriptor) = &ConstVariableDescriptor_type; static void t_descriptor_dealloc(t_descriptor *self) { if (self->flags & DESCRIPTOR_VALUE) { Py_DECREF(self->access.value); } self->ob_base.ob_type->tp_free((PyObject *) self); } PyObject *make_descriptor(PyType_Def *value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { PyTypeObject *type = makeType(value); Py_INCREF(type); self->access.value = (PyObject *) type; self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(getclassfn initializeClass) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.initializeClass = initializeClass; self->flags = DESCRIPTOR_CLASS; } return (PyObject *) self; } PyObject *make_descriptor(getclassfn initializeClass, int generics) { t_descriptor *self = (t_descriptor *) make_descriptor(initializeClass); if (self && generics) self->flags |= DESCRIPTOR_GENERIC; return (PyObject *) self; } PyObject *make_descriptor(PyObject *value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = value; self->flags = DESCRIPTOR_VALUE; } else Py_DECREF(value); return (PyObject *) self; } PyObject *make_descriptor(PyObject *(*wrapfn)(const jobject &)) { return make_descriptor(PyCapsule_New((void *) wrapfn, "wrapfn", NULL)); } PyObject *make_descriptor(boxfn fn) { return make_descriptor(PyCapsule_New((void *) fn, "boxfn", NULL)); } PyObject *make_descriptor(jboolean b) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { PyObject *value = b ? Py_True : Py_False; self->access.value = (PyObject *) value; Py_INCREF(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jbyte value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyLong_FromLong(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jchar value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = c2p(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jdouble value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyFloat_FromDouble(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jfloat value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyFloat_FromDouble((double) value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jint value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyLong_FromLong(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jlong value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyLong_FromLongLong((long long) value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jshort value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor)->tp_alloc(PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyLong_FromLong((short) value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } static PyObject *t_descriptor___get__(t_descriptor *self, PyObject *obj, PyObject *type) { if (self->flags & DESCRIPTOR_VALUE) { Py_INCREF(self->access.value); return self->access.value; } if (self->flags & DESCRIPTOR_CLASS) { #ifdef _java_generics if (self->flags & DESCRIPTOR_GENERIC) return t_Class::wrap_Object(Class(env->getClass(self->access.initializeClass)), (PyTypeObject *) type); else #endif return t_Class::wrap_Object(Class(env->getClass(self->access.initializeClass))); } Py_RETURN_NONE; } JCC-3.6/jcc3/sources/JObject.h0000644000076500000000000000424513171761200016165 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JObject_H #define _JObject_H #include #include "JCCEnv.h" class _DLL_EXPORT JObject { public: jobject this$; inline explicit JObject(jobject obj) { if (obj) { id = env->id(obj); this$ = env->newGlobalRef(obj, id); } else { id = 0; this$ = NULL; } } inline JObject(const JObject& obj) { id = obj.id ? obj.id : env->id(obj.this$); this$ = env->newGlobalRef(obj.this$, id); } virtual ~JObject() { this$ = env->deleteGlobalRef(this$, id); } JObject& weaken$() { if (id) { jobject ref = env->newGlobalRef(this$, 0); env->deleteGlobalRef(this$, id); id = 0; this$ = ref; } return *this; } inline int operator!() const { return env->isSame(this$, NULL); } inline int operator==(const JObject& obj) const { return env->isSame(this$, obj.this$); } JObject& operator=(const JObject& obj) { jobject prev = this$; int objid = obj.id ? obj.id : env->id(obj.this$); this$ = env->newGlobalRef(obj.this$, objid); env->deleteGlobalRef(prev, id); id = objid; return *this; } protected: JObject() {} private: int id; // zero when this$ is a weak ref */ }; #ifdef PYTHON #include #include "macros.h" class t_JObject { public: PyObject_HEAD JObject object; }; DECLARE_TYPE(JObject); #endif /* PYTHON */ #endif /* _JObject_H */ JCC-3.6/jcc3/sources/jccfuncs.h0000644000076500000000000000353413063017546016452 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _jccfuncs_H #define _jccfuncs_H #ifdef PYTHON PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds); PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds); PyObject *getVMEnv(PyObject *self); PyObject *_set_exception_types(PyObject *self, PyObject *args); PyObject *_set_function_self(PyObject *self, PyObject *args); PyObject *findClass(PyObject *self, PyObject *args); PyObject *makeInterface(PyObject *self, PyObject *args); PyObject *makeClass(PyObject *self, PyObject *args); PyObject *JArray_Type(PyObject *self, PyObject *arg); PyMethodDef jcc_funcs[] = { { "initVM", (PyCFunction) __initialize__, METH_VARARGS | METH_KEYWORDS, NULL }, { "getVMEnv", (PyCFunction) getVMEnv, METH_NOARGS, NULL }, { "findClass", (PyCFunction) findClass, METH_VARARGS, NULL }, { "makeInterface", (PyCFunction) makeInterface, METH_VARARGS, NULL }, { "makeClass", (PyCFunction) makeClass, METH_VARARGS, NULL }, { "_set_exception_types", (PyCFunction) _set_exception_types, METH_VARARGS, NULL }, { "_set_function_self", (PyCFunction) _set_function_self, METH_VARARGS, NULL }, { "JArray", (PyCFunction) JArray_Type, METH_O, NULL }, { NULL, NULL, 0, NULL } }; #endif #endif /* _jccfuncs_H */ JCC-3.6/jcc3/sources/JCCEnv.cpp0000644000076500000000000010225213114762222016247 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include #include "JCCEnv.h" #if defined(_MSC_VER) || defined(__WIN32) _DLL_EXPORT DWORD VM_ENV = 0; #else pthread_key_t JCCEnv::VM_ENV = (pthread_key_t) NULL; #endif #if defined(_MSC_VER) || defined(__WIN32) static CRITICAL_SECTION *mutex = NULL; class lock { public: lock() { EnterCriticalSection(mutex); } virtual ~lock() { LeaveCriticalSection(mutex); } }; #else static pthread_mutex_t *mutex = NULL; class lock { public: lock() { pthread_mutex_lock(mutex); } virtual ~lock() { pthread_mutex_unlock(mutex); } }; #endif // borrowed from ICU (http://icu-project.org/apiref/icu4c/utf16_8h.html) #define U16_LEAD(c) (jchar) (((c) >> 10) + 0xd7c0) #define U16_TRAIL(c) (jchar) (((c) & 0x3ff) | 0xdc00) #define U16_IS_LEAD(c) (((c) & 0xfffffc00) == 0xd800) #define U16_IS_TRAIL(c) (((c) & 0xfffffc00) == 0xdc00) #define U16_SURROGATE_OFFSET ((0xd800 << 10UL) + 0xdc00 - 0x10000) #define U16_GET_SUPPLEMENTARY(lead, trail) \ (((uint32_t) (lead) << 10UL) + (uint32_t) (trail) - U16_SURROGATE_OFFSET) #define U16_NEXT(s, i, length, c) { \ (c) = (s)[(i)++]; \ if (U16_IS_LEAD(c)) { \ jchar __c2; \ if ((i) != (length) && U16_IS_TRAIL(__c2 = (s)[(i)])) { \ ++(i); \ (c) = U16_GET_SUPPLEMENTARY((c), __c2); \ } \ } \ } JCCEnv::JCCEnv(JavaVM *vm, JNIEnv *vm_env) { #if defined(_MSC_VER) || defined(__WIN32) if (!mutex) { mutex = new CRITICAL_SECTION(); InitializeCriticalSection(mutex); // recursive by default } #else if (!mutex) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); mutex = new pthread_mutex_t(); pthread_mutex_init(mutex, &attr); } #endif if (vm) set_vm(vm, vm_env); else this->vm = NULL; } void JCCEnv::set_vm(JavaVM *vm, JNIEnv *vm_env) { this->vm = vm; set_vm_env(vm_env); _sys = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/System")); _obj = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Object")); #ifdef _jcc_lib _thr = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("org/apache/jcc/PythonException")); #else _thr = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/RuntimeException")); #endif _boo = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Boolean")); _byt = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Byte")); _cha = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Character")); _dou = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Double")); _flo = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Float")); _int = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Integer")); _lon = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Long")); _sho = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Short")); _mids = new jmethodID[max_mid]; _mids[mid_sys_identityHashCode] = vm_env->GetStaticMethodID(_sys, "identityHashCode", "(Ljava/lang/Object;)I"); _mids[mid_sys_setProperty] = vm_env->GetStaticMethodID(_sys, "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); _mids[mid_sys_getProperty] = vm_env->GetStaticMethodID(_sys, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"); _mids[mid_obj_toString] = vm_env->GetMethodID(_obj, "toString", "()Ljava/lang/String;"); _mids[mid_obj_hashCode] = vm_env->GetMethodID(_obj, "hashCode", "()I"); _mids[mid_obj_getClass] = vm_env->GetMethodID(_obj, "getClass", "()Ljava/lang/Class;"); jclass iterable = vm_env->FindClass("java/lang/Iterable"); if (iterable == NULL) /* JDK < 1.5 */ { vm_env->ExceptionClear(); _mids[mid_iterator] = NULL; _mids[mid_iterator_next] = NULL; } else { _mids[mid_iterator] = vm_env->GetMethodID(iterable, "iterator", "()Ljava/util/Iterator;"); _mids[mid_iterator_next] = vm_env->GetMethodID(vm_env->FindClass("java/util/Iterator"), "next", "()Ljava/lang/Object;"); } _mids[mid_enumeration_nextElement] = vm_env->GetMethodID(vm_env->FindClass("java/util/Enumeration"), "nextElement", "()Ljava/lang/Object;"); _mids[mid_Boolean_booleanValue] = vm_env->GetMethodID(_boo, "booleanValue", "()Z"); _mids[mid_Byte_byteValue] = vm_env->GetMethodID(_byt, "byteValue", "()B"); _mids[mid_Character_charValue] = vm_env->GetMethodID(_cha, "charValue", "()C"); _mids[mid_Double_doubleValue] = vm_env->GetMethodID(_dou, "doubleValue", "()D"); _mids[mid_Float_floatValue] = vm_env->GetMethodID(_flo, "floatValue", "()F"); _mids[mid_Integer_intValue] = vm_env->GetMethodID(_int, "intValue", "()I"); _mids[mid_Long_longValue] = vm_env->GetMethodID(_lon, "longValue", "()J"); _mids[mid_Short_shortValue] = vm_env->GetMethodID(_sho, "shortValue", "()S"); _mids[mid_Boolean_init] = vm_env->GetMethodID(_boo, "", "(Z)V"); _mids[mid_Byte_init] = vm_env->GetMethodID(_byt, "", "(B)V"); _mids[mid_Character_init] = vm_env->GetMethodID(_cha, "", "(C)V"); _mids[mid_Double_init] = vm_env->GetMethodID(_dou, "", "(D)V"); _mids[mid_Float_init] = vm_env->GetMethodID(_flo, "", "(F)V"); _mids[mid_Integer_init] = vm_env->GetMethodID(_int, "", "(I)V"); _mids[mid_Long_init] = vm_env->GetMethodID(_lon, "", "(J)V"); _mids[mid_Short_init] = vm_env->GetMethodID(_sho, "", "(S)V"); } int JCCEnv::attachCurrentThread(char *name, int asDaemon) { JNIEnv *jenv = NULL; JavaVMAttachArgs attach = { JNI_VERSION_1_4, name, NULL }; int result; if (asDaemon) result = vm->AttachCurrentThreadAsDaemon((void **) &jenv, &attach); else result = vm->AttachCurrentThread((void **) &jenv, &attach); set_vm_env(jenv); return result; } #if defined(_MSC_VER) || defined(__WIN32) void JCCEnv::set_vm_env(JNIEnv *vm_env) { if (!VM_ENV) VM_ENV = TlsAlloc(); TlsSetValue(VM_ENV, (LPVOID) vm_env); } #else void JCCEnv::set_vm_env(JNIEnv *vm_env) { if (!VM_ENV) pthread_key_create(&VM_ENV, NULL); pthread_setspecific(VM_ENV, (void *) vm_env); } #endif jint JCCEnv::getJNIVersion() const { return get_vm_env()->GetVersion(); } jstring JCCEnv::getJavaVersion() const { return (jstring) callStaticObjectMethod(_sys, _mids[mid_sys_getProperty], get_vm_env()->NewStringUTF("java.version")); } jobject JCCEnv::iterator(jobject obj) const { return callObjectMethod(obj, _mids[mid_iterator]); } jobject JCCEnv::iteratorNext(jobject obj) const { return callObjectMethod(obj, _mids[mid_iterator_next]); } jobject JCCEnv::enumerationNext(jobject obj) const { return callObjectMethod(obj, _mids[mid_enumeration_nextElement]); } jboolean JCCEnv::isInstanceOf(jobject obj, getclassfn initializeClass) const { return get_vm_env()->IsInstanceOf(obj, getClass(initializeClass)); } jclass JCCEnv::findClass(const char *className) const { jclass cls = NULL; if (vm) { JNIEnv *vm_env = get_vm_env(); if (vm_env) { cls = vm_env->FindClass(className); if (cls == NULL) reportException(); } #ifdef PYTHON else { PythonGIL gil; PyErr_SetString(PyExc_RuntimeError, "attachCurrentThread() must be called first"); throw _EXC_PYTHON; } #else else throw _EXC_JAVA; #endif } #ifdef PYTHON else { PythonGIL gil; PyErr_SetString(PyExc_RuntimeError, "initVM() must be called first"); throw _EXC_PYTHON; } #else else throw _EXC_JAVA; #endif reportException(); return cls; } void JCCEnv::registerNatives(jclass cls, JNINativeMethod *methods, int n) const { get_vm_env()->RegisterNatives(cls, methods, n); } jobject JCCEnv::newGlobalRef(jobject obj, int id) { if (obj) { if (id) /* zero when weak global ref is desired */ { lock locked; for (std::multimap::iterator iter = refs.find(id); iter != refs.end(); iter++) { if (iter->first != id) break; if (isSame(obj, iter->second.global)) { /* If it's in the table but not the same reference, * it must be a local reference and must be deleted. */ if (obj != iter->second.global) get_vm_env()->DeleteLocalRef(obj); iter->second.count += 1; return iter->second.global; } } JNIEnv *vm_env = get_vm_env(); countedRef ref; ref.global = vm_env->NewGlobalRef(obj); ref.count = 1; refs.insert(std::pair(id, ref)); vm_env->DeleteLocalRef(obj); return ref.global; } else return (jobject) get_vm_env()->NewWeakGlobalRef(obj); } return NULL; } jobject JCCEnv::deleteGlobalRef(jobject obj, int id) { if (obj) { if (id) /* zero when obj is weak global ref */ { lock locked; for (std::multimap::iterator iter = refs.find(id); iter != refs.end(); iter++) { if (iter->first != id) break; if (isSame(obj, iter->second.global)) { if (iter->second.count == 1) { JNIEnv *vm_env = get_vm_env(); if (!vm_env) { /* Python's cyclic garbage collector may remove * an object inside a thread that is not attached * to the JVM. This makes sure the JVM doesn't * segfault. */ attachCurrentThread(NULL, 0); vm_env = get_vm_env(); } vm_env->DeleteGlobalRef(iter->second.global); refs.erase(iter); } else iter->second.count -= 1; return NULL; } } printf("deleting non-existent ref: 0x%x\n", id); } else get_vm_env()->DeleteWeakGlobalRef((jweak) obj); } return NULL; } jclass JCCEnv::getClass(getclassfn initializeClass) const { jclass cls = (*initializeClass)(true); if (cls == NULL) { lock locked; cls = (*initializeClass)(false); } return cls; } jobject JCCEnv::newObject(getclassfn initializeClass, jmethodID **mids, int m, ...) { jclass cls = getClass(initializeClass); JNIEnv *vm_env = get_vm_env(); jobject obj; if (vm_env) { va_list ap; va_start(ap, m); obj = vm_env->NewObjectV(cls, (*mids)[m], ap); va_end(ap); } #ifdef PYTHON else { PythonGIL gil; PyErr_SetString(PyExc_RuntimeError, "attachCurrentThread() must be called first"); throw _EXC_PYTHON; } #else else throw _EXC_JAVA; #endif reportException(); return obj; } jobjectArray JCCEnv::newObjectArray(jclass cls, int size) { jobjectArray array = get_vm_env()->NewObjectArray(size, cls, NULL); reportException(); return array; } void JCCEnv::setObjectArrayElement(jobjectArray array, int n, jobject obj) const { get_vm_env()->SetObjectArrayElement(array, n, obj); reportException(); } jobject JCCEnv::getObjectArrayElement(jobjectArray array, int n) const { jobject obj = get_vm_env()->GetObjectArrayElement(array, n); reportException(); return obj; } int JCCEnv::getArrayLength(jarray array) const { int len = get_vm_env()->GetArrayLength(array); reportException(); return len; } #ifdef PYTHON jclass JCCEnv::getPythonExceptionClass() const { return _thr; } // returns true if Python exception instance was successfully restored bool JCCEnv::restorePythonException(jthrowable throwable) const { #ifdef _jcc_lib // PythonException is only available in shared mode jclass pycls = getPythonExceptionClass(); JNIEnv *vm_env = get_vm_env(); // Support through-layer exceptions by taking the active PythonException // and making the enclosed exception visible to Python again. if (vm_env->IsSameObject(vm_env->GetObjectClass(throwable), pycls)) { jfieldID fid = vm_env->GetFieldID(pycls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(throwable, fid); if (state != NULL) { PyObject *type = PyTuple_GET_ITEM(state, 0); PyObject *value = PyTuple_GET_ITEM(state, 1); PyObject *tb = PyTuple_GET_ITEM(state, 2); Py_INCREF(type); if (value == Py_None) value = NULL; else Py_INCREF(value); if (tb == Py_None) tb = NULL; else Py_INCREF(tb); PyErr_Restore(type, value, tb); return true; } } #endif return false; } #endif void JCCEnv::reportException() const { JNIEnv *vm_env = get_vm_env(); jthrowable throwable = vm_env->ExceptionOccurred(); if (throwable) { if (!env->handlers) vm_env->ExceptionDescribe(); #ifdef PYTHON PythonGIL gil; if (PyErr_Occurred()) { /* _thr is PythonException ifdef _jcc_lib (shared mode) * if not shared mode, _thr is RuntimeException */ jobject cls = (jobject) vm_env->GetObjectClass(throwable); if (vm_env->IsSameObject(cls, _thr)) { #ifndef _jcc_lib /* PythonException class is not available without shared mode. * Python exception information thus gets lost and exception * is reported via plain Java RuntimeException. */ PyErr_Clear(); throw _EXC_JAVA; #else throw _EXC_PYTHON; #endif } } #endif throw _EXC_JAVA; } } #define DEFINE_CALL(jtype, Type) \ jtype JCCEnv::call##Type##Method(jobject obj, \ jmethodID mid, ...) const \ { \ va_list ap; \ jtype result; \ \ va_start(ap, mid); \ result = get_vm_env()->Call##Type##MethodV(obj, mid, ap); \ va_end(ap); \ \ reportException(); \ \ return result; \ } #define DEFINE_NONVIRTUAL_CALL(jtype, Type) \ jtype JCCEnv::callNonvirtual##Type##Method(jobject obj, jclass cls, \ jmethodID mid, ...) const \ { \ va_list ap; \ jtype result; \ \ va_start(ap, mid); \ result = get_vm_env()->CallNonvirtual##Type##MethodV(obj, cls, \ mid, ap); \ va_end(ap); \ \ reportException(); \ \ return result; \ } #define DEFINE_STATIC_CALL(jtype, Type) \ jtype JCCEnv::callStatic##Type##Method(jclass cls, \ jmethodID mid, ...) const \ { \ va_list ap; \ jtype result; \ \ va_start(ap, mid); \ result = get_vm_env()->CallStatic##Type##MethodV(cls, mid, ap); \ va_end(ap); \ \ reportException(); \ \ return result; \ } DEFINE_CALL(jobject, Object) DEFINE_CALL(jboolean, Boolean) DEFINE_CALL(jbyte, Byte) DEFINE_CALL(jchar, Char) DEFINE_CALL(jdouble, Double) DEFINE_CALL(jfloat, Float) DEFINE_CALL(jint, Int) DEFINE_CALL(jlong, Long) DEFINE_CALL(jshort, Short) DEFINE_NONVIRTUAL_CALL(jobject, Object) DEFINE_NONVIRTUAL_CALL(jboolean, Boolean) DEFINE_NONVIRTUAL_CALL(jbyte, Byte) DEFINE_NONVIRTUAL_CALL(jchar, Char) DEFINE_NONVIRTUAL_CALL(jdouble, Double) DEFINE_NONVIRTUAL_CALL(jfloat, Float) DEFINE_NONVIRTUAL_CALL(jint, Int) DEFINE_NONVIRTUAL_CALL(jlong, Long) DEFINE_NONVIRTUAL_CALL(jshort, Short) DEFINE_STATIC_CALL(jobject, Object) DEFINE_STATIC_CALL(jboolean, Boolean) DEFINE_STATIC_CALL(jbyte, Byte) DEFINE_STATIC_CALL(jchar, Char) DEFINE_STATIC_CALL(jdouble, Double) DEFINE_STATIC_CALL(jfloat, Float) DEFINE_STATIC_CALL(jint, Int) DEFINE_STATIC_CALL(jlong, Long) DEFINE_STATIC_CALL(jshort, Short) void JCCEnv::callVoidMethod(jobject obj, jmethodID mid, ...) const { va_list ap; va_start(ap, mid); get_vm_env()->CallVoidMethodV(obj, mid, ap); va_end(ap); reportException(); } void JCCEnv::callNonvirtualVoidMethod(jobject obj, jclass cls, jmethodID mid, ...) const { va_list ap; va_start(ap, mid); get_vm_env()->CallNonvirtualVoidMethodV(obj, cls, mid, ap); va_end(ap); reportException(); } void JCCEnv::callStaticVoidMethod(jclass cls, jmethodID mid, ...) const { va_list ap; va_start(ap, mid); get_vm_env()->CallStaticVoidMethodV(cls, mid, ap); va_end(ap); reportException(); } jboolean JCCEnv::booleanValue(jobject obj) const { return get_vm_env()->CallBooleanMethod(obj, _mids[mid_Boolean_booleanValue]); } jbyte JCCEnv::byteValue(jobject obj) const { return get_vm_env()->CallByteMethod(obj, _mids[mid_Byte_byteValue]); } jchar JCCEnv::charValue(jobject obj) const { return get_vm_env()->CallCharMethod(obj, _mids[mid_Character_charValue]); } jdouble JCCEnv::doubleValue(jobject obj) const { return get_vm_env()->CallDoubleMethod(obj, _mids[mid_Double_doubleValue]); } jfloat JCCEnv::floatValue(jobject obj) const { return get_vm_env()->CallFloatMethod(obj, _mids[mid_Float_floatValue]); } jint JCCEnv::intValue(jobject obj) const { return get_vm_env()->CallIntMethod(obj, _mids[mid_Integer_intValue]); } jlong JCCEnv::longValue(jobject obj) const { return get_vm_env()->CallLongMethod(obj, _mids[mid_Long_longValue]); } jshort JCCEnv::shortValue(jobject obj) const { return get_vm_env()->CallShortMethod(obj, _mids[mid_Short_shortValue]); } jobject JCCEnv::boxBoolean(jboolean value) const { return get_vm_env()->NewObject(_boo, _mids[mid_Boolean_init], value); } jobject JCCEnv::boxByte(jbyte value) const { return get_vm_env()->NewObject(_byt, _mids[mid_Byte_init], value); } jobject JCCEnv::boxChar(jchar value) const { return get_vm_env()->NewObject(_cha, _mids[mid_Character_init], value); } jobject JCCEnv::boxDouble(jdouble value) const { return get_vm_env()->NewObject(_dou, _mids[mid_Double_init], value); } jobject JCCEnv::boxFloat(jfloat value) const { return get_vm_env()->NewObject(_flo, _mids[mid_Float_init], value); } jobject JCCEnv::boxInteger(jint value) const { return get_vm_env()->NewObject(_int, _mids[mid_Integer_init], value); } jobject JCCEnv::boxLong(jlong value) const { return get_vm_env()->NewObject(_lon, _mids[mid_Long_init], value); } jobject JCCEnv::boxShort(jshort value) const { return get_vm_env()->NewObject(_sho, _mids[mid_Short_init], value); } jmethodID JCCEnv::getMethodID(jclass cls, const char *name, const char *signature) const { jmethodID id = get_vm_env()->GetMethodID(cls, name, signature); reportException(); return id; } jfieldID JCCEnv::getFieldID(jclass cls, const char *name, const char *signature) const { jfieldID id = get_vm_env()->GetFieldID(cls, name, signature); reportException(); return id; } jmethodID JCCEnv::getStaticMethodID(jclass cls, const char *name, const char *signature) const { jmethodID id = get_vm_env()->GetStaticMethodID(cls, name, signature); reportException(); return id; } jobject JCCEnv::getStaticObjectField(jclass cls, const char *name, const char *signature) const { JNIEnv *vm_env = get_vm_env(); jfieldID id = vm_env->GetStaticFieldID(cls, name, signature); reportException(); return vm_env->GetStaticObjectField(cls, id); } #define DEFINE_GET_STATIC_FIELD(jtype, Type, signature) \ jtype JCCEnv::getStatic##Type##Field(jclass cls, \ const char *name) const \ { \ JNIEnv *vm_env = get_vm_env(); \ jfieldID id = vm_env->GetStaticFieldID(cls, name, #signature); \ reportException(); \ return vm_env->GetStatic##Type##Field(cls, id); \ } DEFINE_GET_STATIC_FIELD(jboolean, Boolean, Z) DEFINE_GET_STATIC_FIELD(jbyte, Byte, B) DEFINE_GET_STATIC_FIELD(jchar, Char, C) DEFINE_GET_STATIC_FIELD(jdouble, Double, D) DEFINE_GET_STATIC_FIELD(jfloat, Float, F) DEFINE_GET_STATIC_FIELD(jint, Int, I) DEFINE_GET_STATIC_FIELD(jlong, Long, J) DEFINE_GET_STATIC_FIELD(jshort, Short, S) #define DEFINE_GET_FIELD(jtype, Type) \ jtype JCCEnv::get##Type##Field(jobject obj, jfieldID id) const \ { \ jtype value = get_vm_env()->Get##Type##Field(obj, id); \ reportException(); \ return value; \ } DEFINE_GET_FIELD(jobject, Object) DEFINE_GET_FIELD(jboolean, Boolean) DEFINE_GET_FIELD(jbyte, Byte) DEFINE_GET_FIELD(jchar, Char) DEFINE_GET_FIELD(jdouble, Double) DEFINE_GET_FIELD(jfloat, Float) DEFINE_GET_FIELD(jint, Int) DEFINE_GET_FIELD(jlong, Long) DEFINE_GET_FIELD(jshort, Short) #define DEFINE_SET_FIELD(jtype, Type) \ void JCCEnv::set##Type##Field(jobject obj, jfieldID id, \ jtype value) const \ { \ get_vm_env()->Set##Type##Field(obj, id, value); \ reportException(); \ } DEFINE_SET_FIELD(jobject, Object) DEFINE_SET_FIELD(jboolean, Boolean) DEFINE_SET_FIELD(jbyte, Byte) DEFINE_SET_FIELD(jchar, Char) DEFINE_SET_FIELD(jdouble, Double) DEFINE_SET_FIELD(jfloat, Float) DEFINE_SET_FIELD(jint, Int) DEFINE_SET_FIELD(jlong, Long) DEFINE_SET_FIELD(jshort, Short) void JCCEnv::setClassPath(const char *classPath) { JNIEnv *vm_env = get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jclass _fil = (jclass) vm_env->FindClass("java/io/File"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); jmethodID mf = vm_env->GetMethodID(_fil, "", "(Ljava/lang/String;)V"); jmethodID mu = vm_env->GetMethodID(_fil, "toURL", "()Ljava/net/URL;"); jmethodID ma = vm_env->GetMethodID(_ucl, "addURL", "(Ljava/net/URL;)V"); #if defined(_MSC_VER) || defined(__WIN32) const char *pathsep = ";"; char *path = _strdup(classPath); #else const char *pathsep = ":"; char *path = strdup(classPath); #endif for (char *cp = strtok(path, pathsep); cp != NULL; cp = strtok(NULL, pathsep)) { jstring string = vm_env->NewStringUTF(cp); jobject file = vm_env->NewObject(_fil, mf, string); jobject url = vm_env->CallObjectMethod(file, mu); vm_env->CallVoidMethod(classLoader, ma, url); } free(path); } char *JCCEnv::getClassPath() { JNIEnv *vm_env = get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jclass _url = (jclass) vm_env->FindClass("java/net/URL"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); jmethodID gu = vm_env->GetMethodID(_ucl, "getURLs", "()[Ljava/net/URL;"); jmethodID gp = vm_env->GetMethodID(_url, "getPath", "()Ljava/lang/String;"); #if defined(_MSC_VER) || defined(__WIN32) const char *pathsep = ";"; #else const char *pathsep = ":"; #endif jobjectArray array = (jobjectArray) vm_env->CallObjectMethod(classLoader, gu); int count = array ? vm_env->GetArrayLength(array) : 0; int first = 1, total = 0; char *classpath = NULL; for (int i = 0; i < count; i++) { jobject url = vm_env->GetObjectArrayElement(array, i); jstring path = (jstring) vm_env->CallObjectMethod(url, gp); const char *chars = vm_env->GetStringUTFChars(path, NULL); int size = vm_env->GetStringUTFLength(path); total += size + 1; if (classpath == NULL) classpath = (char *) calloc(total, 1); else classpath = (char *) realloc(classpath, total); if (classpath == NULL) return NULL; if (first) first = 0; else strcat(classpath, pathsep); strcat(classpath, chars); } return classpath; } jstring JCCEnv::fromUTF32(const uint32_t *chars, jsize len) const { std::vector jchars; for (jsize i = 0; i < len; ++i) { uint32_t c = chars[i]; if (c <= 0xd7ff || (c >= 0xe000 && c <= 0xffff)) { jchars.push_back((jchar) c); } else if (c >= 0x10000 && c <= 0x10ffff) { jchars.push_back(U16_LEAD(c)); jchars.push_back(U16_TRAIL(c)); } else if (c >= 0xd800 && c <= 0xdfff) { jchars.push_back((jchar) 0xfffd); // invalid char } } jstring str = get_vm_env()->NewString(jchars.data(), jchars.size()); reportException(); return str; } #ifdef PYTHON jstring JCCEnv::fromPyString(PyObject *object) const { if (object == Py_None) return NULL; if (PyUnicode_Check(object)) { PyUnicode_READY(object); switch (PyUnicode_KIND(object)) { case PyUnicode_WCHAR_KIND: { // this code path should be deprecated if (sizeof(Py_UNICODE) == sizeof(jchar)) { Py_ssize_t len; Py_UNICODE *pchars = PyUnicode_AsUnicodeAndSize(object, &len); return get_vm_env()->NewString((jchar *) pchars, (jsize) len); } else // Py_UNICODE 32-bit case { Py_ssize_t len; Py_UNICODE *pchars = PyUnicode_AsUnicodeAndSize(object, &len); return fromUTF32((uint32_t *) pchars, (jsize) len); } } case PyUnicode_1BYTE_KIND: return get_vm_env()->NewStringUTF( (const char *) PyUnicode_1BYTE_DATA(object)); case PyUnicode_2BYTE_KIND: { Py_ssize_t len = PyUnicode_GET_LENGTH(object); Py_UCS2 *pchars = PyUnicode_2BYTE_DATA(object); return get_vm_env()->NewString((jchar *) pchars, (jsize) len); } case PyUnicode_4BYTE_KIND: { Py_ssize_t len = PyUnicode_GET_LENGTH(object); Py_UCS4 *pchars = PyUnicode_4BYTE_DATA(object); return fromUTF32((uint32_t *) pchars, (jsize) len); } } } else if (PyBytes_Check(object)) return get_vm_env()->NewStringUTF(PyBytes_AS_STRING(object)); PyObject *tuple = Py_BuildValue("(sO)", "expected a string", object); PyErr_SetObject(PyExc_TypeError, tuple); Py_DECREF(tuple); return NULL; } PyObject *JCCEnv::fromJString(jstring js, int delete_local_ref) const { if (!js) Py_RETURN_NONE; JNIEnv *vm_env = get_vm_env(); jsize len16 = vm_env->GetStringLength(js); jboolean isCopy; const jchar *utf16 = vm_env->GetStringChars(js, &isCopy); int32_t len32 = 0; uint32_t max_char = 0; for (jsize i = 0; i < len16;) { uint32_t cp; U16_NEXT(utf16, i, len16, cp); max_char |= cp; // we only care about the leftmost bit len32 += 1; } PyObject *result = PyUnicode_New(len32, max_char); if (result == NULL) { vm_env->ReleaseStringChars(js, utf16); return NULL; } switch (PyUnicode_KIND(result)) { case PyUnicode_1BYTE_KIND: // note: len16 == len32 for (int32_t i = 0; i < len32; ++i) PyUnicode_1BYTE_DATA(result)[i] = (Py_UCS1) (utf16[i]); break; case PyUnicode_2BYTE_KIND: // note: len16 == len32 memcpy(PyUnicode_2BYTE_DATA(result), utf16, len16 * 2); break; case PyUnicode_4BYTE_KIND: len32 = 0; for (jsize i = 0; i < len16;) { uint32_t cp; U16_NEXT(utf16, i, len16, cp); PyUnicode_4BYTE_DATA(result)[len32++] = cp; } break; default: Py_DECREF(result); vm_env->ReleaseStringChars(js, utf16); return NULL; } vm_env->ReleaseStringChars(js, utf16); if (delete_local_ref) vm_env->DeleteLocalRef((jobject) js); return result; } PyObject *JCCEnv::toPyUnicode(jobject obj) const { try { if (obj) return fromJString((jstring) callObjectMethod( obj, _mids[mid_obj_toString]), 0); Py_RETURN_NONE; } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: { JNIEnv *vm_env = get_vm_env(); vm_env->ExceptionDescribe(); vm_env->ExceptionClear(); return NULL; } default: throw; } } } PyObject *JCCEnv::getClassName(jobject obj) const { if (obj) return toPyUnicode(callObjectMethod(obj, _mids[mid_obj_getClass])); Py_RETURN_NONE; } /* may be called from finalizer thread which has no vm_env thread local */ void JCCEnv::finalizeObject(JNIEnv *jenv, PyObject *obj) { PythonGIL gil; set_vm_env(jenv); Py_DECREF(obj); } #endif /* PYTHON */ JCC-3.6/jcc3/sources/JObject.cpp0000644000076500000000000001374513171761200016525 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #ifdef PYTHON #include #include "structmember.h" #include "JObject.h" #include "macros.h" /* JObject */ static void t_JObject_dealloc(t_JObject *self); static PyObject *t_JObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject *t_JObject_richcmp(t_JObject *, PyObject *o2, int op); static PyObject *t_JObject_str(t_JObject *self); static PyObject *t_JObject_repr(t_JObject *self); static int t_JObject_hash(t_JObject *self); static PyObject *t_JObject__getJObject(t_JObject *self, void *data); static PyMemberDef t_JObject_members[] = { { NULL, 0, 0, 0, NULL } }; static PyMethodDef t_JObject_methods[] = { { NULL, NULL, 0, NULL } }; static PyGetSetDef t_JObject_properties[] = { { "_jobject", (getter) t_JObject__getJObject, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static PyTypeObject JObject_type = { PyVarObject_HEAD_INIT(NULL, 0) "jcc.JObject", /* tp_name */ sizeof(t_JObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_JObject_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)t_JObject_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)t_JObject_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)t_JObject_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE), /* tp_flags */ "t_JObject objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)t_JObject_richcmp, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ t_JObject_methods, /* tp_methods */ t_JObject_members, /* tp_members */ t_JObject_properties, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ (newfunc)t_JObject_new, /* tp_new */ }; // used only to hold a pointer to JObject_type once JObject type installed // so that Object type can be installed using JObject's spec (to get its base) PyType_Def PY_TYPE_DEF(JObject) = {}; PyTypeObject *PY_TYPE(JObject) = &JObject_type; static void t_JObject_dealloc(t_JObject *self) { self->object = JObject(NULL); self->ob_base.ob_type->tp_free((PyObject *) self); } static PyObject *t_JObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { t_JObject *self = (t_JObject *) type->tp_alloc(type, 0); self->object = JObject(NULL); return (PyObject *) self; } static PyObject *t_JObject_richcmp(t_JObject *self, PyObject *arg, int op) { int b = 0; switch (op) { case Py_EQ: case Py_NE: if (PyObject_TypeCheck(arg, PY_TYPE(JObject))) b = self->object == ((t_JObject *) arg)->object; if (op == Py_EQ) Py_RETURN_BOOL(b); Py_RETURN_BOOL(!b); case Py_LT: PyErr_SetString(PyExc_NotImplementedError, "<"); return NULL; case Py_LE: PyErr_SetString(PyExc_NotImplementedError, "<="); return NULL; case Py_GT: PyErr_SetString(PyExc_NotImplementedError, ">"); return NULL; case Py_GE: PyErr_SetString(PyExc_NotImplementedError, ">="); return NULL; } return NULL; } static PyObject *t_JObject_str(t_JObject *self) { if (self->object.this$) return env->toPyUnicode(self->object.this$); return PyUnicode_FromString(""); } static PyObject *t_JObject_repr(t_JObject *self) { PyObject *str = self->ob_base.ob_type->tp_str((PyObject *) self); if (str == NULL) return NULL; PyObject *name = PyObject_GetAttrString((PyObject *) Py_TYPE(self), "__name__"); PyObject *args = PyTuple_Pack(2, name, str); PyObject *format = PyUnicode_FromString("<%s: %s>"); PyObject *repr = PyUnicode_Format(format, args); Py_DECREF(name); Py_DECREF(str); Py_DECREF(args); Py_DECREF(format); return repr; } static int t_JObject_hash(t_JObject *self) { return env->hash(self->object.this$); } static PyObject *t_JObject__getJObject(t_JObject *self, void *data) { return PyCapsule_New((void *) self->object.this$, "jobject", NULL); } #endif /* PYTHON */ JCC-3.6/jcc3/sources/JCCEnv.h0000644000076500000000000002577413063607215015734 0ustar vajdawheel00000000000000/* * Copyright (c) 2007-2008 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JCCEnv_H #define _JCCEnv_H #include #include #if defined(_MSC_VER) || defined(__WIN32) #define _DLL_IMPORT __declspec(dllimport) #define _DLL_EXPORT __declspec(dllexport) #include #undef MAX_PRIORITY #undef MIN_PRIORITY #else #include #define _DLL_IMPORT #define _DLL_EXPORT #endif #ifdef __SUNPRO_CC #undef DEFAULT_TYPE #endif #ifdef TRUE #undef TRUE #endif #ifdef FALSE #undef FALSE #endif #include #ifdef PYTHON #include #endif #undef EOF class JCCEnv; #if defined(_MSC_VER) || defined(__WIN32) #ifdef _jcc_shared _DLL_IMPORT extern JCCEnv *env; _DLL_IMPORT extern DWORD VM_ENV; #else _DLL_EXPORT extern JCCEnv *env; _DLL_EXPORT extern DWORD VM_ENV; #endif #else extern JCCEnv *env; #endif #define _EXC_PYTHON ((int) 0) #define _EXC_JAVA ((int) 1) typedef jclass (*getclassfn)(bool); class countedRef { public: jobject global; int count; }; class _DLL_EXPORT JCCEnv { protected: jclass _sys, _obj, _thr; jclass _boo, _byt, _cha, _dou, _flo, _int, _lon, _sho; jmethodID *_mids; enum { mid_sys_identityHashCode, mid_sys_setProperty, mid_sys_getProperty, mid_obj_toString, mid_obj_hashCode, mid_obj_getClass, mid_iterator, mid_iterator_next, mid_enumeration_nextElement, mid_Boolean_booleanValue, mid_Byte_byteValue, mid_Character_charValue, mid_Double_doubleValue, mid_Float_floatValue, mid_Integer_intValue, mid_Long_longValue, mid_Short_shortValue, mid_Boolean_init, mid_Byte_init, mid_Character_init, mid_Double_init, mid_Float_init, mid_Integer_init, mid_Long_init, mid_Short_init, max_mid }; public: JavaVM *vm; std::multimap refs; int handlers; explicit JCCEnv(JavaVM *vm, JNIEnv *env); #if defined(_MSC_VER) || defined(__WIN32) inline JNIEnv *get_vm_env() const { return (JNIEnv *) TlsGetValue(VM_ENV); } #else static pthread_key_t VM_ENV; inline JNIEnv *get_vm_env() const { return (JNIEnv *) pthread_getspecific(VM_ENV); } #endif void set_vm(JavaVM *vm, JNIEnv *vm_env); void set_vm_env(JNIEnv *vm_env); int attachCurrentThread(char *name, int asDaemon); jint getJNIVersion() const; jstring getJavaVersion() const; jclass findClass(const char *className) const; jboolean isInstanceOf(jobject obj, getclassfn initializeClass) const; void registerNatives(jclass cls, JNINativeMethod *methods, int n) const; jobject iterator(jobject obj) const; jobject iteratorNext(jobject obj) const; jobject enumerationNext(jobject obj) const; jobject newGlobalRef(jobject obj, int id); jobject deleteGlobalRef(jobject obj, int id); jclass getClass(getclassfn initializeClass) const; jobject newObject(getclassfn initializeClass, jmethodID **mids, int m, ...); jobjectArray newObjectArray(jclass cls, int size); void setObjectArrayElement(jobjectArray a, int n, jobject obj) const; jobject getObjectArrayElement(jobjectArray a, int n) const; int getArrayLength(jarray a) const; void reportException() const; jobject callObjectMethod(jobject obj, jmethodID mid, ...) const; jboolean callBooleanMethod(jobject obj, jmethodID mid, ...) const; jbyte callByteMethod(jobject obj, jmethodID mid, ...) const; jchar callCharMethod(jobject obj, jmethodID mid, ...) const; jdouble callDoubleMethod(jobject obj, jmethodID mid, ...) const; jfloat callFloatMethod(jobject obj, jmethodID mid, ...) const; jint callIntMethod(jobject obj, jmethodID mid, ...) const; jlong callLongMethod(jobject obj, jmethodID mid, ...) const; jshort callShortMethod(jobject obj, jmethodID mid, ...) const; void callVoidMethod(jobject obj, jmethodID mid, ...) const; jobject callNonvirtualObjectMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jboolean callNonvirtualBooleanMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jbyte callNonvirtualByteMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jchar callNonvirtualCharMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jdouble callNonvirtualDoubleMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jfloat callNonvirtualFloatMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jint callNonvirtualIntMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jlong callNonvirtualLongMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jshort callNonvirtualShortMethod(jobject obj, jclass cls, jmethodID mid, ...) const; void callNonvirtualVoidMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jobject callStaticObjectMethod(jclass cls, jmethodID mid, ...) const; jboolean callStaticBooleanMethod(jclass cls, jmethodID mid, ...) const; jbyte callStaticByteMethod(jclass cls, jmethodID mid, ...) const; jchar callStaticCharMethod(jclass cls, jmethodID mid, ...) const; jdouble callStaticDoubleMethod(jclass cls, jmethodID mid, ...) const; jfloat callStaticFloatMethod(jclass cls, jmethodID mid, ...) const; jint callStaticIntMethod(jclass cls, jmethodID mid, ...) const; jlong callStaticLongMethod(jclass cls, jmethodID mid, ...) const; jshort callStaticShortMethod(jclass cls, jmethodID mid, ...) const; void callStaticVoidMethod(jclass cls, jmethodID mid, ...) const; jboolean booleanValue(jobject obj) const; jbyte byteValue(jobject obj) const; jchar charValue(jobject obj) const; jdouble doubleValue(jobject obj) const; jfloat floatValue(jobject obj) const; jint intValue(jobject obj) const; jlong longValue(jobject obj) const; jshort shortValue(jobject obj) const; jobject boxBoolean(jboolean value) const; jobject boxByte(jbyte value) const; jobject boxChar(jchar value) const; jobject boxDouble(jdouble value) const; jobject boxFloat(jfloat value) const; jobject boxInteger(jint value) const; jobject boxLong(jlong value) const; jobject boxShort(jshort value) const; jmethodID getMethodID(jclass cls, const char *name, const char *signature) const; jfieldID getFieldID(jclass cls, const char *name, const char *signature) const; jmethodID getStaticMethodID(jclass cls, const char *name, const char *signature) const; jobject getStaticObjectField(jclass cls, const char *name, const char *signature) const; jboolean getStaticBooleanField(jclass cls, const char *name) const; jbyte getStaticByteField(jclass cls, const char *name) const; jchar getStaticCharField(jclass cls, const char *name) const; jdouble getStaticDoubleField(jclass cls, const char *name) const; jfloat getStaticFloatField(jclass cls, const char *name) const; jint getStaticIntField(jclass cls, const char *name) const; jlong getStaticLongField(jclass cls, const char *name) const; jshort getStaticShortField(jclass cls, const char *name) const; jobject getObjectField(jobject obj, jfieldID id) const; jboolean getBooleanField(jobject obj, jfieldID id) const; jbyte getByteField(jobject obj, jfieldID id) const; jchar getCharField(jobject obj, jfieldID id) const; jdouble getDoubleField(jobject obj, jfieldID id) const; jfloat getFloatField(jobject obj, jfieldID id) const; jint getIntField(jobject obj, jfieldID id) const; jlong getLongField(jobject obj, jfieldID id) const; jshort getShortField(jobject obj, jfieldID id) const; void setObjectField(jobject obj, jfieldID id, jobject value) const; void setBooleanField(jobject obj, jfieldID id, jboolean value) const; void setByteField(jobject obj, jfieldID id, jbyte value) const; void setCharField(jobject obj, jfieldID id, jchar value) const; void setDoubleField(jobject obj, jfieldID id, jdouble value) const; void setFloatField(jobject obj, jfieldID id, jfloat value) const; void setIntField(jobject obj, jfieldID id, jint value) const; void setLongField(jobject obj, jfieldID id, jlong value) const; void setShortField(jobject obj, jfieldID id, jshort value) const; int id(jobject obj) const { return obj ? get_vm_env()->CallStaticIntMethod(_sys, _mids[mid_sys_identityHashCode], obj) : 0; } int hash(jobject obj) const { return obj ? get_vm_env()->CallIntMethod(obj, _mids[mid_obj_hashCode]) : 0; } void setClassPath(const char *classPath); char *getClassPath(); jstring fromUTF32(const uint32_t *chars, jsize len) const; #ifdef PYTHON jclass getPythonExceptionClass() const; bool restorePythonException(jthrowable throwable) const; jstring fromPyString(PyObject *object) const; PyObject *fromJString(jstring js, int delete_local_ref) const; PyObject *toPyUnicode(jobject obj) const; PyObject *getClassName(jobject obj) const; void finalizeObject(JNIEnv *jenv, PyObject *obj); #endif inline int isSame(jobject o1, jobject o2) const { return o1 == o2 || get_vm_env()->IsSameObject(o1, o2); } }; #ifdef PYTHON class PythonGIL { private: PyGILState_STATE state; public: PythonGIL() { state = PyGILState_Ensure(); } PythonGIL(JNIEnv *vm_env) { state = PyGILState_Ensure(); env->set_vm_env(vm_env); } ~PythonGIL() { PyGILState_Release(state); } }; class PythonThreadState { private: PyThreadState *state; int handler; public: PythonThreadState(int handler=0) { state = PyEval_SaveThread(); this->handler = handler; env->handlers += handler; } ~PythonThreadState() { PyEval_RestoreThread(state); env->handlers -= handler; } }; #endif #endif /* _JCCEnv_H */ JCC-3.6/jcc3/sources/macros.h0000644000076500000000000002002713131242207016122 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _macros_H #define _macros_H #define OBJ_CALL(action) \ { \ try { \ PythonThreadState state(1); \ action; \ } catch (int e) { \ switch (e) { \ case _EXC_PYTHON: \ return NULL; \ case _EXC_JAVA: \ return PyErr_SetJavaError(); \ default: \ throw; \ } \ } \ } #define INT_CALL(action) \ { \ try { \ PythonThreadState state(1); \ action; \ } catch (int e) { \ switch (e) { \ case _EXC_PYTHON: \ return -1; \ case _EXC_JAVA: \ PyErr_SetJavaError(); \ return -1; \ default: \ throw; \ } \ } \ } #define DECLARE_METHOD(type, name, flags) \ { #name, (PyCFunction) type##_##name, flags, "" } #define DECLARE_GET_FIELD(type, name) \ { #name, (getter) type##_get__##name, NULL, "", NULL } #define DECLARE_SET_FIELD(type, name) \ { #name, NULL, (setter) type##_set__##name, "", NULL } #define DECLARE_GETSET_FIELD(type, name) \ { #name, (getter) type##_get__##name, (setter) type##_set__##name, "", NULL } struct PyType_Def { PyType_Spec spec; PyTypeObject *type; PyType_Def **bases; // NULL terminated array }; #define PY_TYPE(name) name##$$Type #define PY_TYPE_DEF(name) name##$$TypeDef #define PY_TYPE_BASES(name) name##$$TypeBases #define PY_TYPE_SLOTS(name) name##$$TypeSlots #define DEFINE_TYPE(name, t_name, javaClass) \ PyType_Def PY_TYPE_DEF(name) = { \ { \ #name, \ sizeof(t_name), \ 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, \ PY_TYPE_SLOTS(name) \ }, \ NULL, \ PY_TYPE_BASES(name), \ }; \ PyTypeObject *PY_TYPE(name) = NULL; \ PyObject *t_name::wrap_Object(const javaClass& object) \ { \ if (!!object) \ { \ t_name *self = (t_name *) \ PyType_GenericAlloc(PY_TYPE(name), 0); \ if (self) \ self->object = object; \ return (PyObject *) self; \ } \ Py_RETURN_NONE; \ } \ PyObject *t_name::wrap_jobject(const jobject& object) \ { \ if (!!object) \ { \ if (!env->isInstanceOf(object, javaClass::initializeClass)) \ { \ PyErr_SetObject(PyExc_TypeError, \ (PyObject *) PY_TYPE(name)); \ return NULL; \ } \ t_name *self = (t_name *) \ PyType_GenericAlloc(PY_TYPE(name), 0); \ if (self) \ self->object = javaClass(object); \ return (PyObject *) self; \ } \ Py_RETURN_NONE; \ } \ #define DECLARE_TYPE(name) \ extern PyType_Def PY_TYPE_DEF(name); \ extern PyTypeObject *PY_TYPE(name) #define INSTALL_TYPE(name, module) \ installType(&PY_TYPE(name), &PY_TYPE_DEF(name), module, #name, 0) #define INSTALL_STATIC_TYPE(name, module) \ if (PyType_Ready(PY_TYPE(name)) == 0) \ { \ Py_INCREF(PY_TYPE(name)); \ PyModule_AddObject(module, #name, (PyObject *) PY_TYPE(name)); \ } #define Py_RETURN_BOOL(b) \ { \ if (b) \ Py_RETURN_TRUE; \ else \ Py_RETURN_FALSE; \ } #define Py_RETURN_SELF \ { \ Py_INCREF(self); \ return (PyObject *) self; \ } #endif /* _macros_H */ JCC-3.6/jcc3/sources/JArray.h0000644000076500000000000013653713360761054016056 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JArray_H #define _JArray_H #ifdef PYTHON #include #include "macros.h" extern jobjectArray fromPySequence(jclass cls, PyObject *sequence); extern jobjectArray fromPySequence(jclass cls, PyObject **args, int length); extern PyObject *PyErr_SetJavaError(); extern PyTypeObject *PY_TYPE(JArrayObject); extern PyTypeObject *PY_TYPE(JArrayString); extern PyTypeObject *PY_TYPE(JArrayBool); extern PyTypeObject *PY_TYPE(JArrayByte); extern PyTypeObject *PY_TYPE(JArrayChar); extern PyTypeObject *PY_TYPE(JArrayDouble); extern PyTypeObject *PY_TYPE(JArrayFloat); extern PyTypeObject *PY_TYPE(JArrayInt); extern PyTypeObject *PY_TYPE(JArrayLong); extern PyTypeObject *PY_TYPE(JArrayShort); #else typedef int Py_ssize_t; #endif /* PYTHON */ #include "JCCEnv.h" #include "java/lang/Object.h" template class JArray : public java::lang::Object { public: Py_ssize_t length; explicit JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(fromPySequence(env->getClass(T::initializeClass), sequence)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(jclass cls, PyObject *sequence) : java::lang::Object(fromPySequence(cls, sequence)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(jclass cls, PyObject **args, int length) : java::lang::Object(fromPySequence(cls, args, length)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } PyObject *toSequence(PyObject *(*wrapfn)(const T&)) { if (this$ == NULL) Py_RETURN_NONE; PyObject *list = PyList_New(length); for (Py_ssize_t i = 0; i < length; i++) PyList_SET_ITEM(list, i, (*wrapfn)((*this)[i])); return list; } PyObject *get(Py_ssize_t n, PyObject *(*wrapfn)(const T&)) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return (*wrapfn)((*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } #endif T operator[](Py_ssize_t n) { return T(env->getObjectArrayElement((jobjectArray) this$, n)); } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; JArray(jclass cls, Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewObjectArray(n, cls, NULL)) { length = env->getArrayLength((jobjectArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } #ifdef PYTHON JArray(jclass cls, PyObject *sequence) : java::lang::Object(fromPySequence(cls, sequence)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(jclass cls, PyObject **args, int length) : java::lang::Object(fromPySequence(cls, args, length)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } PyObject *toSequence(PyObject *(*wrapfn)(const jobject&)) { return toSequence(0, length, wrapfn); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi, PyObject *(*wrapfn)(const jobject&)) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); if (!wrapfn) wrapfn = java::lang::t_Object::wrap_jobject; for (Py_ssize_t i = lo; i < hi; i++) { jobject jobj = env->getObjectArrayElement((jobjectArray) this$, i); PyObject *obj = (*wrapfn)(jobj); PyList_SET_ITEM(list, i - lo, obj); } return list; } PyObject *get(Py_ssize_t n, PyObject *(*wrapfn)(const jobject&)) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!wrapfn) wrapfn = java::lang::t_Object::wrap_jobject; jobject jobj = env->getObjectArrayElement((jobjectArray) this$, n); return (*wrapfn)(jobj); } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jobject jobj; if (PyBytes_Check(obj) || PyUnicode_Check(obj)) jobj = env->fromPyString(obj); else if (!PyObject_TypeCheck(obj, PY_TYPE(JObject))) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } else jobj = ((t_JObject *) obj)->object.this$; try { env->setObjectArrayElement((jobjectArray) this$, n, jobj); } catch (int e) { switch (e) { case _EXC_JAVA: PyErr_SetJavaError(); return -1; default: throw; } } return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap(PyObject *(*wrapfn)(const jobject&)) const; #endif jobject operator[](Py_ssize_t n) { return (jobject) env->getObjectArrayElement((jobjectArray) this$, n); } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewObjectArray(n, env->findClass("java/lang/String"), NULL)) { length = env->getArrayLength((jobjectArray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewObjectArray(PySequence_Length(sequence), env->findClass("java/lang/String"), NULL)) { length = env->getArrayLength((jobjectArray) this$); for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (obj == NULL) break; jstring str = env->fromPyString(obj); Py_DECREF(obj); if (PyErr_Occurred()) break; env->setObjectArrayElement((jobjectArray) this$, i, str); env->get_vm_env()->DeleteLocalRef(str); } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); for (Py_ssize_t i = lo; i < hi; i++) { jstring str = (jstring) env->getObjectArrayElement((jobjectArray) this$, i); PyObject *obj = env->fromJString(str, 1); PyList_SET_ITEM(list, i - lo, obj); } return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jstring str = (jstring) env->getObjectArrayElement((jobjectArray) this$, n); PyObject *obj = env->fromJString(str, 1); return obj; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jstring str = env->fromPyString(obj); if (PyErr_Occurred()) return -1; env->setObjectArrayElement((jobjectArray) this$, n, str); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jstring operator[](Py_ssize_t n) { return (jstring) env->getObjectArrayElement((jobjectArray) this$, n); } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jbooleanArray array; jboolean *elts; public: arrayElements(jbooleanArray array) { this->array = array; elts = env->get_vm_env()->GetBooleanArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseBooleanArrayElements(array, elts, 0); } operator jboolean *() { return elts; } }; arrayElements elements() { return arrayElements((jbooleanArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewBooleanArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewBooleanArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jboolean *buf = (jboolean *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (obj == Py_True || obj == Py_False) { buf[i] = (jboolean) (obj == Py_True); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewBooleanArray(length)) { arrayElements elts = elements(); jboolean *buf = (jboolean *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (obj == Py_True || obj == Py_False) buf[i] = (jboolean) (obj == Py_True); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jboolean *buf = (jboolean *) elts; for (Py_ssize_t i = lo; i < hi; i++) { jboolean value = buf[i]; PyObject *obj = value ? Py_True : Py_False; Py_INCREF(obj); PyList_SET_ITEM(list, i - lo, obj); } return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) Py_RETURN_BOOL(elements()[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { elements()[n] = (jboolean) PyObject_IsTrue(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jboolean operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jboolean *elts = (jboolean *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jboolean value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jbyteArray array; jbyte *elts; public: arrayElements(jbyteArray array) { this->array = array; elts = env->get_vm_env()->GetByteArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseByteArrayElements(array, elts, 0); } operator jbyte *() { return elts; } }; arrayElements elements() { return arrayElements((jbyteArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewByteArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewByteArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; if (PyBytes_Check(sequence)) memcpy(buf, PyBytes_AS_STRING(sequence), length); else for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyBytes_Check(obj) && (PyBytes_GET_SIZE(obj) == 1)) { buf[i] = (jbyte) PyBytes_AS_STRING(obj)[0]; Py_DECREF(obj); } else if (PyLong_CheckExact(obj)) { buf[i] = (jbyte) PyLong_AS_LONG(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewByteArray(length)) { arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyBytes_Check(obj) && (PyBytes_GET_SIZE(obj) == 1)) buf[i] = (jbyte) PyBytes_AS_STRING(obj)[0]; else if (PyLong_CheckExact(obj)) buf[i] = (jbyte) PyLong_AS_LONG(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } char getType() { return 'Z'; } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; PyObject *tuple = PyTuple_New(hi - lo); for (Py_ssize_t i = 0; i < hi - lo; i++) PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(buf[lo + i])); return tuple; } PyObject *to_bytes_() { if (this$ == NULL) Py_RETURN_NONE; arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; return PyBytes_FromStringAndSize((char *) buf, length); } PyObject *to_string_() { if (this$ == NULL) Py_RETURN_NONE; arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; return PyUnicode_FromStringAndSize((char *) buf, length); } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jbyte b = (*this)[n]; return PyLong_FromLong(b); } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyLong_CheckExact(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jbyte) PyLong_AS_LONG(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jbyte operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jbyte *elts = (jbyte *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jbyte value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jcharArray array; jchar *elts; public: arrayElements(jcharArray array) { this->array = array; elts = env->get_vm_env()->GetCharArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseCharArrayElements(array, elts, 0); } operator jchar *() { return elts; } }; arrayElements elements() { return arrayElements((jcharArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewCharArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewCharArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jchar *buf = (jchar *) elts; if (PyUnicode_Check(sequence)) { if (sizeof(Py_UNICODE) == sizeof(jchar)) memcpy(buf, PyUnicode_AS_UNICODE(sequence), length * sizeof(jchar)); else { Py_UNICODE *pchars = PyUnicode_AS_UNICODE(sequence); for (Py_ssize_t i = 0; i < length; i++) buf[i] = (jchar) pchars[i]; } } else for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyUnicode_Check(obj) && (PyUnicode_GET_LENGTH(obj) == 1)) { buf[i] = (jchar) PyUnicode_AS_UNICODE(obj)[0]; Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewCharArray(length)) { arrayElements elts = elements(); jchar *buf = (jchar *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyUnicode_Check(obj) && (PyUnicode_GET_LENGTH(obj) == 1)) buf[i] = (jchar) PyUnicode_AS_UNICODE(obj)[0]; else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; arrayElements elts = elements(); jchar *buf = (jchar *) elts; if (sizeof(Py_UNICODE) == sizeof(jchar)) return PyUnicode_FromUnicode((const Py_UNICODE *) buf + lo, hi - lo); else { PyObject *string = PyUnicode_FromUnicode(NULL, hi - lo); Py_UNICODE *pchars = PyUnicode_AS_UNICODE(string); for (Py_ssize_t i = lo; i < hi; i++) pchars[i - lo] = (Py_UNICODE) buf[i]; return string; } } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jchar c = (*this)[n]; if (sizeof(Py_UNICODE) == sizeof(jchar)) return PyUnicode_FromUnicode((const Py_UNICODE *) &c, 1); else { PyObject *string = PyUnicode_FromUnicode(NULL, 1); Py_UNICODE *pchars = PyUnicode_AS_UNICODE(string); pchars[0] = (Py_UNICODE) c; return string; } } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyUnicode_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } if (PyUnicode_GET_LENGTH(obj) != 1) { PyErr_SetObject(PyExc_ValueError, obj); return -1; } elements()[n] = (jchar) PyUnicode_AS_UNICODE(obj)[0]; return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jchar operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jchar *elts = (jchar *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jchar value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jdoubleArray array; jdouble *elts; public: arrayElements(jdoubleArray array) { this->array = array; elts = env->get_vm_env()->GetDoubleArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseDoubleArrayElements(array, elts, 0); } operator jdouble *() { return elts; } }; arrayElements elements() { return arrayElements((jdoubleArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewDoubleArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewDoubleArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jdouble *buf = (jdouble *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyFloat_Check(obj)) { buf[i] = (jdouble) PyFloat_AS_DOUBLE(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewDoubleArray(length)) { arrayElements elts = elements(); jdouble *buf = (jdouble *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyFloat_Check(obj)) buf[i] = (jdouble) PyFloat_AS_DOUBLE(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jdouble *buf = (jdouble *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyFloat_FromDouble((double) buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyFloat_FromDouble((double) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyFloat_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jdouble) PyFloat_AS_DOUBLE(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jdouble operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jdouble *elts = (jdouble *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jdouble value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jfloatArray array; jfloat *elts; public: arrayElements(jfloatArray array) { this->array = array; elts = env->get_vm_env()->GetFloatArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseFloatArrayElements(array, elts, 0); } operator jfloat *() { return elts; } }; arrayElements elements() { return arrayElements((jfloatArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewFloatArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewFloatArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jfloat *buf = (jfloat *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyFloat_Check(obj)) { buf[i] = (jfloat) PyFloat_AS_DOUBLE(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewFloatArray(length)) { arrayElements elts = elements(); jfloat *buf = (jfloat *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyFloat_Check(obj)) buf[i] = (jfloat) PyFloat_AS_DOUBLE(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jfloat *buf = (jfloat *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyFloat_FromDouble((double) buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyFloat_FromDouble((double) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyFloat_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jfloat) PyFloat_AS_DOUBLE(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jfloat operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jfloat *elts = (jfloat *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jfloat value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jintArray array; jint *elts; public: arrayElements(jintArray array) { this->array = array; elts = env->get_vm_env()->GetIntArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseIntArrayElements(array, elts, 0); } operator jint *() { return elts; } }; arrayElements elements() { return arrayElements((jintArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewIntArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewIntArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jint *buf = (jint *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyLong_Check(obj)) { buf[i] = (jint) PyLong_AS_LONG(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewIntArray(length)) { arrayElements elts = elements(); jint *buf = (jint *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyLong_Check(obj)) buf[i] = (jint) PyLong_AS_LONG(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jint *buf = (jint *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyLong_FromLong(buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyLong_FromLong((*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyLong_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jint) PyLong_AS_LONG(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jint operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jint *elts = (jint *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jint value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jlongArray array; jlong *elts; public: arrayElements(jlongArray array) { this->array = array; elts = env->get_vm_env()->GetLongArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseLongArrayElements(array, elts, 0); } operator jlong *() { return elts; } }; arrayElements elements() { return arrayElements((jlongArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewLongArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewLongArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jlong *buf = (jlong *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyLong_Check(obj)) { buf[i] = (jlong) PyLong_AsLongLong(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewLongArray(length)) { arrayElements elts = elements(); jlong *buf = (jlong *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyLong_Check(obj)) buf[i] = (jlong) PyLong_AsLongLong(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jlong *buf = (jlong *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyLong_FromLongLong((long long) buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyLong_FromLongLong((long long) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyLong_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jlong) PyLong_AsLongLong(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jlong operator[](long n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jlong *elts = (jlong *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jlong value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jshortArray array; jshort *elts; public: arrayElements(jshortArray array) { this->array = array; elts = env->get_vm_env()->GetShortArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseShortArrayElements(array, elts, 0); } operator jshort *() { return elts; } }; arrayElements elements() { return arrayElements((jshortArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewShortArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewShortArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jshort *buf = (jshort *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyLong_Check(obj)) { buf[i] = (jshort) PyLong_AS_LONG(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewShortArray(length)) { arrayElements elts = elements(); jshort *buf = (jshort *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyLong_Check(obj)) buf[i] = (jshort) PyLong_AS_LONG(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jshort *buf = (jshort *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyLong_FromLong(buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyLong_FromLong((long) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyLong_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jshort) PyLong_AS_LONG(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jshort operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jshort *elts = (jshort *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jshort value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; #ifdef PYTHON template class t_JArray { public: PyObject_HEAD JArray array; }; template class t_JArrayWrapper { public: static PyObject *wrap_Object(const JArray &array) { if (!!array) return array.wrap(U::wrap_jobject); Py_RETURN_NONE; } static PyObject *wrap_jobject(const jobject &array) { if (!!array) return JArray(array).wrap(U::wrap_jobject); Py_RETURN_NONE; } }; template class t_JArrayWrapper { public: static PyObject *wrap_Object(const JArray &array) { if (!!array) return array.wrap(); Py_RETURN_NONE; } static PyObject *wrap_jobject(const jobject &array) { if (!!array) return JArray(array).wrap(); Py_RETURN_NONE; } }; #endif #endif /* _JArray_H */ JCC-3.6/jcc3/sources/functions.h0000644000076500000000000002204513121702414016650 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _functions_h #define _functions_h #include "java/util/Iterator.h" #include "java/util/Enumeration.h" #include "java/lang/String.h" #include "java/lang/Object.h" #include "macros.h" typedef PyTypeObject **(*getparametersfn)(void *); typedef int (*boxfn)(PyTypeObject *, PyObject *, java::lang::Object *); PyObject *PyErr_SetArgsError(char *name, PyObject *args); PyObject *PyErr_SetArgsError(PyObject *self, char *name, PyObject *args); PyObject *PyErr_SetArgsError(PyTypeObject *type, char *name, PyObject *args); PyObject *PyErr_SetJavaError(); extern PyObject *PyExc_JavaError; extern PyObject *PyExc_InvalidArgsError; void throwPythonError(void); void throwTypeError(const char *name, PyObject *object); #if defined(_MSC_VER) || defined(__SUNPRO_CC) #define parseArgs __parseArgs #define parseArg __parseArg int __parseArgs(PyObject *args, char *types, ...); int __parseArg(PyObject *arg, char *types, ...); int _parseArgs(PyObject **args, unsigned int count, char *types, va_list list, va_list check); #else #define parseArgs(args, types, rest...) \ _parseArgs(((PyTupleObject *)(args))->ob_item, \ ((PyTupleObject *)(args))->ob_base.ob_size, types, ##rest) #define parseArg(arg, types, rest...) \ _parseArgs(&(arg), 1, types, ##rest) int _parseArgs(PyObject **args, unsigned int count, char *types, ...); #endif int abstract_init(PyObject *self, PyObject *args, PyObject *kwds); PyObject *wrapType(PyTypeObject *type, const jobject& obj); PyObject *unboxBoolean(const jobject& obj); PyObject *unboxByte(const jobject& obj); PyObject *unboxCharacter(const jobject& obj); PyObject *unboxDouble(const jobject& obj); PyObject *unboxFloat(const jobject& obj); PyObject *unboxInteger(const jobject& obj); PyObject *unboxLong(const jobject& obj); PyObject *unboxShort(const jobject& obj); PyObject *unboxString(const jobject& obj); int boxBoolean(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxByte(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxCharacter(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxCharSequence(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxDouble(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxFloat(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxInteger(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxLong(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxNumber(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxShort(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxString(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxObject(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); java::lang::String p2j(PyObject *object); PyObject *j2p(const java::lang::String& js); PyObject *c2p(jchar c); PyObject *make_descriptor(PyType_Def *value); PyObject *make_descriptor(getclassfn initializeClass); PyObject *make_descriptor(getclassfn initializeClass, int generics); PyObject *make_descriptor(PyObject *value); PyObject *make_descriptor(PyObject *(*wrapfn)(const jobject &)); PyObject *make_descriptor(boxfn fn); PyObject *make_descriptor(jboolean value); PyObject *make_descriptor(jbyte value); PyObject *make_descriptor(jchar value); PyObject *make_descriptor(jdouble value); PyObject *make_descriptor(jfloat value); PyObject *make_descriptor(jint value); PyObject *make_descriptor(jlong value); PyObject *make_descriptor(jshort value); jobjectArray make_array(jclass cls, PyObject *sequence); PyObject *callSuper(PyTypeObject *type, const char *name, PyObject *args, int cardinality); PyObject *callSuper(PyTypeObject *type, PyObject *self, const char *name, PyObject *args, int cardinality); template PyObject *get_iterator(T *self) { jobject iterator; OBJ_CALL(iterator = env->iterator(self->object.this$)); return java::util::t_Iterator::wrap_jobject(iterator); } #ifdef _java_generics template PyObject *get_generic_iterator(T *self) { PyTypeObject *param = self->parameters[0]; jobject iterator; OBJ_CALL(iterator = env->iterator(self->object.this$)); return java::util::t_Iterator::wrap_jobject(iterator, param); } #endif template PyObject *get_iterator_next(T *self) { jboolean hasNext; OBJ_CALL(hasNext = self->object.hasNext()); if (!hasNext) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->iteratorNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); return U::wrap_jobject(next); } #ifdef _java_generics template PyObject *get_generic_iterator_next(T *self) { jboolean hasNext; OBJ_CALL(hasNext = self->object.hasNext()); if (!hasNext) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->iteratorNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); PyTypeObject *param = self->parameters[0]; if (param != NULL) return wrapType(param, next); return U::wrap_jobject(next); } #endif template PyObject *get_enumeration_next(T *self) { jboolean hasMoreElements; OBJ_CALL(hasMoreElements = self->object.hasMoreElements()); if (!hasMoreElements) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->enumerationNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); return U::wrap_jobject(next); } #ifdef _java_generics template PyObject *get_generic_enumeration_next(T *self) { jboolean hasMoreElements; OBJ_CALL(hasMoreElements = self->object.hasMoreElements()); if (!hasMoreElements) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->enumerationNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); PyTypeObject *param = self->parameters[0]; if (param != NULL) return wrapType(param, next); return U::wrap_jobject(next); } #endif template PyObject *get_next(T *self) { V next((jobject) NULL); OBJ_CALL(next = self->object.next()); if (!next) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next.this$, cls)) return env->fromJString((jstring) next.this$, 0); return U::wrap_Object(next); } #ifdef _java_generics template PyObject *get_generic_next(T *self) { V next((jobject) NULL); OBJ_CALL(next = self->object.next()); if (!next) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next.this$, cls)) return env->fromJString((jstring) next.this$, 0); PyTypeObject *param = self->parameters[0]; if (param != NULL) return wrapType(param, next.this$); return U::wrap_Object(next); } #endif PyObject *get_extension_iterator(PyObject *self); PyObject *get_extension_next(PyObject *self); PyObject *get_extension_nextElement(PyObject *self); jobjectArray fromPySequence(jclass cls, PyObject *sequence); jobjectArray fromPySequence(jclass cls, PyObject **args, int length); PyObject *castCheck(PyObject *obj, getclassfn initializeClass, int reportError); PyTypeObject *makeType(PyType_Def *def); void installType(PyTypeObject **type, PyType_Def *spec, PyObject *module, char *name, int isExtension); #ifdef _java_generics PyObject *typeParameters(PyTypeObject *types[], size_t size); #endif extern PyTypeObject *PY_TYPE(FinalizerClass); extern PyTypeObject *PY_TYPE(FinalizerProxy); typedef struct { PyObject_HEAD PyObject *object; } t_fp; #endif /* _functions_h */ JCC-3.6/jcc3/sources/functions.cpp0000644000076500000000000017543313502045511017216 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #ifdef _MSC_VER #include #else #include #endif #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "java/lang/Throwable.h" #include "java/lang/Boolean.h" #include "java/lang/Byte.h" #include "java/lang/Character.h" #include "java/lang/Double.h" #include "java/lang/Float.h" #include "java/lang/Integer.h" #include "java/lang/Long.h" #include "java/lang/Short.h" #include "java/util/Iterator.h" #include "JArray.h" #include "functions.h" #include "macros.h" using namespace java::lang; using namespace java::util; PyObject *PyExc_JavaError = PyExc_ValueError; PyObject *PyExc_InvalidArgsError = PyExc_ValueError; PyObject *_set_exception_types(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "OO", &PyExc_JavaError, &PyExc_InvalidArgsError)) return NULL; Py_RETURN_NONE; } PyObject *_set_function_self(PyObject *self, PyObject *args) { PyObject *object, *module; if (!PyArg_ParseTuple(args, "OO", &object, &module)) return NULL; if (!PyCFunction_Check(object)) { PyErr_SetObject(PyExc_TypeError, object); return NULL; } PyCFunctionObject *cfn = (PyCFunctionObject *) object; Py_INCREF(module); Py_XDECREF(cfn->m_self); cfn->m_self = module; Py_RETURN_NONE; } PyObject *findClass(PyObject *self, PyObject *args) { char *className; if (!PyArg_ParseTuple(args, "s", &className)) return NULL; try { jclass cls = env->findClass(className); if (cls) return t_Class::wrap_Object(Class(cls)); } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: return PyErr_SetJavaError(); default: throw; } } Py_RETURN_NONE; } static const char interface_bytes[] = { '\xca', '\xfe', '\xba', '\xbe', // magic number: 0xcafebabe '\x00', '\x00', '\x00', '\x32', // version 50.0 '\x00', '\x07', // constant pool max index: 6 '\x07', '\x00', '\x04', // 1: class name at 4 '\x07', '\x00', '\x05', // 2: class name at 5 '\x07', '\x00', '\x06', // 3: class name at 6 '\x01', '\x00', '\x00', // 4: empty string '\x01', '\x00', '\x10', // 5: 16-byte string: java/lang/Object 'j', 'a', 'v', 'a', '/', 'l', 'a', 'n', 'g', '/', 'O', 'b', 'j', 'e', 'c', 't', '\x01', '\x00', '\x00', // 6: empty string '\x06', '\x01', // public abstract interface '\x00', '\x01', // this class at 1 '\x00', '\x02', // superclass at 2 '\x00', '\x01', // 1 interface '\x00', '\x03', // interface at 3 '\x00', '\x00', // 0 fields '\x00', '\x00', // 0 methods '\x00', '\x00' // 0 attributes }; /* make an empty interface that extends an interface */ PyObject *makeInterface(PyObject *self, PyObject *args) { char *name, *extName; int name_len, extName_len; if (!PyArg_ParseTuple(args, "s#s#", &name, &name_len, &extName, &extName_len)) return NULL; JNIEnv *vm_env = env->get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); const int bytes_len = sizeof(interface_bytes); const int len = bytes_len + name_len + extName_len; char *buf = (char *) malloc(len); if (buf == NULL) return PyErr_NoMemory(); int name_pos = 22; int extName_pos = 44; jclass cls; memcpy(buf, interface_bytes, name_pos); memcpy(buf + name_pos + name_len, interface_bytes + name_pos, extName_pos - name_pos); memcpy(buf + extName_pos + name_len + extName_len, interface_bytes + extName_pos, bytes_len - extName_pos); extName_pos += name_len; *((unsigned short *) (buf + name_pos - 2)) = htons(name_len); memcpy(buf + name_pos, name, name_len); *((unsigned short *) (buf + extName_pos - 2)) = htons(extName_len); memcpy(buf + extName_pos, extName, extName_len); cls = vm_env->DefineClass(name, classLoader, (const jbyte *) buf, len); free(buf); if (cls) return t_Class::wrap_Object(Class(cls)); return PyErr_SetJavaError(); } static const char class_bytes[] = { '\xca', '\xfe', '\xba', '\xbe', // magic number: 0xcafebabe '\x00', '\x00', '\x00', '\x32', // version 50.0 '\x00', '\x0c', // constant pool max index: 11 '\x0a', '\x00', '\x03', '\x00', '\x08', // 1: method for class 3 at 8 '\x07', '\x00', '\x09', // 2: class name at 9 '\x07', '\x00', '\x0a', // 3: class name at 10 '\x07', '\x00', '\x0b', // 4: class name at 11 '\x01', '\x00', '\x06', // 5: 6-byte string: '<', 'i', 'n', 'i', 't', '>', '\x01', '\x00', '\x03', '(', ')', 'V', // 6: 3-byte string: ()V '\x01', '\x00', '\x04', // 7: 4-byte string: Code 'C', 'o', 'd', 'e', '\x0c', '\x00', '\x05', '\x00', '\x06', // 8: name at 5, signature at 6 '\x01', '\x00', '\x00', // 9: empty string '\x01', '\x00', '\x00', // 10: empty string '\x01', '\x00', '\x00', // 11: empty string '\x00', '\x21', // super public '\x00', '\x02', // this class at 2 '\x00', '\x03', // superclass at 3 '\x00', '\x01', // 1 interface '\x00', '\x04', // interface at 4 '\x00', '\x00', // 0 fields '\x00', '\x01', // 1 method '\x00', '\x01', '\x00', '\x05', // public, name at 5 '\x00', '\x06', '\x00', '\x01', // signature at 6, 1 attribute '\x00', '\x07', // attribute name at 7: Code '\x00', '\x00', '\x00', '\x11', // 17 bytes past 6 attribute bytes '\x00', '\x01', // max stack: 1 '\x00', '\x01', // max locals: 1 '\x00', '\x00', '\x00', '\x05', // code length: 5 '\x2a', '\xb7', '\x00', '\x01', '\xb1', // actual code bytes '\x00', '\x00', // 0 method exceptions '\x00', '\x00', // 0 method attributes '\x00', '\x00', // 0 attributes }; /* make an empty class that extends a class and implements an interface */ PyObject *makeClass(PyObject *self, PyObject *args) { char *name, *extName, *implName; int name_len, extName_len, implName_len; if (!PyArg_ParseTuple(args, "s#s#s#", &name, &name_len, &extName, &extName_len, &implName, &implName_len)) return NULL; JNIEnv *vm_env = env->get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); const int bytes_len = sizeof(class_bytes); const int len = bytes_len + name_len + extName_len + implName_len; char *buf = (char *) malloc(len); if (buf == NULL) return PyErr_NoMemory(); int name_pos = 54; int extName_pos = 57; int implName_pos = 60; jclass cls; memcpy(buf, class_bytes, name_pos); memcpy(buf + name_pos + name_len, class_bytes + name_pos, extName_pos - name_pos); memcpy(buf + extName_pos + name_len + extName_len, class_bytes + extName_pos, bytes_len - extName_pos); memcpy(buf + implName_pos + name_len + extName_len + implName_len, class_bytes + implName_pos, bytes_len - implName_pos); extName_pos += name_len; implName_pos += name_len + extName_len; *((unsigned short *) (buf + name_pos - 2)) = htons(name_len); memcpy(buf + name_pos, name, name_len); *((unsigned short *) (buf + extName_pos - 2)) = htons(extName_len); memcpy(buf + extName_pos, extName, extName_len); *((unsigned short *) (buf + implName_pos - 2)) = htons(implName_len); memcpy(buf + implName_pos, implName, implName_len); cls = vm_env->DefineClass(name, classLoader, (const jbyte *) buf, len); free(buf); if (cls) return t_Class::wrap_Object(Class(cls)); return PyErr_SetJavaError(); } static boxfn get_boxfn(PyTypeObject *type) { static PyObject *boxfn_ = PyUnicode_FromString("boxfn_"); PyObject *cobj = PyObject_GetAttr((PyObject *) type, boxfn_); boxfn fn; if (cobj == NULL) return NULL; fn = (boxfn) PyCapsule_GetPointer(cobj, "boxfn"); Py_DECREF(cobj); return fn; } static int is_instance_of(PyObject *arg, PyTypeObject *type) { static PyObject *class_ = PyUnicode_FromString("class_"); PyObject *clsObj = PyObject_GetAttr((PyObject *) type, class_); int result; if (clsObj == NULL) return -1; result = env->get_vm_env()-> IsInstanceOf(((t_Object *) arg)->object.this$, (jclass) ((t_Object *) clsObj)->object.this$); Py_DECREF(clsObj); return result; } #if defined(_MSC_VER) || defined(__SUNPRO_CC) int __parseArgs(PyObject *args, char *types, ...) { int count = Py_SIZE((PyTupleObject *) args); va_list list, check; va_start(list, types); va_start(check, types); return _parseArgs(((PyTupleObject *) args)->ob_item, count, types, list, check); } int __parseArg(PyObject *arg, char *types, ...) { va_list list, check; va_start(list, types); va_start(check, types); return _parseArgs(&arg, 1, types, list, check); } int _parseArgs(PyObject **args, unsigned int count, char *types, va_list list, va_list check) { unsigned int typeCount = strlen(types); if (count > typeCount) return -1; #else int _parseArgs(PyObject **args, unsigned int count, char *types, ...) { unsigned int typeCount = strlen(types); va_list list, check; va_start(list, types); va_start(check, types); #endif if (!env->vm) { PyErr_SetString(PyExc_RuntimeError, "initVM() must be called first"); return -1; } JNIEnv *vm_env = env->get_vm_env(); if (!vm_env) { PyErr_SetString(PyExc_RuntimeError, "attachCurrentThread() must be called first"); return -1; } bool last = false; /* true if last expected parameter */ bool varargs = false; /* true if in varargs mode */ bool empty = false; /* true if in varargs mode and no params passed */ int array = 0; /* > 0 if expecting an array, its nesting level */ unsigned int pos = 0; for (unsigned int a = 0; a < count; a++, pos++) { PyObject *arg = args[a]; char tc = types[pos]; last = last || types[pos + 1] == '\0'; if (array > 1 && tc != '[') tc = 'o'; switch (tc) { case '[': { if (++array > 1 && !PyObject_TypeCheck(arg, PY_TYPE(JArrayObject))) return -1; a -= 1; break; } case 'j': /* Java object, with class$ */ case 'k': /* Java object, with initializeClass */ case 'K': /* Java object, with initializeClass and params */ { jclass cls = NULL; switch (tc) { case 'j': cls = (jclass) va_arg(list, Class *)->this$; break; case 'k': case 'K': try { getclassfn initializeClass = va_arg(list, getclassfn); cls = env->getClass(initializeClass); } catch (int e) { switch (e) { case _EXC_PYTHON: return -1; case _EXC_JAVA: PyErr_SetJavaError(); return -1; default: throw; } } break; } if (arg == Py_None) break; /* ensure that class Class is initialized (which may not be the * case because of earlier recursion avoidance (JObject(cls)). */ if (!Class::class$) env->getClass(Class::initializeClass); if (array) { if (PyObject_TypeCheck(arg, PY_TYPE(JArrayObject))) break; if (PySequence_Check(arg) && !PyBytes_Check(arg) && !PyUnicode_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = 0; if (obj == Py_None) ok = 1; else if (PyObject_TypeCheck(obj, PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) obj)->object.this$, cls)) ok = 1; else if (PyObject_TypeCheck(obj, PY_TYPE(FinalizerProxy))) { PyObject *o = ((t_fp *) obj)->object; if (PyObject_TypeCheck(o, PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) o)->object.this$, cls)) ok = 1; } Py_DECREF(obj); if (ok) break; } else break; } if (last) { int ok = 0; if (arg == Py_None) ok = 1; else if (PyObject_TypeCheck(arg, PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) arg)->object.this$, cls)) ok = 1; else if (PyObject_TypeCheck(arg, PY_TYPE(FinalizerProxy))) { PyObject *o = ((t_fp *) arg)->object; if (PyObject_TypeCheck(o, PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) o)->object.this$, cls)) ok = 1; } if (ok) { varargs = true; break; } } } else if (PyObject_TypeCheck(arg, PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) arg)->object.this$, cls)) break; else if (PyObject_TypeCheck(arg, PY_TYPE(FinalizerProxy))) { arg = ((t_fp *) arg)->object; if (PyObject_TypeCheck(arg, PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) arg)->object.this$, cls)) break; } return -1; } case 'Z': /* boolean, strict */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayBool))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = obj == Py_True || obj == Py_False; Py_DECREF(obj); if (ok) break; } else break; } if (last && (arg == Py_True || arg == Py_False)) { varargs = true; break; } } else if (arg == Py_True || arg == Py_False) break; return -1; } case 'B': /* byte */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayByte))) break; if (last) { if (PyBytes_Check(arg) && (PyBytes_Size(arg) == 1)) { varargs = true; break; } } } else if (PyBytes_Check(arg) && (PyBytes_Size(arg) == 1)) break; return -1; } case 'C': /* char */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayChar))) break; if (last) { if ((PyBytes_Check(arg) && PyBytes_Size(arg) == 1) || (PyUnicode_Check(arg) && PyUnicode_GetLength(arg) == 1 && PyUnicode_READ_CHAR(arg, 0) < 0x10000)) { varargs = true; break; } } } else if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) break; else if (PyUnicode_Check(arg) && PyUnicode_GetLength(arg) == 1 && PyUnicode_READ_CHAR(arg, 0) < 0x10000) break; return -1; } case 'I': /* int */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayInt))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyLong_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyLong_CheckExact(arg)) { varargs = true; break; } } else if (PyLong_CheckExact(arg)) break; return -1; } case 'S': /* short */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayShort))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyLong_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyLong_CheckExact(arg)) { varargs = true; break; } } else if (PyLong_CheckExact(arg)) break; return -1; } case 'D': /* double */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayDouble))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyFloat_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyFloat_CheckExact(arg)) { varargs = true; break; } } else if (PyFloat_CheckExact(arg)) break; return -1; } case 'F': /* float */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayFloat))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyFloat_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyFloat_CheckExact(arg)) { varargs = true; break; } } else if (PyFloat_CheckExact(arg)) break; return -1; } case 'J': /* long long */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayLong))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyLong_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyLong_CheckExact(arg)) { varargs = true; break; } } else if (PyLong_CheckExact(arg)) break; return -1; } case 's': /* string */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayString))) break; if (PySequence_Check(arg) && !PyBytes_Check(arg) && !PyUnicode_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = (obj == Py_None || PyBytes_Check(obj) || PyUnicode_Check(obj)); Py_DECREF(obj); if (ok) break; } else break; } if (last && (arg == Py_None || PyBytes_Check(arg) || PyUnicode_Check(arg))) { varargs = true; break; } } else if (arg == Py_None || PyBytes_Check(arg) || PyUnicode_Check(arg)) break; return -1; } case 'o': /* java.lang.Object */ break; case 'O': /* java.lang.Object with type param */ { PyTypeObject *type = va_arg(list, PyTypeObject *); if (type != NULL) { boxfn fn = get_boxfn(type); if (fn == NULL || fn(type, arg, NULL) < 0) return -1; } break; } case 'T': /* tuple of python types with wrapfn_ */ { static PyObject *wrapfn_ = PyUnicode_FromString("wrapfn_"); int len = va_arg(list, int); if (PyTuple_Check(arg)) { if (PyTuple_GET_SIZE(arg) != len) return -1; for (int i = 0; i < len; i++) { PyObject *type = PyTuple_GET_ITEM(arg, i); if (!(type == Py_None || (PyType_Check(type) && PyObject_HasAttr(type, wrapfn_)))) return -1; } break; } return -1; } default: return -1; } if (tc != '[') array = 0; if (varargs) { pos = typeCount; break; } } if (array) return -1; if (pos == typeCount - 2 && types[pos] == '[' && types[pos + 1] != '[') { varargs = true; empty = true; pos = typeCount; } if (pos != typeCount) return -1; pos = 0; last = false; for (unsigned int a = 0; a <= count; a++, pos++) { char tc = types[pos]; PyObject *arg; if (a == count) { if (empty) /* empty varargs */ arg = NULL; else break; } else arg = args[a]; last = last || types[pos + 1] == '\0'; if (array > 1 && tc != '[') tc = 'o'; switch (tc) { case '[': { array += 1; a -= 1; break; } case 'j': /* Java object except String and Object */ case 'k': /* Java object, with initializeClass */ case 'K': /* Java object, with initializeClass and params */ { jclass cls = NULL; switch (tc) { case 'j': cls = (jclass) va_arg(check, Class *)->this$; break; case 'k': case 'K': getclassfn initializeClass = va_arg(check, getclassfn); cls = env->getClass(initializeClass); break; } if (array) { JArray *array = va_arg(list, JArray *); #ifdef _java_generics if (tc == 'K') { PyTypeObject ***tp = va_arg(list, PyTypeObject ***); va_arg(list, getparametersfn); *tp = NULL; } #endif if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = fromPySequence(cls, args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayObject))) *array = ((t_JArray *) arg)->array; else *array = JArray(cls, arg); if (PyErr_Occurred()) return -1; } else { Object *obj = va_arg(list, Object *); if (PyObject_TypeCheck(arg, PY_TYPE(FinalizerProxy))) arg = ((t_fp *) arg)->object; #ifdef _java_generics if (tc == 'K') { PyTypeObject ***tp = va_arg(list, PyTypeObject ***); PyTypeObject **(*parameters_)(void *) = va_arg(list, getparametersfn); if (arg == Py_None) *tp = NULL; else *tp = (*parameters_)(arg); } #endif *obj = arg == Py_None ? Object(NULL) : ((t_Object *) arg)->object; } break; } case 'Z': /* boolean, strict */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayBool))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jboolean *b = va_arg(list, jboolean *); *b = arg == Py_True; } break; } case 'B': /* byte */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayByte))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else if (PyBytes_Check(arg)) { jbyte *a = va_arg(list, jbyte *); *a = (jbyte) PyBytes_AS_STRING(arg)[0]; } else if (PyUnicode_Check(arg)) { jbyte *a = va_arg(list, jbyte *); *a = (jbyte) PyUnicode_AsUTF8(arg)[0]; } else { jbyte *a = va_arg(list, jbyte *); *a = (jbyte) PyLong_AsLong(arg); } break; } case 'C': /* char */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayChar))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jchar *c = va_arg(list, jchar *); *c = (jchar) PyUnicode_READ_CHAR(arg, 0); } break; } case 'I': /* int */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayInt))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jint *n = va_arg(list, jint *); *n = (jint) PyLong_AsLong(arg); } break; } case 'S': /* short */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayShort))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jshort *n = va_arg(list, jshort *); *n = (jshort) PyLong_AsLong(arg); } break; } case 'D': /* double */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayDouble))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jdouble *d = va_arg(list, jdouble *); *d = (jdouble) PyFloat_AsDouble(arg); } break; } case 'F': /* float */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayFloat))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jfloat *d = va_arg(list, jfloat *); *d = (jfloat) (float) PyFloat_AsDouble(arg); } break; } case 'J': /* long long */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayLong))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jlong *l = va_arg(list, jlong *); *l = (jlong) PyLong_AsLongLong(arg); } break; } case 's': /* string */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = fromPySequence( env->getClass(String::initializeClass), args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayString))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { String *str = va_arg(list, String *); if (arg == Py_None) *str = String(NULL); else { *str = p2j(arg); if (PyErr_Occurred()) return -1; } } break; } case 'o': /* java.lang.Object */ case 'O': /* java.lang.Object with type param */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray( env->getClass(Object::initializeClass), args + a, count - a); else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { Object *obj = va_arg(list, Object *); if (tc == 'O') { PyTypeObject *type = va_arg(check, PyTypeObject *); if (type != NULL) { boxfn fn = get_boxfn(type); if (fn == NULL || fn(type, arg, obj) < 0) return -1; break; } } if (boxObject(NULL, arg, obj) < 0) return -1; } break; } case 'T': /* tuple of python types with wrapfn_ */ { int len = va_arg(check, int); PyTypeObject **types = va_arg(list, PyTypeObject **); for (int i = 0; i < len; i++) { PyObject *type = PyTuple_GET_ITEM(arg, i); if (type == Py_None) types[i] = NULL; else types[i] = (PyTypeObject *) type; } break; } default: return -1; } if (tc != '[') array = 0; if (last && varargs) { pos = typeCount; break; } } if (pos == typeCount) return 0; return -1; } String p2j(PyObject *object) { return String(env->fromPyString(object)); } PyObject *j2p(const String& js) { return env->fromJString((jstring) js.this$, 0); } PyObject *c2p(jchar c) { PyObject *result = PyUnicode_New(1, c); PyUnicode_WriteChar(result, 0, c); return result; } PyObject *PyErr_SetArgsError(char *name, PyObject *args) { if (!PyErr_Occurred()) { PyObject *err = Py_BuildValue("(sO)", name, args); PyErr_SetObject(PyExc_InvalidArgsError, err); Py_DECREF(err); } return NULL; } PyObject *PyErr_SetArgsError(PyObject *self, char *name, PyObject *args) { if (!PyErr_Occurred()) { PyObject *type = (PyObject *) self->ob_type; PyObject *err = Py_BuildValue("(OsO)", type, name, args); PyErr_SetObject(PyExc_InvalidArgsError, err); Py_DECREF(err); } return NULL; } PyObject *PyErr_SetArgsError(PyTypeObject *type, char *name, PyObject *args) { if (!PyErr_Occurred()) { PyObject *err = Py_BuildValue("(OsO)", type, name, args); PyErr_SetObject(PyExc_InvalidArgsError, err); Py_DECREF(err); } return NULL; } PyObject *PyErr_SetJavaError() { JNIEnv *vm_env = env->get_vm_env(); jthrowable throwable = vm_env->ExceptionOccurred(); vm_env->ExceptionClear(); if (env->restorePythonException(throwable)) return NULL; PyObject *err = t_Throwable::wrap_Object(Throwable(throwable)); PyErr_SetObject(PyExc_JavaError, err); Py_DECREF(err); return NULL; } void throwPythonError(void) { PyObject *exc = PyErr_Occurred(); if (exc && PyErr_GivenExceptionMatches(exc, PyExc_JavaError)) { PyObject *value, *traceback; PyErr_Fetch(&exc, &value, &traceback); if (value) { PyObject *je = PyObject_CallMethod(value, "getJavaException", ""); if (!je) PyErr_Restore(exc, value, traceback); else { Py_DECREF(exc); Py_DECREF(value); Py_XDECREF(traceback); exc = je; if (exc && PyObject_TypeCheck(exc, PY_TYPE(Throwable))) { jobject jobj = ((t_Throwable *) exc)->object.this$; env->get_vm_env()->Throw((jthrowable) jobj); Py_DECREF(exc); return; } } } else { Py_DECREF(exc); Py_XDECREF(traceback); } } else if (exc && PyErr_GivenExceptionMatches(exc, PyExc_StopIteration)) { PyErr_Clear(); return; } if (exc) { PyObject *name = PyObject_GetAttrString(exc, "__name__"); env->get_vm_env()->ThrowNew(env->getPythonExceptionClass(), PyUnicode_AsUTF8(name)); Py_DECREF(name); } else env->get_vm_env()->ThrowNew(env->getPythonExceptionClass(), "python error"); } void throwTypeError(const char *name, PyObject *object) { PyObject *tuple = Py_BuildValue("(ssO)", "while calling", name, object); PyErr_SetObject(PyExc_TypeError, tuple); Py_DECREF(tuple); env->get_vm_env()->ThrowNew(env->getPythonExceptionClass(), "type error"); } int abstract_init(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *err = Py_BuildValue("(sO)", "instantiating java class", self->ob_type); PyErr_SetObject(PyExc_NotImplementedError, err); Py_DECREF(err); return -1; } PyObject *callSuper(PyTypeObject *type, const char *name, PyObject *args, int cardinality) { PyObject *super = (PyObject *) type->tp_base; PyObject *method = PyObject_GetAttrString(super, (char *) name); // python 2.4 cast PyObject *value; if (!method) return NULL; if (cardinality > 1) value = PyObject_Call(method, args, NULL); else { PyObject *tuple = PyTuple_Pack(1, args); value = PyObject_Call(method, tuple, NULL); Py_DECREF(tuple); } Py_DECREF(method); return value; } PyObject *callSuper(PyTypeObject *type, PyObject *self, const char *name, PyObject *args, int cardinality) { PyObject *tuple = PyTuple_Pack(2, type, self); PyObject *super = PyObject_Call((PyObject *) &PySuper_Type, tuple, NULL); PyObject *method, *value; Py_DECREF(tuple); if (!super) return NULL; method = PyObject_GetAttrString(super, (char *) name); // python 2.4 cast Py_DECREF(super); if (!method) return NULL; if (cardinality > 1) value = PyObject_Call(method, args, NULL); else { tuple = PyTuple_Pack(1, args); value = PyObject_Call(method, tuple, NULL); Py_DECREF(tuple); } Py_DECREF(method); return value; } PyObject *castCheck(PyObject *obj, getclassfn initializeClass, int reportError) { if (PyObject_TypeCheck(obj, PY_TYPE(FinalizerProxy))) obj = ((t_fp *) obj)->object; if (!PyObject_TypeCheck(obj, PY_TYPE(Object))) { if (reportError) PyErr_SetObject(PyExc_TypeError, obj); return NULL; } jobject jobj = ((t_Object *) obj)->object.this$; if (jobj && !env->isInstanceOf(jobj, initializeClass)) { if (reportError) PyErr_SetObject(PyExc_TypeError, obj); return NULL; } return obj; } PyObject *get_extension_iterator(PyObject *self) { return PyObject_CallMethod(self, "iterator", ""); } PyObject *get_extension_next(PyObject *self) { return PyObject_CallMethod(self, "next", ""); } PyObject *get_extension_nextElement(PyObject *self) { return PyObject_CallMethod(self, "nextElement", ""); } static bool setArrayObj(jobjectArray array, int index, PyObject *obj) { bool deleteLocal = false; jobject jobj; if (obj == Py_None) jobj = NULL; else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { jobj = env->fromPyString(obj); deleteLocal = true; } else if (PyObject_TypeCheck(obj, PY_TYPE(JObject))) jobj = ((t_JObject *) obj)->object.this$; else if (PyObject_TypeCheck(obj, PY_TYPE(FinalizerProxy))) jobj = ((t_JObject *) ((t_fp *) obj)->object)->object.this$; else if (obj == Py_True || obj == Py_False) { jobj = env->boxBoolean(obj == Py_True); deleteLocal = true; } else if (PyFloat_Check(obj)) { jobj = env->boxDouble(PyFloat_AS_DOUBLE(obj)); deleteLocal = true; } else if (PyLong_Check(obj)) { long long value = PyLong_AsLongLong(obj); if (static_cast(static_cast(value)) == value) jobj = env->boxInteger((int) value); else jobj = env->boxLong(value); deleteLocal = true; } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); return false; } try { env->setObjectArrayElement(array, index, jobj); if (deleteLocal) env->get_vm_env()->DeleteLocalRef(jobj); Py_DECREF(obj); } catch (int e) { Py_DECREF(obj); switch (e) { case _EXC_JAVA: PyErr_SetJavaError(); return false; default: throw; } } return true; } jobjectArray fromPySequence(jclass cls, PyObject *sequence) { if (sequence == Py_None) return NULL; if (!PySequence_Check(sequence)) { PyErr_SetObject(PyExc_TypeError, sequence); return NULL; } int length = PySequence_Length(sequence); jobjectArray array; try { array = env->newObjectArray(cls, length); } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: PyErr_SetJavaError(); return NULL; default: throw; } } for (int i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (!setArrayObj(array, i, obj)) return NULL; } return array; } jobjectArray fromPySequence(jclass cls, PyObject **args, int length) { jobjectArray array; try { array = env->newObjectArray(cls, length); } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: PyErr_SetJavaError(); return NULL; default: throw; } } for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; Py_INCREF(obj); if (!setArrayObj(array, i, obj)) return NULL; } return array; } PyTypeObject *makeType(PyType_Def *def) { if (def->type == NULL) { int count = 0; for (PyType_Def **base = def->bases; *base != NULL; ++base) count += 1; PyObject *bases = PyTuple_New(count); for (int i = 0; i < count; ++i) PyTuple_SET_ITEM(bases, i, (PyObject *) makeType(def->bases[i])); def->type = (PyTypeObject *) PyType_FromSpecWithBases(&def->spec, bases); Py_DECREF(bases); } return def->type; } void installType(PyTypeObject **type, PyType_Def *def, PyObject *module, char *name, int isExtension) { if (*type == NULL) { *type = makeType(def); Py_INCREF(*type); if (isExtension) { Py_TYPE(*type) = PY_TYPE(FinalizerClass); Py_INCREF(PY_TYPE(FinalizerClass)); } PyModule_AddObject(module, name, (PyObject *) *type); } } PyObject *wrapType(PyTypeObject *type, const jobject& obj) { static PyObject *wrapfn_ = PyUnicode_FromString("wrapfn_"); PyObject *cobj = PyObject_GetAttr((PyObject *) type, wrapfn_); PyObject *(*wrapfn)(const jobject&); if (cobj == NULL) return NULL; wrapfn = (PyObject *(*)(const jobject &)) PyCapsule_GetPointer(cobj, "wrapfn"); Py_DECREF(cobj); return wrapfn(obj); } PyObject *unboxBoolean(const jobject& obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Boolean::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Boolean)); return NULL; } if (env->booleanValue(obj)) Py_RETURN_TRUE; Py_RETURN_FALSE; } Py_RETURN_NONE; } PyObject *unboxByte(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Byte::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Byte)); return NULL; } return PyLong_FromLong((long) env->byteValue(obj)); } Py_RETURN_NONE; } PyObject *unboxCharacter(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Character::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Character)); return NULL; } return c2p(env->charValue(obj)); } Py_RETURN_NONE; } PyObject *unboxDouble(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Double::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Double)); return NULL; } return PyFloat_FromDouble((double) env->doubleValue(obj)); } Py_RETURN_NONE; } PyObject *unboxFloat(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Float::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Float)); return NULL; } return PyFloat_FromDouble((double) env->floatValue(obj)); } Py_RETURN_NONE; } PyObject *unboxInteger(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Integer::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Integer)); return NULL; } return PyLong_FromLong((long) env->intValue(obj)); } Py_RETURN_NONE; } PyObject *unboxLong(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Long::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Long)); return NULL; } return PyLong_FromLongLong((PY_LONG_LONG) env->longValue(obj)); } Py_RETURN_NONE; } PyObject *unboxShort(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Short::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(Short)); return NULL; } return PyLong_FromLong((long) env->shortValue(obj)); } Py_RETURN_NONE; } PyObject *unboxString(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::String::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) java::lang::PY_TYPE(String)); return NULL; } return env->fromJString((jstring) obj, 0); } Py_RETURN_NONE; } static int boxJObject(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { if (arg == Py_None) { if (obj != NULL) *obj = Object(NULL); } else if (PyObject_TypeCheck(arg, PY_TYPE(Object))) { if (type != NULL && !is_instance_of(arg, type)) return -1; if (obj != NULL) *obj = ((t_Object *) arg)->object; } else if (PyObject_TypeCheck(arg, PY_TYPE(FinalizerProxy))) { arg = ((t_fp *) arg)->object; if (PyObject_TypeCheck(arg, PY_TYPE(Object))) { if (type != NULL && !is_instance_of(arg, type)) return -1; if (obj != NULL) *obj = ((t_Object *) arg)->object; } else return -1; } else return 1; return 0; } int boxBoolean(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (arg == Py_True) { if (obj != NULL) *obj = *Boolean::TRUE; } else if (arg == Py_False) { if (obj != NULL) *obj = *Boolean::FALSE; } else return -1; return 0; } int boxByte(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { long ln = PyLong_AS_LONG(arg); jbyte b = (jbyte) ln; if (b == ln) { if (obj != NULL) *obj = Byte(b); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); jbyte b = (jbyte) d; if (b == d) { if (obj != NULL) *obj = Byte(b); } else return -1; } else return -1; return 0; } int boxCharacter(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyBytes_Check(arg)) { char *c; Py_ssize_t len; if (PyBytes_AsStringAndSize(arg, &c, &len) < 0 || len != 1) return -1; if (obj != NULL) *obj = Character((jchar) c[0]); } else if (PyUnicode_Check(arg)) { Py_ssize_t len = PyUnicode_GetLength(arg); if (len != 1) return -1; if (obj != NULL) *obj = Character((jchar) PyUnicode_READ_CHAR(arg, 0)); } else return -1; return 0; } int boxCharSequence(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyBytes_Check(arg) || PyUnicode_Check(arg)) { if (obj != NULL) { *obj = p2j(arg); if (PyErr_Occurred()) return -1; } } else return -1; return 0; } int boxDouble(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { if (obj != NULL) *obj = Double((jdouble) PyLong_AsLongLong(arg)); } else if (PyFloat_Check(arg)) { if (obj != NULL) *obj = Double(PyFloat_AS_DOUBLE(arg)); } else return -1; return 0; } int boxFloat(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); float f = (float) ln; if ((PY_LONG_LONG) f == ln) { if (obj != NULL) *obj = Float(f); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); float f = (float) d; if ((double) f == d) { if (obj != NULL) *obj = Float(f); } else return -1; } else return -1; return 0; } int boxInteger(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); int n = (int) ln; if (n == ln) { if (obj != NULL) *obj = Integer(n); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); int n = (int) d; if ((double) n == d) { if (obj != NULL) *obj = Integer(n); } else return -1; } else return -1; return 0; } int boxLong(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { if (obj != NULL) *obj = Long((jlong) PyLong_AsLongLong(arg)); } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); PY_LONG_LONG n = (PY_LONG_LONG) d; if ((double) n == d) { if (obj != NULL) *obj = Long((jlong) n); } else return -1; } else return -1; return 0; } int boxNumber(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { if (obj != NULL) { long long value = PyLong_AsLongLong(arg); if (static_cast(static_cast(value)) == value) *obj = Integer((jint) value); else *obj = Long((jlong) value); } } else if (PyFloat_Check(arg)) { if (obj != NULL) *obj = Double((jdouble) PyFloat_AS_DOUBLE(arg)); } else return -1; return 0; } int boxShort(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); short sn = (short) ln; if (sn == ln) { if (obj != NULL) *obj = Short((jshort) sn); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); short sn = (short) (int) d; if ((double) sn == d) { if (obj != NULL) *obj = Short((jshort) sn); } else return -1; } else return -1; return 0; } int boxString(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyBytes_Check(arg) || PyUnicode_Check(arg)) { if (obj != NULL) { *obj = p2j(arg); if (PyErr_Occurred()) return -1; } } else return -1; return 0; } int boxObject(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (obj != NULL) { if (PyBytes_Check(arg) || PyUnicode_Check(arg)) { *obj = p2j(arg); if (PyErr_Occurred()) return -1; } else if (arg == Py_True) *obj = *Boolean::TRUE; else if (arg == Py_False) *obj = *Boolean::FALSE; else if (PyLong_Check(arg)) { long long value = PyLong_AsLongLong(arg); if (static_cast(static_cast(value)) == value) *obj = Integer((jint) value); else *obj = Long((jlong) value); } else if (PyFloat_Check(arg)) *obj = Double((jdouble) PyFloat_AS_DOUBLE(arg)); else return -1; } else if (!(PyBytes_Check(arg) || PyUnicode_Check(arg) || arg == Py_True || arg == Py_False || PyLong_Check(arg) || PyFloat_Check(arg))) return -1; return 0; } #ifdef _java_generics PyObject *typeParameters(PyTypeObject *types[], size_t size) { size_t count = size / sizeof(PyTypeObject *); PyObject *tuple = PyTuple_New(count); for (size_t i = 0; i < count; i++) { PyObject *type = (PyObject *) types[i]; if (type == NULL) type = Py_None; PyTuple_SET_ITEM(tuple, i, type); Py_INCREF(type); } return tuple; } #endif JCC-3.6/jcc3/windows.py0000644000076500000000000000476513063317171015070 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, winreg class WindowsRegistry(object): def __init__(self): self.handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) def get(self, key, name): handle = None try: handle = winreg.OpenKey(self.handle, key) return winreg.QueryValueEx(handle, name)[0] finally: if handle is not None: handle.Close() def close(self): self.handle.Close() def get_jvm_dll_directory(client_or_server="client"): jre_key = r"SOFTWARE\JavaSoft\Java Runtime Environment" jdk_key = r"SOFTWARE\JavaSoft\Java Development Kit" current_key = r"%s\%s" registry = None try: registry = WindowsRegistry() try: # try JRE version = registry.get(jre_key, "CurrentVersion") path = registry.get(current_key %(jre_key, version), "JavaHome") if not os.path.exists(path): path = None except: path = None if not path: try: # try JDK version = registry.get(jdk_key, "CurrentVersion") path = registry.get(current_key %(jdk_key, version), "JavaHome") if os.path.exists(path): path = os.path.abspath(os.path.join(path, "jre")) else: path = None except: path = None finally: if registry is not None: registry.close() if path: path = os.path.abspath(os.path.join(path, "bin", client_or_server)) if os.path.exists(os.path.join(path, "jvm.dll")): return path return None def add_jvm_dll_directory_to_path(): path = os.environ['Path'].split(os.pathsep) dll_path = get_jvm_dll_directory() if dll_path is not None: path.append(dll_path) os.environ['Path'] = os.pathsep.join(path) return True raise ValueError("jvm.dll could not be found") JCC-3.6/jcc3/__main__.py0000644000076500000000000001253613063316466015117 0ustar vajdawheel00000000000000 import sys from jcc import cpp if len(sys.argv) == 1 or '--help' in sys.argv: help = ''' JCC - C++/Python Java Native Interface Code Generator Usage: python -m jcc [options] [actions] Input options: --jar JARFILE - make JCC wrap all public classes found in JARFILE, add it to the module's CLASSPATH and include it in the distribution --include JARFILE - include JARFILE in the distribution and add it to the module's CLASSPATH --import MODULE - link against the wrappers to classes shared with MODULE instead of generating duplicate and incompatible wrappers --exclude CLASS - explicitly don't wrap CLASS --package PACKAGE - add PACKAGE to the list of packages from which dependencies are automatically wrapped --classpath [PATH|JAR] - add [PATH|JAR] to CLASSPATH while generating wrappers --libpath [PATH] - add [PATH] to java.library.path while generating wrappers --module MODULE - include Python MODULE in the distribution --reserved SYMBOL - mark SYMBOL as a reserved word that will be mangled in the generated C++ code to avoid clashes with C/C++ reserved words or header file definitions --vmarg - add extra Java VM initialization parameter --maxheap - set the maximum Java heap size, as passing -Xmx* using --vmarg doesn't do anything --resources - include resource directory in distribution as package data Python wrapper generation options: --python NAME - generate wrappers for use from Python in a module called NAME --version VERSION - the generated module's version number --shared - generate a module that links against a shared library version of the JCC runtime so that multiple JCC-wrapped modules can be used within the same Python runtime --sequence CLASS METHODSIGNATURE - generate a pythonic sequence protocol wrapper for CLASS --mapping CLASS METHODSIGNATURE1 METHODSIGNATURE2 - generate a pythonic map protocol wrapper for CLASS --rename CLASS1=NAME1,CLASS2=NAME2,... - rename one or more Python wrapper classes to avoid name clashes due to the flattening of the Java package namespaces as mapped into Python --use_full_names - map the full Java package structure into Python modules, as an alternative to selectively renaming or excluding classes due to name conflicts --no-generics - disable support for Java generics If you're planning to use pythonic wrappers you should read the relevant documentation first: http://lucene.apache.org/pylucene/jcc/documentation/readme.html#python Output options: --debug - generate a module using the C++ compiler's debug options --output OUTPUTDIR - the wrapper will be generated in OUTPUTDIR, 'build' by default --files N - split the generated wrapper file into at least N files to workaround C++ compiler file size limitations --arch - Mac OS X only: filter the -arch parameters Python was configured with to build leaner binaries, faster --find-jvm-dll - Windows only: extract the directory containing jvm.dll from the registry and append it to the Path at runtime Actions: --build - generate the wrapper and compile it --compile - recompile the (previously generated) module --install - install the wrapper in the local site-packages --egg-info - ask distutils setup() to generate egg info, and don't compile the module (for pip install) Distribution actions: --use-distutils - use distutils even when setuptools is available --bdist - generate a binary distutils-based distribution or a setuptools-based .egg --wininst - create an installer application for Microsoft Windows Other distutils/setuptools options (there are passed right through): --compiler COMPILER - use COMPILER instead of the platform default --root ROOTDIR --install-dir INSTALLDIR --prefix PREFIX --home HOMEDIR --extra-setup-arg - pass an extra argument on setup.py command line (pip install uses --egg-base and --record params) ''' print(help) sys.exit(0) cpp.jcc(sys.argv) JCC-3.6/LICENSE0000644000076500000000000000106311131542523013166 0ustar vajdawheel00000000000000 # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. JCC-3.6/helpers3/0000755000076500000000000000000013536235634013723 5ustar vajdawheel00000000000000JCC-3.6/helpers3/build.py0000644000076500000000000000277013063564166015402 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from distutils.command.build_py import build_py from distutils import log class jcc_build_py(build_py): config_text = None config_file = None def run(self): self.write_jcc_config() return build_py.run(self) def write_jcc_config(self): # only write jcc's config.py file if it doesn't exist or a build # command is given write = False if not os.path.isfile(self.config_file): write = True else: for command in self.distribution.commands: if command.startswith("build"): write = True break if write: log.info("writing %s" %(self.config_file)) config = open(self.config_file, 'w') try: config.write(self.config_text) finally: config.close() else: log.info("not writing %s" %(self.config_file)) JCC-3.6/helpers3/mingw32.py0000644000076500000000000000371213063044250015551 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, copy from distutils.cygwinccompiler import Mingw32CCompiler class JCCMinGW32CCompiler(Mingw32CCompiler): def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # use separate copies, so we can modify the lists extra_preargs = copy.copy(extra_preargs or []) (dll_name, dll_extension) = os.path.splitext(output_filename) if dll_extension.lower() == ".dll": extra_preargs.extend(["-Wl,--out-implib,%s" %(os.path.join(os.path.dirname(dll_name), "jcc", "jcc.lib"))]) Mingw32CCompiler.link(self, target_desc=target_desc, objects=objects, output_filename=output_filename, output_dir=output_dir, libraries=libraries, library_dirs=library_dirs, runtime_library_dirs=runtime_library_dirs, export_symbols=export_symbols, debug=debug, extra_preargs=extra_preargs, extra_postargs=extra_postargs, build_temp=build_temp, target_lang=target_lang) JCC-3.6/helpers3/__init__.py0000644000076500000000000000002213063044250016011 0ustar vajdawheel00000000000000# helpers package JCC-3.6/helpers3/darwin.py0000644000076500000000000000524313063552161015555 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys, os global JAVAHOME, JAVAFRAMEWORKS JAVAHOME = None JAVAFRAMEWORKS = None if sys.platform == "darwin": # figure out where the JDK lives from subprocess import run, PIPE try: args = ['/usr/libexec/java_home'] process = run(args, stdout=PIPE, stderr=PIPE, encoding='utf8') except Exception as e: print("%s: %s" %(e, args), file=sys.stderr) else: if process.returncode == 0: _path = process.stdout.strip() if os.path.exists(os.path.join(_path, "include", "jni.h")): JAVAHOME = _path print('found JAVAHOME =', JAVAHOME, file=sys.stderr) else: print(process.stderr.read(), file=sys.stderr) # figure out where the JDK Frameworks lives import platform, re _os_version = re.match("[0-9]+\.[0-9]+", platform.mac_ver()[0]).group(0) # this is where Apple says we should look for headers _path = "/System/Library/Frameworks/JavaVM.framework" if os.path.exists(os.path.join(_path, "Headers", "jni.h")): JAVAFRAMEWORKS = _path print('found JAVAFRAMEWORKS =', JAVAFRAMEWORKS, file=sys.stderr) else: # but their updates don't always match their documentation, # so look up the same path in the OS's /Developer tree _path = "/Developer/SDKs/MacOSX%s.sdk%s" %(_os_version, _path) if os.path.exists(os.path.join(_path, "Headers", "jni.h")): JAVAFRAMEWORKS = _path print('found JAVAFRAMEWORKS =', JAVAFRAMEWORKS, file=sys.stderr) # monkeypatch build_ext so that it doesn't mess with a Library's extension from setuptools.command.build_ext import build_ext as _build_ext from setuptools.extension import Library class build_ext_(_build_ext): def get_ext_filename(self, fullname): if fullname in self.ext_map: ext = self.ext_map[fullname] if isinstance(ext, Library): return "lib%s.dylib" %(fullname) return _build_ext.get_ext_filename(self, fullname) from setuptools.command import build_ext build_ext.build_ext = build_ext_ JCC-3.6/helpers3/windows.py0000644000076500000000000000356413063045052015763 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys global JAVAHOME JAVAHOME = None if sys.platform == "win32": # figure out where the JDK lives try: import winreg as wreg class WindowsRegistry: # see the Python Cookbook, #146305, Dirk Holtwick def __init__(self, keyname): " handle registry access " self.reg = wreg.ConnectRegistry(None, wreg.HKEY_LOCAL_MACHINE) self.key = wreg.OpenKey(self.reg, keyname) def get(self, name): " get value out of registry " v, t = wreg.QueryValueEx(self.key, name) return v, t def close(self): " close the key finally " if hasattr(self, 'key'): self.key.Close() if hasattr(self, 'reg'): self.reg.Close() def __del__(self): self.close() def get_registry_value(vname, subname): r = WindowsRegistry(vname) v, t = r.get(subname) return v javaversion = get_registry_value(r"SOFTWARE\JavaSoft\Java Development Kit", "CurrentVersion") JAVAHOME = get_registry_value(r"SOFTWARE\JavaSoft\Java Development Kit\%s" % javaversion, "JavaHome") except: JAVAHOME = 'c:/Program Files/Java/jdk1.6.0_18' JCC-3.6/helpers3/linux.py0000644000076500000000000001121713240641353015425 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys, os, os.path, re import distutils, setuptools from setuptools import dist, extension from setuptools.command import build_ext from setuptools.extension import Library as _Library def patch_setuptools(with_setuptools): try: from setuptools.command.build_ext import sh_link_shared_object enable_shared = True # jcc2/patches/patch.43 was applied except ImportError: # patch build_ext so that it doesn't mess with a Library's extension from setuptools.command.build_ext import build_ext as _build_ext from setuptools.extension import Library setuptools.Library = LinuxLibrary extension.Library = LinuxLibrary build_ext.build_ext = LinuxBuildExt if build_ext.use_stubs: # Build shared libraries. global sh_link_shared_object # Fix UnboundLocalError build_ext.link_shared_object = sh_link_shared_object else: # Build static libraries every where else (unless forced) build_ext.libtype = 'static' build_ext.link_shared_object = st_link_shared_object print("Applied shared mode monkeypatch to:", setuptools, file=sys.stderr) return True # monkey patch was applied return enable_shared class LinuxLibrary(_Library): def __init__(self, *args, **kwds): self.force_shared = kwds.pop('force_shared', False) extension.Extension.__init__(self, *args, **kwds) class LinuxBuildExt(build_ext.build_ext): def get_ext_filename(self, fullname): filename = build_ext._build_ext.get_ext_filename(self, fullname) if fullname in self.ext_map: ext = self.ext_map[fullname] if isinstance(ext, _Library): filename = '%s.so' %(fullname) if ext.force_shared and not build_ext.use_stubs: libtype = 'shared' else: libtype = build_ext.libtype fn, ext = os.path.splitext(filename) return self.shlib_compiler.library_filename(fn, libtype) elif build_ext.use_stubs and ext._links_to_dynamic: d, fn = os.path.split(filename) return os.path.join(d, 'dl-' + fn) return filename def build_extension(self, ext): _compiler = self.compiler try: force_shared = False if isinstance(ext, _Library): self.compiler = self.shlib_compiler force_shared = ext.force_shared and not build_ext.use_stubs if force_shared: self.compiler.link_shared_object = sh_link_shared_object.__get__(self.compiler) build_ext._build_ext.build_extension(self, ext) if ext._needs_stub: self.write_stub(self.get_finalized_command('build_py').build_lib, ext) finally: if force_shared: self.compiler.link_shared_object = build_ext.link_shared_object.__get__(self.compiler) self.compiler = _compiler def sh_link_shared_object(self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): self.link(self.SHARED_LIBRARY, objects, output_libname, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols, debug, extra_preargs, extra_postargs, build_temp, target_lang) def st_link_shared_object(self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): assert output_dir is None # distutils build_ext doesn't pass this output_dir, filename = os.path.split(output_libname) basename, ext = os.path.splitext(filename) if self.library_filename("x").startswith('lib'): # strip 'lib' prefix; this is kludgy if some platform uses # a different prefix basename = basename[3:] self.create_static_lib(objects, basename, output_dir, debug, target_lang) JCC-3.6/_jcc3/0000755000076500000000000000000013536235634013157 5ustar vajdawheel00000000000000JCC-3.6/_jcc3/boot.cpp0000644000076500000000000000434013121702604014611 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "java/lang/Class.h" #include "java/lang/RuntimeException.h" #include "macros.h" extern PyTypeObject *PY_TYPE(JObject), *PY_TYPE(ConstVariableDescriptor); PyObject *initJCC(PyObject *module); PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds); namespace java { namespace lang { void __install__(PyObject *m); } namespace io { void __install__(PyObject *m); } } PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds) { PyObject *env = initVM(module, args, kwds); if (env == NULL) return NULL; java::lang::Class::initializeClass(false); java::lang::RuntimeException::initializeClass(false); return env; } #include "jccfuncs.h" extern "C" { static struct PyModuleDef _jccmodule = { PyModuleDef_HEAD_INIT, /* m_base */ "_jcc3", /* m_name */ "_jcc3 module", /* m_doc */ 0, /* m_size */ jcc_funcs, /* m_methods */ 0, /* m_reload */ 0, /* m_traverse */ 0, /* m_clear */ 0, /* m_free */ }; PyObject *PyInit__jcc3(void) { PyObject *m = PyModule_Create(&_jccmodule); if (!m) return NULL; initJCC(m); INSTALL_STATIC_TYPE(JObject, m); PY_TYPE_DEF(JObject).type = PY_TYPE(JObject); INSTALL_STATIC_TYPE(ConstVariableDescriptor, m); java::lang::__install__(m); java::io::__install__(m); return m; } } JCC-3.6/_jcc3/java/0000755000076500000000000000000013536235634014100 5ustar vajdawheel00000000000000JCC-3.6/_jcc3/java/util/0000755000076500000000000000000013536235634015055 5ustar vajdawheel00000000000000JCC-3.6/_jcc3/java/util/Iterator.cpp0000644000076500000000000000760613122243525017350 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/util/Iterator.h" namespace java { namespace util { enum { mid_hasNext, mid_next, max_mid }; Class *Iterator::class$ = NULL; jmethodID *Iterator::mids$ = NULL; jclass Iterator::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/util/Iterator"); mids$ = new jmethodID[max_mid]; mids$[mid_hasNext] = env->getMethodID(cls, "hasNext", "()Z"); mids$[mid_next] = env->getMethodID(cls, "next", "()Ljava/lang/Object;"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } jboolean Iterator::hasNext() const { return env->callBooleanMethod(this$, mids$[mid_hasNext]); } Object Iterator::next() const { return Object(env->callObjectMethod(this$, mids$[mid_next])); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace util { static PyObject *t_Iterator_hasNext(t_Iterator *self); static PyObject *t_Iterator_next(t_Iterator *self); static PyMethodDef t_Iterator__methods_[] = { DECLARE_METHOD(t_Iterator, hasNext, METH_NOARGS), DECLARE_METHOD(t_Iterator, next, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Iterator)[] = { { Py_tp_methods, t_Iterator__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Iterator)[] = { &PY_TYPE_DEF(JObject), NULL }; DEFINE_TYPE(Iterator, t_Iterator, java::util::Iterator); #ifdef _java_generics PyObject *t_Iterator::wrap_Object(const Iterator& object, PyTypeObject *T) { PyObject *obj = t_Iterator::wrap_Object(object); if (obj != Py_None) { t_Iterator *self = (t_Iterator *) obj; self->parameters[0] = T; } return obj; } PyObject *t_Iterator::wrap_jobject(const jobject& object, PyTypeObject *T) { PyObject *obj = t_Iterator::wrap_jobject(object); if (obj != Py_None) { t_Iterator *self = (t_Iterator *) obj; self->parameters[0] = T; } return obj; } #endif static PyObject *t_Iterator_hasNext(t_Iterator *self) { jboolean b; OBJ_CALL(b = self->object.hasNext()); Py_RETURN_BOOL(b); } static PyObject *t_Iterator_next(t_Iterator *self) { Object next((jobject) NULL); OBJ_CALL(next = self->object.next()); return t_Object::wrap_Object(next); } } } JCC-3.6/_jcc3/java/util/Enumeration.h0000644000076500000000000000357713121703300017504 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Enumeration_H #define _Enumeration_H #include #include "JObject.h" namespace java { namespace lang { class Class; class Object; } namespace util { using namespace java::lang; class Enumeration : public JObject { public: static Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Enumeration(jobject obj) : JObject(obj) { initializeClass(false); } jboolean hasMoreElements() const; Object nextElement() const; }; DECLARE_TYPE(Enumeration); class t_Enumeration { public: PyObject_HEAD Enumeration object; #ifdef _java_generics PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_Enumeration *self) { return (PyTypeObject **) &(self->parameters); } #endif static PyObject *wrap_Object(const Enumeration& object); #ifdef _java_generics static PyObject *wrap_Object(const Enumeration& object, PyTypeObject *T); #endif static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Enumeration_H */ JCC-3.6/_jcc3/java/util/Enumeration.cpp0000644000076500000000000000721613122243517020043 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/util/Enumeration.h" namespace java { namespace util { enum { mid_hasMoreElements, mid_nextElement, max_mid }; Class *Enumeration::class$ = NULL; jmethodID *Enumeration::mids$ = NULL; jclass Enumeration::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/util/Enumeration"); mids$ = new jmethodID[max_mid]; mids$[mid_hasMoreElements] = env->getMethodID(cls, "hasMoreElements", "()Z"); mids$[mid_nextElement] = env->getMethodID(cls, "nextElement", "()Ljava/lang/Object;"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } jboolean Enumeration::hasMoreElements() const { return env->callBooleanMethod(this$, mids$[mid_hasMoreElements]); } Object Enumeration::nextElement() const { return Object(env->callObjectMethod(this$, mids$[mid_nextElement])); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace util { static PyObject *t_Enumeration_hasMoreElements(t_Enumeration *self); static PyObject *t_Enumeration_nextElement(t_Enumeration *self); static PyMethodDef t_Enumeration__methods_[] = { DECLARE_METHOD(t_Enumeration, hasMoreElements, METH_NOARGS), DECLARE_METHOD(t_Enumeration, nextElement, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Enumeration)[] = { { Py_tp_methods, t_Enumeration__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Enumeration)[] = { &PY_TYPE_DEF(JObject), NULL }; DEFINE_TYPE(Enumeration, t_Enumeration, java::util::Enumeration); #ifdef _java_generics PyObject *t_Enumeration::wrap_Object(const Enumeration& object, PyTypeObject *T) { PyObject *obj = t_Enumeration::wrap_Object(object); if (obj != Py_None) { t_Enumeration *self = (t_Enumeration *) obj; self->parameters[0] = T; } return obj; } #endif static PyObject *t_Enumeration_hasMoreElements(t_Enumeration *self) { jboolean b; OBJ_CALL(b = self->object.hasMoreElements()); Py_RETURN_BOOL(b); } static PyObject *t_Enumeration_nextElement(t_Enumeration *self) { Object nextElement((jobject) NULL); OBJ_CALL(nextElement = self->object.nextElement()); return t_Object::wrap_Object(nextElement); } } } JCC-3.6/_jcc3/java/util/Iterator.h0000644000076500000000000000371413121703303017003 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Iterator_H #define _Iterator_H #include #include "JObject.h" namespace java { namespace lang { class Class; class Object; } namespace util { using namespace java::lang; class Iterator : public JObject { public: static Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Iterator(jobject obj) : JObject(obj) { initializeClass(false); } jboolean hasNext() const; Object next() const; }; DECLARE_TYPE(Iterator); class t_Iterator { public: PyObject_HEAD Iterator object; #ifdef _java_generics PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_Iterator *self) { return (PyTypeObject **) &(self->parameters); } #endif static PyObject *wrap_Object(const Iterator& object); static PyObject *wrap_jobject(const jobject& object); #ifdef _java_generics static PyObject *wrap_Object(const Iterator& object, PyTypeObject *T); static PyObject *wrap_jobject(const jobject& object, PyTypeObject *T); #endif }; } } #endif /* _Iterator_H */ JCC-3.6/_jcc3/java/io/0000755000076500000000000000000013536235634014507 5ustar vajdawheel00000000000000JCC-3.6/_jcc3/java/io/PrintWriter.cpp0000644000076500000000000000544113122243203017466 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/io/PrintWriter.h" namespace java { namespace io { enum { mid__init_, max_mid }; java::lang::Class *PrintWriter::class$ = NULL; jmethodID *PrintWriter::_mids = NULL; jclass PrintWriter::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/io/PrintWriter"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(Ljava/io/Writer;)V"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } PrintWriter::PrintWriter(Writer writer) : Writer(env->newObject(initializeClass, &_mids, mid__init_, writer.this$)) { } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace io { static int t_PrintWriter_init(t_PrintWriter *self, PyObject *args, PyObject *kwds); static PyMethodDef t_PrintWriter__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(PrintWriter)[] = { { Py_tp_methods, t_PrintWriter__methods_ }, { Py_tp_init, (void *) t_PrintWriter_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(PrintWriter)[] = { &PY_TYPE_DEF(Writer), NULL }; DEFINE_TYPE(PrintWriter, t_PrintWriter, java::io::PrintWriter); static int t_PrintWriter_init(t_PrintWriter *self, PyObject *args, PyObject *kwds) { Writer writer((jobject) NULL); if (!parseArgs(args, "j", Writer::class$, &writer)) { INT_CALL(self->object = PrintWriter(writer)); return 0; } PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } } } JCC-3.6/_jcc3/java/io/__init__.cpp0000644000076500000000000000220513121703266016740 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "macros.h" void installType(PyTypeObject **type, PyType_Def *def, PyObject *module, char *name, int isExtension); namespace java { namespace io { DECLARE_TYPE(Writer); DECLARE_TYPE(StringWriter); DECLARE_TYPE(PrintWriter); namespace reflect { void __install__(PyObject *module); } void __install__(PyObject *m) { INSTALL_TYPE(Writer, m); INSTALL_TYPE(StringWriter, m); INSTALL_TYPE(PrintWriter, m); } } } JCC-3.6/_jcc3/java/io/StringWriter.h0000644000076500000000000000272313121703253017312 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _StringWriter_H #define _StringWriter_H #include #include "java/lang/Class.h" #include "java/io/Writer.h" namespace java { namespace io { class StringWriter : public Writer { public: static java::lang::Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit StringWriter(jobject obj) : Writer(obj) { initializeClass(false); } StringWriter(); StringWriter(const StringWriter& obj) : Writer(obj) {} }; DECLARE_TYPE(StringWriter); class t_StringWriter { public: PyObject_HEAD StringWriter object; static PyObject *wrap_Object(const StringWriter& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _StringWriter_H */ JCC-3.6/_jcc3/java/io/StringWriter.cpp0000644000076500000000000000535213122243327017650 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/io/StringWriter.h" namespace java { namespace io { enum { mid__init_, max_mid }; java::lang::Class *StringWriter::class$ = NULL; jmethodID *StringWriter::_mids = NULL; jclass StringWriter::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/io/StringWriter"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "()V"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } StringWriter::StringWriter() : Writer(env->newObject(initializeClass, &_mids, mid__init_)) { } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace io { static int t_StringWriter_init(t_StringWriter *self, PyObject *args, PyObject *kwds); static PyMethodDef t_StringWriter__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(StringWriter)[] = { { Py_tp_methods, t_StringWriter__methods_ }, { Py_tp_init, (void *) t_StringWriter_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(StringWriter)[] = { &PY_TYPE_DEF(Writer), NULL }; DEFINE_TYPE(StringWriter, t_StringWriter, java::io::StringWriter); static int t_StringWriter_init(t_StringWriter *self, PyObject *args, PyObject *kwds) { switch (PyTuple_Size(args)) { case 0: INT_CALL(self->object = StringWriter()); break; default: PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } return 0; } } } JCC-3.6/_jcc3/java/io/Writer.h0000644000076500000000000000251413121703260016117 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Writer_H #define _Writer_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace io { class Writer : public java::lang::Object { public: static java::lang::Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Writer(jobject obj) : Object(obj) { initializeClass(false); } }; DECLARE_TYPE(Writer); class t_Writer { public: PyObject_HEAD Writer object; static PyObject *wrap_Object(const Writer& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Writer_H */ JCC-3.6/_jcc3/java/io/PrintWriter.h0000644000076500000000000000272413121703246017143 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _PrintWriter_H #define _PrintWriter_H #include #include "java/lang/Class.h" #include "java/io/Writer.h" namespace java { namespace io { class PrintWriter : public Writer { public: static java::lang::Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit PrintWriter(jobject obj) : Writer(obj) { initializeClass(false); } PrintWriter(Writer writer); PrintWriter(const PrintWriter& obj) : Writer(obj) {} }; DECLARE_TYPE(PrintWriter); class t_PrintWriter { public: PyObject_HEAD PrintWriter object; static PyObject *wrap_Object(const PrintWriter& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _PrintWriter_H */ JCC-3.6/_jcc3/java/io/Writer.cpp0000644000076500000000000000357013122243336016461 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/io/Writer.h" namespace java { namespace io { enum { max_mid }; java::lang::Class *Writer::class$ = NULL; jmethodID *Writer::_mids = NULL; jclass Writer::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/io/Writer"); _mids = NULL; class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace io { static PyMethodDef t_Writer__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Writer)[] = { { Py_tp_methods, t_Writer__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Writer)[] = { &PY_TYPE_DEF(java::lang::Object), NULL }; DEFINE_TYPE(Writer, t_Writer, java::io::Writer); } } JCC-3.6/_jcc3/java/lang/0000755000076500000000000000000013536235634015021 5ustar vajdawheel00000000000000JCC-3.6/_jcc3/java/lang/RuntimeException.h0000644000076500000000000000265513121703067020472 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _RuntimeException_H #define _RuntimeException_H #include #include "java/lang/Class.h" #include "java/lang/Exception.h" #include "JArray.h" namespace java { namespace lang { class RuntimeException : public Exception { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit RuntimeException(jobject obj) : Exception(obj) { initializeClass(false); } }; DECLARE_TYPE(RuntimeException); class t_RuntimeException { public: PyObject_HEAD RuntimeException object; static PyObject *wrap_Object(const RuntimeException& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _RuntimeException_H */ JCC-3.6/_jcc3/java/lang/Float.h0000644000076500000000000000256013121703047016226 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Float_H #define _Float_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Float : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Float(jobject obj) : Object(obj) { initializeClass(false); } Float(jfloat); jfloat floatValue() const; }; DECLARE_TYPE(Float); class t_Float { public: PyObject_HEAD Float object; static PyObject *wrap_Object(const Float& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Float_H */ JCC-3.6/_jcc3/java/lang/Short.h0000644000076500000000000000256013121703073016257 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Short_H #define _Short_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Short : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Short(jobject obj) : Object(obj) { initializeClass(false); } Short(jshort); jshort shortValue() const; }; DECLARE_TYPE(Short); class t_Short { public: PyObject_HEAD Short object; static PyObject *wrap_Object(const Short& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Short_H */ JCC-3.6/_jcc3/java/lang/Throwable.cpp0000644000076500000000000001004513122243445017442 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "java/lang/Throwable.h" #include "java/io/PrintWriter.h" namespace java { namespace lang { enum { mid_printStackTrace_0, mid_printStackTrace_1, mid_getMessage, max_mid }; Class *Throwable::class$ = NULL; jmethodID *Throwable::_mids = NULL; jclass Throwable::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Throwable"); _mids = new jmethodID[max_mid]; _mids[mid_printStackTrace_0] = env->getMethodID(cls, "printStackTrace", "()V"); _mids[mid_printStackTrace_1] = env->getMethodID(cls, "printStackTrace", "(Ljava/io/PrintWriter;)V"); _mids[mid_getMessage] = env->getMethodID(cls, "getMessage", "()Ljava/lang/String;"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } void Throwable::printStackTrace() const { env->callVoidMethod(this$, _mids[mid_printStackTrace_0]); } void Throwable::printStackTrace(java::io::PrintWriter writer) const { env->callVoidMethod(this$, _mids[mid_printStackTrace_1], writer.this$); } String Throwable::getMessage() const { return String(env->callObjectMethod(this$, _mids[mid_getMessage])); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyObject *t_Throwable_printStackTrace(t_Throwable *self, PyObject *args); static PyMethodDef t_Throwable__methods_[] = { DECLARE_METHOD(t_Throwable, printStackTrace, METH_VARARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Throwable)[] = { { Py_tp_methods, t_Throwable__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Throwable)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Throwable, t_Throwable, Throwable); static PyObject *t_Throwable_printStackTrace(t_Throwable *self, PyObject *args) { switch (PyTuple_Size(args)) { case 0: OBJ_CALL(self->object.printStackTrace()); Py_RETURN_NONE; case 1: { java::io::PrintWriter writer((jobject) NULL); if (!parseArgs(args, "j", java::io::PrintWriter::class$, &writer)) { OBJ_CALL(self->object.printStackTrace(writer)); Py_RETURN_NONE; } } default: PyErr_SetString(PyExc_ValueError, "invalid args"); return NULL; } } } } JCC-3.6/_jcc3/java/lang/Exception.cpp0000644000076500000000000000354713122243412017454 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Exception.h" namespace java { namespace lang { enum { max_mid }; Class *Exception::class$ = NULL; jmethodID *Exception::_mids = NULL; jclass Exception::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Exception"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Exception__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Exception)[] = { { Py_tp_methods, t_Exception__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Exception)[] = { &PY_TYPE_DEF(Throwable), NULL }; DEFINE_TYPE(Exception, t_Exception, java::lang::Exception); } } JCC-3.6/_jcc3/java/lang/Long.cpp0000644000076500000000000000445113122243425016414 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Long.h" namespace java { namespace lang { enum { mid__init_, mid_longValue, max_mid }; Class *Long::class$ = NULL; jmethodID *Long::_mids = NULL; jclass Long::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Long"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(J)V"); _mids[mid_longValue] = env->getMethodID(cls, "longValue", "()J"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Long::Long(jlong n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jlong Long::longValue() const { return env->callLongMethod(this$, _mids[mid_longValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Long__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Long)[] = { { Py_tp_methods, t_Long__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Long)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Long, t_Long, java::lang::Long); } } JCC-3.6/_jcc3/java/lang/Character.cpp0000644000076500000000000000456413122243376017423 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Character.h" namespace java { namespace lang { enum { mid__init_, mid_charValue, max_mid }; Class *Character::class$ = NULL; jmethodID *Character::_mids = NULL; jclass Character::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Character"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(C)V"); _mids[mid_charValue] = env->getMethodID(cls, "charValue", "()C"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Character::Character(jchar c) : Object(env->newObject(initializeClass, &_mids, mid__init_, c)) { } jchar Character::charValue() const { return env->callCharMethod(this$, _mids[mid_charValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Character__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Character)[] = { { Py_tp_methods, t_Character__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Character)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Character, t_Character, java::lang::Character); } } JCC-3.6/_jcc3/java/lang/__init__.cpp0000644000076500000000000000362313121703221017246 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "macros.h" void installType(PyTypeObject **type, PyType_Def *def, PyObject *module, char *name, int isExtension); namespace java { namespace lang { DECLARE_TYPE(Object); DECLARE_TYPE(String); DECLARE_TYPE(Class); DECLARE_TYPE(Throwable); DECLARE_TYPE(Exception); DECLARE_TYPE(RuntimeException); DECLARE_TYPE(Boolean); DECLARE_TYPE(Byte); DECLARE_TYPE(Character); DECLARE_TYPE(Integer); DECLARE_TYPE(Double); DECLARE_TYPE(Float); DECLARE_TYPE(Long); DECLARE_TYPE(Short); namespace reflect { void __install__(PyObject *module); } void __install__(PyObject *m) { INSTALL_TYPE(Object, m); INSTALL_TYPE(String, m); INSTALL_TYPE(Class, m); INSTALL_TYPE(Throwable, m); INSTALL_TYPE(Exception, m); INSTALL_TYPE(RuntimeException, m); INSTALL_TYPE(Boolean, m); INSTALL_TYPE(Byte, m); INSTALL_TYPE(Character, m); INSTALL_TYPE(Double, m); INSTALL_TYPE(Float, m); INSTALL_TYPE(Integer, m); INSTALL_TYPE(Long, m); INSTALL_TYPE(Short, m); reflect::__install__(m); } } } JCC-3.6/_jcc3/java/lang/Object.cpp0000644000076500000000000001134613122243430016720 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" namespace java { namespace lang { enum { mid__init_, mid_toString, mid_getClass, mid_hashCode, mid_equals, max_mid }; Class *Object::class$ = NULL; jmethodID *Object::mids$ = NULL; jclass Object::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Object"); mids$ = new jmethodID[max_mid]; mids$[mid__init_] = env->getMethodID(cls, "", "()V"); mids$[mid_toString] = env->getMethodID(cls, "toString", "()Ljava/lang/String;"); mids$[mid_getClass] = env->getMethodID(cls, "getClass", "()Ljava/lang/Class;"); mids$[mid_hashCode] = env->getMethodID(cls, "hashCode", "()I"); mids$[mid_equals] = env->getMethodID(cls, "equals", "(Ljava/lang/Object;)Z"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Object::Object() : JObject(env->newObject(initializeClass, &mids$, mid__init_)) { } String Object::toString() const { return String(env->callObjectMethod(this$, mids$[mid_toString])); } Class Object::getClass() const { return Class(env->callObjectMethod(this$, mids$[mid_getClass])); } int Object::hashCode() const { return env->callIntMethod(this$, mids$[mid_hashCode]); } jboolean Object::equals(const Object& a0) const { return env->callBooleanMethod(this$, mids$[mid_equals], a0.this$); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static int t_Object_init(t_Object *self, PyObject *args, PyObject *kwds); static PyObject *t_Object_getClass(t_Object *self); static PyObject *t_Object_equals(t_Object *self, PyObject *arg); static PyMethodDef t_Object__methods_[] = { DECLARE_METHOD(t_Object, getClass, METH_NOARGS), DECLARE_METHOD(t_Object, equals, METH_O), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Object)[] = { { Py_tp_methods, t_Object__methods_ }, { Py_tp_init, (void *) t_Object_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Object)[] = { &PY_TYPE_DEF(JObject), NULL }; DEFINE_TYPE(Object, t_Object, java::lang::Object); static int t_Object_init(t_Object *self, PyObject *args, PyObject *kwds) { switch (PyTuple_Size(args)) { case 0: INT_CALL(self->object = Object()); break; default: PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } return 0; } static PyObject *t_Object_getClass(t_Object *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Object_equals(t_Object *self, PyObject *arg) { Object a0((jobject) NULL); jboolean result; if (!parseArg(arg, "o", &a0)) { OBJ_CALL(result = self->object.equals(a0)); Py_RETURN_BOOL(result); } PyErr_SetArgsError((PyObject *) self, "equals", arg); return NULL; } } } JCC-3.6/_jcc3/java/lang/Byte.cpp0000644000076500000000000000445113122243370016417 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Byte.h" namespace java { namespace lang { enum { mid__init_, mid_byteValue, max_mid }; Class *Byte::class$ = NULL; jmethodID *Byte::_mids = NULL; jclass Byte::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Byte"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(B)V"); _mids[mid_byteValue] = env->getMethodID(cls, "byteValue", "()B"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Byte::Byte(jbyte b) : Object(env->newObject(initializeClass, &_mids, mid__init_, b)) { } jbyte Byte::byteValue() const { return env->callByteMethod(this$, _mids[mid_byteValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Byte__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Byte)[] = { { Py_tp_methods, t_Byte__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Byte)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Byte, t_Byte, java::lang::Byte); } } JCC-3.6/_jcc3/java/lang/reflect/0000755000076500000000000000000013536235634016445 5ustar vajdawheel00000000000000JCC-3.6/_jcc3/java/lang/reflect/Type.h0000644000076500000000000000225713121703162017527 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_Type_H #define java_lang_reflect_Type_H #include "java/lang/Object.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class Type : public java::lang::Object { public: static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Type(jobject obj) : java::lang::Object(obj) { if (obj != NULL) initializeClass(false); } Type(const Type& obj) : java::lang::Object(obj) {} }; } } } #include namespace java { namespace lang { namespace reflect { DECLARE_TYPE(Type); class t_Type { public: PyObject_HEAD Type object; static PyObject *wrap_Object(const Type&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/TypeVariable.h0000644000076500000000000000344213121703166021176 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_TypeVariable_H #define java_lang_reflect_TypeVariable_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { namespace reflect { class GenericDeclaration; } class Class; class String; } } template class JArray; namespace java { namespace lang { namespace reflect { class TypeVariable : public java::lang::reflect::Type { public: enum { mid_getBounds_6f565a00, mid_getGenericDeclaration_2dc62edd, mid_getName_14c7b5c5, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit TypeVariable(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } TypeVariable(const TypeVariable& obj) : java::lang::reflect::Type(obj) {} JArray getBounds() const; java::lang::reflect::GenericDeclaration getGenericDeclaration() const; java::lang::String getName() const; }; } } } #include namespace java { namespace lang { namespace reflect { DECLARE_TYPE(TypeVariable); class t_TypeVariable { public: PyObject_HEAD TypeVariable object; static PyObject *wrap_Object(const TypeVariable&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/WildcardType.cpp0000644000076500000000000001025513122243504021531 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/WildcardType.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *WildcardType::class$ = NULL; jmethodID *WildcardType::mids$ = NULL; jclass WildcardType::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/WildcardType"); mids$ = new jmethodID[max_mid]; mids$[mid_getLowerBounds_6f565a00] = env->getMethodID(cls, "getLowerBounds", "()[Ljava/lang/reflect/Type;"); mids$[mid_getUpperBounds_6f565a00] = env->getMethodID(cls, "getUpperBounds", "()[Ljava/lang/reflect/Type;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray WildcardType::getLowerBounds() const { return JArray(env->callObjectMethod(this$, mids$[mid_getLowerBounds_6f565a00])); } JArray WildcardType::getUpperBounds() const { return JArray(env->callObjectMethod(this$, mids$[mid_getUpperBounds_6f565a00])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_WildcardType_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_WildcardType_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_WildcardType_getLowerBounds(t_WildcardType *self); static PyObject *t_WildcardType_getUpperBounds(t_WildcardType *self); static PyMethodDef t_WildcardType__methods_[] = { DECLARE_METHOD(t_WildcardType, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_WildcardType, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_WildcardType, getLowerBounds, METH_NOARGS), DECLARE_METHOD(t_WildcardType, getUpperBounds, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(WildcardType)[] = { { Py_tp_methods, t_WildcardType__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(WildcardType)[] = { &PY_TYPE_DEF(java::lang::reflect::Type), NULL }; DEFINE_TYPE(WildcardType, t_WildcardType, WildcardType); static PyObject *t_WildcardType_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, WildcardType::initializeClass, 1))) return NULL; return t_WildcardType::wrap_Object(WildcardType(((t_WildcardType *) arg)->object.this$)); } static PyObject *t_WildcardType_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, WildcardType::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_WildcardType_getLowerBounds(t_WildcardType *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getLowerBounds()); return result.toSequence(java::lang::reflect::t_Type::wrap_Object); } static PyObject *t_WildcardType_getUpperBounds(t_WildcardType *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getUpperBounds()); return result.toSequence(java::lang::reflect::t_Type::wrap_Object); } } } } #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/GenericArrayType.cpp0000644000076500000000000000675113122243460022362 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/GenericArrayType.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *GenericArrayType::class$ = NULL; jmethodID *GenericArrayType::mids$ = NULL; jclass GenericArrayType::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/GenericArrayType"); mids$ = new jmethodID[max_mid]; mids$[mid_getGenericComponentType_86037cf0] = env->getMethodID(cls, "getGenericComponentType", "()Ljava/lang/reflect/Type;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } java::lang::reflect::Type GenericArrayType::getGenericComponentType() const { return java::lang::reflect::Type(env->callObjectMethod(this$, mids$[mid_getGenericComponentType_86037cf0])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_GenericArrayType_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericArrayType_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericArrayType_getGenericComponentType(t_GenericArrayType *self); static PyMethodDef t_GenericArrayType__methods_[] = { DECLARE_METHOD(t_GenericArrayType, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericArrayType, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericArrayType, getGenericComponentType, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(GenericArrayType)[] = { { Py_tp_methods, t_GenericArrayType__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(GenericArrayType)[] = { &PY_TYPE_DEF(java::lang::reflect::Type), NULL }; DEFINE_TYPE(GenericArrayType, t_GenericArrayType, GenericArrayType); static PyObject *t_GenericArrayType_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, GenericArrayType::initializeClass, 1))) return NULL; return t_GenericArrayType::wrap_Object(GenericArrayType(((t_GenericArrayType *) arg)->object.this$)); } static PyObject *t_GenericArrayType_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, GenericArrayType::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_GenericArrayType_getGenericComponentType(t_GenericArrayType *self) { java::lang::reflect::Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericComponentType()); return java::lang::reflect::t_Type::wrap_Object(result); } } } } #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/ParameterizedType.h0000644000076500000000000000337113121703155022244 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_ParameterizedType_H #define java_lang_reflect_ParameterizedType_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class ParameterizedType : public java::lang::reflect::Type { public: enum { mid_getActualTypeArguments_6f565a00, mid_getOwnerType_86037cf0, mid_getRawType_86037cf0, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit ParameterizedType(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } ParameterizedType(const ParameterizedType& obj) : java::lang::reflect::Type(obj) {} JArray getActualTypeArguments() const; java::lang::reflect::Type getOwnerType() const; java::lang::reflect::Type getRawType() const; }; } } } #include namespace java { namespace lang { namespace reflect { DECLARE_TYPE(ParameterizedType); class t_ParameterizedType { public: PyObject_HEAD ParameterizedType object; static PyObject *wrap_Object(const ParameterizedType&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/Modifier.cpp0000644000076500000000000002341513122243471020701 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Modifier.h" namespace java { namespace lang { namespace reflect { enum { mid_isPublic, mid_isStatic, mid_isNative, mid_isFinal, mid_isAbstract, mid_isPrivate, mid_isProtected, max_mid }; Class *Modifier::class$ = NULL; jmethodID *Modifier::_mids = NULL; jclass Modifier::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Modifier"); _mids = new jmethodID[max_mid]; _mids[mid_isPublic] = env->getStaticMethodID(cls, "isPublic", "(I)Z"); _mids[mid_isStatic] = env->getStaticMethodID(cls, "isStatic", "(I)Z"); _mids[mid_isNative] = env->getStaticMethodID(cls, "isNative", "(I)Z"); _mids[mid_isFinal] = env->getStaticMethodID(cls, "isFinal", "(I)Z"); _mids[mid_isAbstract] = env->getStaticMethodID(cls, "isAbstract", "(I)Z"); _mids[mid_isPrivate] = env->getStaticMethodID(cls, "isPrivate", "(I)Z"); _mids[mid_isProtected] = env->getStaticMethodID(cls, "isProtected", "(I)Z"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Modifier::isPublic(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isPublic], mod); } int Modifier::isStatic(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isStatic], mod); } int Modifier::isNative(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isNative], mod); } int Modifier::isFinal(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isFinal], mod); } int Modifier::isAbstract(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isAbstract], mod); } int Modifier::isPrivate(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isPrivate], mod); } int Modifier::isProtected(int mod) { jclass cls = env->getClass(initializeClass); return (int) env->callStaticBooleanMethod(cls, _mids[mid_isProtected], mod); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Modifier_isPublic(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isStatic(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isNative(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isFinal(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isAbstract(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isPrivate(PyTypeObject *type, PyObject *arg); static PyObject *t_Modifier_isProtected(PyTypeObject *type, PyObject *arg); static PyMethodDef t_Modifier__methods_[] = { DECLARE_METHOD(t_Modifier, isPublic, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isStatic, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isNative, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isFinal, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isAbstract, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isPrivate, METH_O | METH_CLASS), DECLARE_METHOD(t_Modifier, isProtected, METH_O | METH_CLASS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Modifier)[] = { { Py_tp_methods, t_Modifier__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Modifier)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Modifier, t_Modifier, Modifier); static PyObject *t_Modifier_isPublic(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isPublic; if (PyErr_Occurred()) return NULL; OBJ_CALL(isPublic = Modifier::isPublic(mod)); Py_RETURN_BOOL(isPublic); } static PyObject *t_Modifier_isStatic(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isStatic; if (PyErr_Occurred()) return NULL; OBJ_CALL(isStatic = Modifier::isStatic(mod)); Py_RETURN_BOOL(isStatic); } static PyObject *t_Modifier_isNative(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isNative; if (PyErr_Occurred()) return NULL; OBJ_CALL(isNative = Modifier::isNative(mod)); Py_RETURN_BOOL(isNative); } static PyObject *t_Modifier_isFinal(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isFinal; if (PyErr_Occurred()) return NULL; OBJ_CALL(isFinal = Modifier::isFinal(mod)); Py_RETURN_BOOL(isFinal); } static PyObject *t_Modifier_isAbstract(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isAbstract; if (PyErr_Occurred()) return NULL; OBJ_CALL(isAbstract = Modifier::isAbstract(mod)); Py_RETURN_BOOL(isAbstract); } static PyObject *t_Modifier_isPrivate(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isPrivate; if (PyErr_Occurred()) return NULL; OBJ_CALL(isPrivate = Modifier::isPrivate(mod)); Py_RETURN_BOOL(isPrivate); } static PyObject *t_Modifier_isProtected(PyTypeObject *type, PyObject *arg) { if (!PyLong_Check(arg)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } int mod = PyLong_AsLong(arg); int isProtected; if (PyErr_Occurred()) return NULL; OBJ_CALL(isProtected = Modifier::isProtected(mod)); Py_RETURN_BOOL(isProtected); } } } } JCC-3.6/_jcc3/java/lang/reflect/Field.h0000644000076500000000000000327213121703131017623 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Field_H #define _Field_H #include namespace java { namespace lang { class Class; class String; namespace reflect { #ifdef _java_generics class Type; #endif class Field : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Field(jobject obj) : Object(obj) { initializeClass(false); } Field(const Field& obj) : Object(obj) {} int getModifiers() const; Class getType() const; String getName() const; #ifdef _java_generics Type getGenericType() const; #endif }; DECLARE_TYPE(Field); class t_Field { public: PyObject_HEAD Field object; static PyObject *wrap_Object(const Field& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Field_H */ JCC-3.6/_jcc3/java/lang/reflect/__init__.cpp0000644000076500000000000000341513121703205020673 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "macros.h" void installType(PyTypeObject **type, PyType_Def *def, PyObject *module, char *name, int isExtension); namespace java { namespace lang { namespace reflect { DECLARE_TYPE(Constructor); DECLARE_TYPE(Method); DECLARE_TYPE(Modifier); DECLARE_TYPE(Field); #ifdef _java_generics DECLARE_TYPE(Type); DECLARE_TYPE(ParameterizedType); DECLARE_TYPE(TypeVariable); DECLARE_TYPE(GenericArrayType); DECLARE_TYPE(WildcardType); DECLARE_TYPE(GenericDeclaration); #endif void __install__(PyObject *m) { INSTALL_TYPE(Constructor, m); INSTALL_TYPE(Method, m); INSTALL_TYPE(Modifier, m); INSTALL_TYPE(Field, m); #ifdef _java_generics INSTALL_TYPE(Type, m); INSTALL_TYPE(ParameterizedType, m); INSTALL_TYPE(TypeVariable, m); INSTALL_TYPE(GenericArrayType, m); INSTALL_TYPE(WildcardType, m); INSTALL_TYPE(GenericDeclaration, m); #endif } } } } JCC-3.6/_jcc3/java/lang/reflect/Method.h0000644000076500000000000000426713121703146020033 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Method_H #define _Method_H #include #include "JArray.h" namespace java { namespace lang { class Class; class String; namespace reflect { #ifdef _java_generics class Type; class TypeVariable; #endif class Method : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Method(jobject obj) : Object(obj) { initializeClass(false); } Method(const Method& obj) : Object(obj) {} int getModifiers() const; Class getReturnType() const; String getName() const; JArray getParameterTypes() const; JArray getExceptionTypes() const; Class getDeclaringClass() const; bool isSynthetic() const; bool isBridge() const; #ifdef _java_generics JArray getTypeParameters() const; JArray getGenericExceptionTypes() const; JArray getGenericParameterTypes() const; Type getGenericReturnType() const; #endif }; DECLARE_TYPE(Method); class t_Method { public: PyObject_HEAD Method object; static PyObject *wrap_Object(const Method& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Method_H */ JCC-3.6/_jcc3/java/lang/reflect/Constructor.cpp0000644000076500000000000001747413457454727021523 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "JArray.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Constructor.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #include "java/lang/reflect/TypeVariable.h" #endif namespace java { namespace lang { namespace reflect { enum { mid_getModifiers, mid_getSignature, mid_getParameterTypes, mid_getExceptionTypes, #ifdef _java_generics mid_getTypeParameters, mid_getGenericExceptionTypes, mid_getGenericParameterTypes, #endif max_mid }; Class *Constructor::class$ = NULL; jmethodID *Constructor::_mids = NULL; jclass Constructor::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Constructor"); _mids = new jmethodID[max_mid]; _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_getParameterTypes] = env->getMethodID(cls, "getParameterTypes", "()[Ljava/lang/Class;"); _mids[mid_getExceptionTypes] = env->getMethodID(cls, "getExceptionTypes", "()[Ljava/lang/Class;"); #ifdef _java_generics _mids[mid_getTypeParameters] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); _mids[mid_getGenericExceptionTypes] = env->getMethodID(cls, "getGenericExceptionTypes", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericParameterTypes] = env->getMethodID(cls, "getGenericParameterTypes", "()[Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Constructor::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } JArray Constructor::getParameterTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getParameterTypes]); return JArray(array); } JArray Constructor::getExceptionTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getExceptionTypes]); return JArray(array); } #ifdef _java_generics JArray Constructor::getTypeParameters() const { return JArray(env->callObjectMethod(this$, _mids[mid_getTypeParameters])); } JArray Constructor::getGenericExceptionTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericExceptionTypes])); } JArray Constructor::getGenericParameterTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericParameterTypes])); } #endif } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Constructor_getModifiers(t_Constructor *self); static PyObject *t_Constructor_getParameterTypes(t_Constructor *self); static PyObject *t_Constructor_getExceptionTypes(t_Constructor *self); #ifdef _java_generics static PyObject *t_Constructor_getTypeParameters(t_Constructor *self); static PyObject *t_Constructor_getGenericExceptionTypes(t_Constructor *self); static PyObject *t_Constructor_getGenericParameterTypes(t_Constructor *self); #endif static PyMethodDef t_Constructor__methods_[] = { DECLARE_METHOD(t_Constructor, getModifiers, METH_NOARGS), DECLARE_METHOD(t_Constructor, getParameterTypes, METH_NOARGS), DECLARE_METHOD(t_Constructor, getExceptionTypes, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Constructor, getTypeParameters, METH_NOARGS), DECLARE_METHOD(t_Constructor, getGenericExceptionTypes, METH_NOARGS), DECLARE_METHOD(t_Constructor, getGenericParameterTypes, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Constructor)[] = { { Py_tp_methods, t_Constructor__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Constructor)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Constructor, t_Constructor, Constructor); static PyObject *t_Constructor_getModifiers(t_Constructor *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyLong_FromLong(modifiers); } static PyObject *t_Constructor_getParameterTypes(t_Constructor *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getParameterTypes()); return types.toSequence(t_Class::wrap_Object); } static PyObject *t_Constructor_getExceptionTypes(t_Constructor *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getExceptionTypes()); return types.toSequence(t_Class::wrap_Object); } #ifdef _java_generics static PyObject *t_Constructor_getTypeParameters(t_Constructor *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } static PyObject *t_Constructor_getGenericExceptionTypes(t_Constructor *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericExceptionTypes()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Constructor_getGenericParameterTypes(t_Constructor *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericParameterTypes()); return result.toSequence(t_Type::wrap_Object); } #endif } } } JCC-3.6/_jcc3/java/lang/reflect/Constructor.h0000644000076500000000000000374413457454727021163 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Constructor_H #define _Constructor_H #include #include "JArray.h" namespace java { namespace lang { class Class; class String; namespace reflect { #ifdef _java_generics class Type; class TypeVariable; #endif class Constructor : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Constructor(jobject obj) : Object(obj) { initializeClass(false); } Constructor(const Constructor& obj) : Object(obj) {} int getModifiers() const; JArray getParameterTypes() const; JArray getExceptionTypes() const; #ifdef _java_generics JArray getTypeParameters() const; JArray getGenericExceptionTypes() const; JArray getGenericParameterTypes() const; #endif }; DECLARE_TYPE(Constructor); class t_Constructor { public: PyObject_HEAD Constructor object; static PyObject *wrap_Object(const Constructor& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Constructor_H */ JCC-3.6/_jcc3/java/lang/reflect/ParameterizedType.cpp0000644000076500000000000001223613122243473022602 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/ParameterizedType.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *ParameterizedType::class$ = NULL; jmethodID *ParameterizedType::mids$ = NULL; jclass ParameterizedType::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/ParameterizedType"); mids$ = new jmethodID[max_mid]; mids$[mid_getActualTypeArguments_6f565a00] = env->getMethodID(cls, "getActualTypeArguments", "()[Ljava/lang/reflect/Type;"); mids$[mid_getOwnerType_86037cf0] = env->getMethodID(cls, "getOwnerType", "()Ljava/lang/reflect/Type;"); mids$[mid_getRawType_86037cf0] = env->getMethodID(cls, "getRawType", "()Ljava/lang/reflect/Type;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray ParameterizedType::getActualTypeArguments() const { return JArray(env->callObjectMethod(this$, mids$[mid_getActualTypeArguments_6f565a00])); } java::lang::reflect::Type ParameterizedType::getOwnerType() const { return java::lang::reflect::Type(env->callObjectMethod(this$, mids$[mid_getOwnerType_86037cf0])); } java::lang::reflect::Type ParameterizedType::getRawType() const { return java::lang::reflect::Type(env->callObjectMethod(this$, mids$[mid_getRawType_86037cf0])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_ParameterizedType_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_ParameterizedType_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_ParameterizedType_getActualTypeArguments(t_ParameterizedType *self); static PyObject *t_ParameterizedType_getOwnerType(t_ParameterizedType *self); static PyObject *t_ParameterizedType_getRawType(t_ParameterizedType *self); static PyMethodDef t_ParameterizedType__methods_[] = { DECLARE_METHOD(t_ParameterizedType, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_ParameterizedType, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_ParameterizedType, getActualTypeArguments, METH_NOARGS), DECLARE_METHOD(t_ParameterizedType, getOwnerType, METH_NOARGS), DECLARE_METHOD(t_ParameterizedType, getRawType, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(ParameterizedType)[] = { { Py_tp_methods, t_ParameterizedType__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(ParameterizedType)[] = { &PY_TYPE_DEF(java::lang::reflect::Type), NULL }; DEFINE_TYPE(ParameterizedType, t_ParameterizedType, ParameterizedType); static PyObject *t_ParameterizedType_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, ParameterizedType::initializeClass, 1))) return NULL; return t_ParameterizedType::wrap_Object(ParameterizedType(((t_ParameterizedType *) arg)->object.this$)); } static PyObject *t_ParameterizedType_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, ParameterizedType::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_ParameterizedType_getActualTypeArguments(t_ParameterizedType *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getActualTypeArguments()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_ParameterizedType_getOwnerType(t_ParameterizedType *self) { java::lang::reflect::Type result((jobject) NULL); OBJ_CALL(result = self->object.getOwnerType()); return java::lang::reflect::t_Type::wrap_Object(result); } static PyObject *t_ParameterizedType_getRawType(t_ParameterizedType *self) { java::lang::reflect::Type result((jobject) NULL); OBJ_CALL(result = self->object.getRawType()); return java::lang::reflect::t_Type::wrap_Object(result); } } } } #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/GenericDeclaration.cpp0000644000076500000000000000710713122243463022666 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/GenericDeclaration.h" #include "java/lang/Class.h" #include "java/lang/reflect/TypeVariable.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *GenericDeclaration::class$ = NULL; jmethodID *GenericDeclaration::mids$ = NULL; jclass GenericDeclaration::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/GenericDeclaration"); mids$ = new jmethodID[max_mid]; mids$[mid_getTypeParameters_837d3468] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray GenericDeclaration::getTypeParameters() const { return JArray(env->callObjectMethod(this$, mids$[mid_getTypeParameters_837d3468])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_GenericDeclaration_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericDeclaration_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_GenericDeclaration_getTypeParameters(t_GenericDeclaration *self); static PyMethodDef t_GenericDeclaration__methods_[] = { DECLARE_METHOD(t_GenericDeclaration, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericDeclaration, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_GenericDeclaration, getTypeParameters, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(GenericDeclaration)[] = { { Py_tp_methods, t_GenericDeclaration__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(GenericDeclaration)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(GenericDeclaration, t_GenericDeclaration, GenericDeclaration); static PyObject *t_GenericDeclaration_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, GenericDeclaration::initializeClass, 1))) return NULL; return t_GenericDeclaration::wrap_Object(GenericDeclaration(((t_GenericDeclaration *) arg)->object.this$)); } static PyObject *t_GenericDeclaration_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, GenericDeclaration::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_GenericDeclaration_getTypeParameters(t_GenericDeclaration *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } } } } #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/Field.cpp0000644000076500000000000001221513122243455020164 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Field.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #endif namespace java { namespace lang { namespace reflect { enum { mid_getModifiers, mid_getType, mid_getName, #ifdef _java_generics mid_getGenericType, #endif max_mid }; Class *Field::class$ = NULL; jmethodID *Field::_mids = NULL; jclass Field::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Field"); _mids = new jmethodID[max_mid]; _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_getType] = env->getMethodID(cls, "getType", "()Ljava/lang/Class;"); _mids[mid_getName] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); #ifdef _java_generics _mids[mid_getGenericType] = env->getMethodID(cls, "getGenericType", "()Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Field::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } Class Field::getType() const { return Class(env->callObjectMethod(this$, _mids[mid_getType])); } String Field::getName() const { return String(env->callObjectMethod(this$, _mids[mid_getName])); } #ifdef _java_generics Type Field::getGenericType() const { return Type(env->callObjectMethod(this$, _mids[mid_getGenericType])); } #endif } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Field_getModifiers(t_Field *self); static PyObject *t_Field_getType(t_Field *self); static PyObject *t_Field_getName(t_Field *self); #ifdef _java_generics static PyObject *t_Field_getGenericType(t_Field *self); #endif static PyMethodDef t_Field__methods_[] = { DECLARE_METHOD(t_Field, getModifiers, METH_NOARGS), DECLARE_METHOD(t_Field, getType, METH_NOARGS), DECLARE_METHOD(t_Field, getName, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Field, getGenericType, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Field)[] = { { Py_tp_methods, t_Field__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Field)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Field, t_Field, Field); static PyObject *t_Field_getModifiers(t_Field *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyLong_FromLong(modifiers); } static PyObject *t_Field_getType(t_Field *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getType()); return t_Class::wrap_Object(cls); } static PyObject *t_Field_getName(t_Field *self) { String name((jobject) NULL); OBJ_CALL(name = self->object.getName()); return j2p(name); } #ifdef _java_generics static PyObject *t_Field_getGenericType(t_Field *self) { Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericType()); return t_Type::wrap_Object(result); } #endif } } } JCC-3.6/_jcc3/java/lang/reflect/Method.cpp0000644000076500000000000003143513122243466020370 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "JArray.h" #include "java/lang/Class.h" #include "java/lang/Object.h" #include "java/lang/String.h" #include "java/lang/reflect/Method.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #include "java/lang/reflect/TypeVariable.h" #endif namespace java { namespace lang { namespace reflect { enum { mid_getModifiers, mid_getReturnType, mid_getName, mid_getParameterTypes, mid_getExceptionTypes, mid_getDeclaringClass, mid_isSynthetic, mid_isBridge, #ifdef _java_generics mid_getTypeParameters, mid_getGenericExceptionTypes, mid_getGenericParameterTypes, mid_getGenericReturnType, #endif max_mid }; Class *Method::class$ = NULL; jmethodID *Method::_mids = NULL; jclass Method::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/reflect/Method"); _mids = new jmethodID[max_mid]; _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_getReturnType] = env->getMethodID(cls, "getReturnType", "()Ljava/lang/Class;"); _mids[mid_getName] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); _mids[mid_getParameterTypes] = env->getMethodID(cls, "getParameterTypes", "()[Ljava/lang/Class;"); _mids[mid_getExceptionTypes] = env->getMethodID(cls, "getExceptionTypes", "()[Ljava/lang/Class;"); _mids[mid_getDeclaringClass] = env->getMethodID(cls, "getDeclaringClass", "()Ljava/lang/Class;"); _mids[mid_isSynthetic] = env->getMethodID(cls, "isSynthetic", "()Z"); _mids[mid_isBridge] = env->getMethodID(cls, "isBridge", "()Z"); #ifdef _java_generics _mids[mid_getTypeParameters] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); _mids[mid_getGenericExceptionTypes] = env->getMethodID(cls, "getGenericExceptionTypes", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericParameterTypes] = env->getMethodID(cls, "getGenericParameterTypes", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericReturnType] = env->getMethodID(cls, "getGenericReturnType", "()Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } int Method::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } Class Method::getReturnType() const { return Class(env->callObjectMethod(this$, _mids[mid_getReturnType])); } String Method::getName() const { return String(env->callObjectMethod(this$, _mids[mid_getName])); } JArray Method::getParameterTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getParameterTypes]); return JArray(array); } JArray Method::getExceptionTypes() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getExceptionTypes]); return JArray(array); } Class Method::getDeclaringClass() const { return Class(env->callObjectMethod(this$, _mids[mid_getDeclaringClass])); } bool Method::isSynthetic() const { return env->callBooleanMethod(this$, _mids[mid_isSynthetic]); } bool Method::isBridge() const { return env->callBooleanMethod(this$, _mids[mid_isBridge]); } #ifdef _java_generics JArray Method::getTypeParameters() const { return JArray(env->callObjectMethod(this$, _mids[mid_getTypeParameters])); } JArray Method::getGenericExceptionTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericExceptionTypes])); } JArray Method::getGenericParameterTypes() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericParameterTypes])); } Type Method::getGenericReturnType() const { return Type(env->callObjectMethod(this$, _mids[mid_getGenericReturnType])); } #endif } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Method_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_Method_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_Method_getModifiers(t_Method *self); static PyObject *t_Method_getReturnType(t_Method *self); static PyObject *t_Method_getName(t_Method *self); static PyObject *t_Method_getParameterTypes(t_Method *self); static PyObject *t_Method_getExceptionTypes(t_Method *self); static PyObject *t_Method_getDeclaringClass(t_Method *self); static PyObject *t_Method_isSynthetic(t_Method *self); static PyObject *t_Method_isBridge(t_Method *self); #ifdef _java_generics static PyObject *t_Method_getTypeParameters(t_Method *self); static PyObject *t_Method_getGenericExceptionTypes(t_Method *self); static PyObject *t_Method_getGenericParameterTypes(t_Method *self); static PyObject *t_Method_getGenericReturnType(t_Method *self); #endif static PyMethodDef t_Method__methods_[] = { DECLARE_METHOD(t_Method, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_Method, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_Method, getModifiers, METH_NOARGS), DECLARE_METHOD(t_Method, getReturnType, METH_NOARGS), DECLARE_METHOD(t_Method, getName, METH_NOARGS), DECLARE_METHOD(t_Method, getParameterTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getExceptionTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getDeclaringClass, METH_NOARGS), DECLARE_METHOD(t_Method, isSynthetic, METH_NOARGS), DECLARE_METHOD(t_Method, isBridge, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Method, getTypeParameters, METH_NOARGS), DECLARE_METHOD(t_Method, getGenericExceptionTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getGenericParameterTypes, METH_NOARGS), DECLARE_METHOD(t_Method, getGenericReturnType, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Method)[] = { { Py_tp_methods, t_Method__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Method)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Method, t_Method, Method); static PyObject *t_Method_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, Method::initializeClass, 1))) return NULL; return t_Method::wrap_Object(Method(((t_Method *) arg)->object.this$)); } static PyObject *t_Method_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, Method::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_Method_getModifiers(t_Method *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyLong_FromLong(modifiers); } static PyObject *t_Method_getReturnType(t_Method *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getReturnType()); return t_Class::wrap_Object(cls); } static PyObject *t_Method_getName(t_Method *self) { String name((jobject) NULL); OBJ_CALL(name = self->object.getName()); return j2p(name); } static PyObject *t_Method_getParameterTypes(t_Method *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getParameterTypes()); return types.toSequence(t_Class::wrap_Object); } static PyObject *t_Method_getExceptionTypes(t_Method *self) { JArray types((jobject) NULL); OBJ_CALL(types = self->object.getExceptionTypes()); return types.toSequence(t_Class::wrap_Object); } static PyObject *t_Method_getDeclaringClass(t_Method *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getDeclaringClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Method_isSynthetic(t_Method *self) { int isSynthetic; OBJ_CALL(isSynthetic = self->object.isSynthetic()); Py_RETURN_BOOL(isSynthetic); } static PyObject *t_Method_isBridge(t_Method *self) { int isBridge; OBJ_CALL(isBridge = self->object.isBridge()); Py_RETURN_BOOL(isBridge); } #ifdef _java_generics static PyObject *t_Method_getTypeParameters(t_Method *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } static PyObject *t_Method_getGenericExceptionTypes(t_Method *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericExceptionTypes()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Method_getGenericParameterTypes(t_Method *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericParameterTypes()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Method_getGenericReturnType(t_Method *self) { Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericReturnType()); return t_Type::wrap_Object(result); } #endif } } } JCC-3.6/_jcc3/java/lang/reflect/GenericArrayType.h0000644000076500000000000000301713121703136022017 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_GenericArrayType_H #define java_lang_reflect_GenericArrayType_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class GenericArrayType : public java::lang::reflect::Type { public: enum { mid_getGenericComponentType_86037cf0, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit GenericArrayType(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } GenericArrayType(const GenericArrayType& obj) : java::lang::reflect::Type(obj) {} java::lang::reflect::Type getGenericComponentType() const; }; } } } #include namespace java { namespace lang { namespace reflect { DECLARE_TYPE(GenericArrayType); class t_GenericArrayType { public: PyObject_HEAD GenericArrayType object; static PyObject *wrap_Object(const GenericArrayType&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/TypeVariable.cpp0000644000076500000000000001172713122243501021527 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/TypeVariable.h" #include "java/lang/reflect/GenericDeclaration.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *TypeVariable::class$ = NULL; jmethodID *TypeVariable::mids$ = NULL; jclass TypeVariable::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/TypeVariable"); mids$ = new jmethodID[max_mid]; mids$[mid_getBounds_6f565a00] = env->getMethodID(cls, "getBounds", "()[Ljava/lang/reflect/Type;"); mids$[mid_getGenericDeclaration_2dc62edd] = env->getMethodID(cls, "getGenericDeclaration", "()Ljava/lang/reflect/GenericDeclaration;"); mids$[mid_getName_14c7b5c5] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } JArray TypeVariable::getBounds() const { return JArray(env->callObjectMethod(this$, mids$[mid_getBounds_6f565a00])); } java::lang::reflect::GenericDeclaration TypeVariable::getGenericDeclaration() const { return java::lang::reflect::GenericDeclaration(env->callObjectMethod(this$, mids$[mid_getGenericDeclaration_2dc62edd])); } java::lang::String TypeVariable::getName() const { return java::lang::String(env->callObjectMethod(this$, mids$[mid_getName_14c7b5c5])); } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_TypeVariable_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_TypeVariable_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_TypeVariable_getBounds(t_TypeVariable *self); static PyObject *t_TypeVariable_getGenericDeclaration(t_TypeVariable *self); static PyObject *t_TypeVariable_getName(t_TypeVariable *self); static PyMethodDef t_TypeVariable__methods_[] = { DECLARE_METHOD(t_TypeVariable, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_TypeVariable, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_TypeVariable, getBounds, METH_NOARGS), DECLARE_METHOD(t_TypeVariable, getGenericDeclaration, METH_NOARGS), DECLARE_METHOD(t_TypeVariable, getName, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(TypeVariable)[] = { { Py_tp_methods, t_TypeVariable__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(TypeVariable)[] = { &PY_TYPE_DEF(java::lang::reflect::Type), NULL }; DEFINE_TYPE(TypeVariable, t_TypeVariable, TypeVariable); static PyObject *t_TypeVariable_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, TypeVariable::initializeClass, 1))) return NULL; return t_TypeVariable::wrap_Object(TypeVariable(((t_TypeVariable *) arg)->object.this$)); } static PyObject *t_TypeVariable_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, TypeVariable::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_TypeVariable_getBounds(t_TypeVariable *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getBounds()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_TypeVariable_getGenericDeclaration(t_TypeVariable *self) { java::lang::reflect::GenericDeclaration result((jobject) NULL); OBJ_CALL(result = self->object.getGenericDeclaration()); return java::lang::reflect::t_GenericDeclaration::wrap_Object(result); } static PyObject *t_TypeVariable_getName(t_TypeVariable *self) { java::lang::String result((jobject) NULL); OBJ_CALL(result = self->object.getName()); return j2p(result); } } } } #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/GenericDeclaration.h0000644000076500000000000000312213121703141022315 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_GenericDeclaration_H #define java_lang_reflect_GenericDeclaration_H #include "java/lang/Object.h" namespace java { namespace lang { namespace reflect { class TypeVariable; } class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class GenericDeclaration : public java::lang::Object { public: enum { mid_getTypeParameters_837d3468, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit GenericDeclaration(jobject obj) : java::lang::Object(obj) { if (obj != NULL) initializeClass(false); } GenericDeclaration(const GenericDeclaration& obj) : java::lang::Object(obj) {} JArray getTypeParameters() const; }; } } } #include namespace java { namespace lang { namespace reflect { DECLARE_TYPE(GenericDeclaration); class t_GenericDeclaration { public: PyObject_HEAD GenericDeclaration object; static PyObject *wrap_Object(const GenericDeclaration&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/Modifier.h0000644000076500000000000000346713121703152020347 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Modifier_H #define _Modifier_H #include #include "JArray.h" namespace java { namespace lang { class Class; class String; namespace reflect { class Modifier : public Object { private: explicit Modifier(); public: explicit Modifier(jobject obj) : Object(obj) { initializeClass(false); } static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); static int isPublic(int mod); static int isStatic(int mod); static int isNative(int mod); static int isFinal(int mod); static int isAbstract(int mod); static int isPrivate(int mod); static int isProtected(int mod); }; DECLARE_TYPE(Modifier); class t_Modifier { public: PyObject_HEAD Modifier object; static PyObject *wrap_Object(const Modifier& object); static PyObject *wrap_jobject(const jobject& object); }; } } } #endif /* _Modifier_H */ JCC-3.6/_jcc3/java/lang/reflect/WildcardType.h0000644000076500000000000000312713121703172021177 0ustar vajdawheel00000000000000#ifdef _java_generics #ifndef java_lang_reflect_WildcardType_H #define java_lang_reflect_WildcardType_H #include "java/lang/reflect/Type.h" namespace java { namespace lang { class Class; } } template class JArray; namespace java { namespace lang { namespace reflect { class WildcardType : public java::lang::reflect::Type { public: enum { mid_getLowerBounds_6f565a00, mid_getUpperBounds_6f565a00, max_mid }; static java::lang::Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit WildcardType(jobject obj) : java::lang::reflect::Type(obj) { if (obj != NULL) initializeClass(false); } WildcardType(const WildcardType& obj) : java::lang::reflect::Type(obj) {} JArray getLowerBounds() const; JArray getUpperBounds() const; }; } } } #include namespace java { namespace lang { namespace reflect { DECLARE_TYPE(WildcardType); class t_WildcardType { public: PyObject_HEAD WildcardType object; static PyObject *wrap_Object(const WildcardType&); static PyObject *wrap_jobject(const jobject&); }; } } } #endif #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/reflect/Type.cpp0000644000076500000000000000436713122243476020076 0ustar vajdawheel00000000000000#ifdef _java_generics #include #include "JCCEnv.h" #include "java/lang/reflect/Type.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { namespace reflect { java::lang::Class *Type::class$ = NULL; jmethodID *Type::mids$ = NULL; jclass Type::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = (jclass) env->findClass("java/lang/reflect/Type"); class$ = (java::lang::Class *) new JObject(cls); } return (jclass) class$->this$; } } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { namespace reflect { static PyObject *t_Type_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_Type_instance_(PyTypeObject *type, PyObject *arg); static PyMethodDef t_Type__methods_[] = { DECLARE_METHOD(t_Type, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_Type, instance_, METH_O | METH_CLASS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Type)[] = { { Py_tp_methods, t_Type__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Type)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Type, t_Type, Type); static PyObject *t_Type_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, Type::initializeClass, 1))) return NULL; return t_Type::wrap_Object(Type(((t_Type *) arg)->object.this$)); } static PyObject *t_Type_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, Type::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } } } } #endif /* _java_generics */ JCC-3.6/_jcc3/java/lang/String.cpp0000644000076500000000000000727413122243442016770 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" namespace java { namespace lang { enum { mid__init_, mid_toString, mid_length, max_mid }; Class *String::class$ = NULL; jmethodID *String::_mids = NULL; jclass String::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/String"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "()V"); _mids[mid_toString] = env->getMethodID(cls, "toString", "()Ljava/lang/String;"); _mids[mid_length] = env->getMethodID(cls, "length", "()I"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } String::String() : Object(env->newObject(initializeClass, &_mids, mid__init_)) { } int String::length() const { return env->callIntMethod(this$, _mids[mid_length]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static int t_String_init(t_String *self, PyObject *args, PyObject *kwds); static PyObject *t_String_length(t_String *self); static PyMethodDef t_String__methods_[] = { DECLARE_METHOD(t_String, length, METH_NOARGS), { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(String)[] = { { Py_tp_methods, t_String__methods_ }, { Py_tp_init, (void *) t_String_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(String)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(String, t_String, java::lang::String); static int t_String_init(t_String *self, PyObject *args, PyObject *kwds) { char *bytes; switch (PyTuple_Size(args)) { case 0: INT_CALL(self->object = String()); break; case 1: if (!PyArg_ParseTuple(args, "s", &bytes)) return -1; INT_CALL(self->object = String( env->get_vm_env()->NewStringUTF(bytes))); break; default: PyErr_SetString(PyExc_ValueError, "invalid args"); return -1; } return 0; } static PyObject *t_String_length(t_String *self) { jint length; OBJ_CALL(length = self->object.length()); return PyLong_FromLong(length); } } } JCC-3.6/_jcc3/java/lang/Long.h0000644000076500000000000000254313121703057016062 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Long_H #define _Long_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Long : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Long(jobject obj) : Object(obj) { initializeClass(false); } Long(jlong); jlong longValue() const; }; DECLARE_TYPE(Long); class t_Long { public: PyObject_HEAD Long object; static PyObject *wrap_Object(const Long& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Long_H */ JCC-3.6/_jcc3/java/lang/Character.h0000644000076500000000000000262513121703020017046 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Character_H #define _Character_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Character : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Character(jobject obj) : Object(obj) { initializeClass(false); } Character(jchar); jchar charValue() const; }; DECLARE_TYPE(Character); class t_Character { public: PyObject_HEAD Character object; static PyObject *wrap_Object(const Character& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Character_H */ JCC-3.6/_jcc3/java/lang/Boolean.h0000644000076500000000000000271313121702672016543 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Boolean_H #define _Boolean_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Boolean : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Boolean(jobject obj) : Object(obj) { initializeClass(false); } Boolean(jboolean); int booleanValue() const; static Boolean *TRUE; static Boolean *FALSE; }; DECLARE_TYPE(Boolean); class t_Boolean { public: PyObject_HEAD Boolean object; static PyObject *wrap_Object(const Boolean& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Boolean_H */ JCC-3.6/_jcc3/java/lang/RuntimeException.cpp0000644000076500000000000000375613122243434021026 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/RuntimeException.h" namespace java { namespace lang { enum { mid_printStackTrace, max_mid }; Class *RuntimeException::class$ = NULL; jmethodID *RuntimeException::_mids = NULL; jclass RuntimeException::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/RuntimeException"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_RuntimeException__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(RuntimeException)[] = { { Py_tp_methods, t_RuntimeException__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(RuntimeException)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(RuntimeException, t_RuntimeException, java::lang::RuntimeException); } } JCC-3.6/_jcc3/java/lang/Float.cpp0000644000076500000000000000450013122243416016555 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Float.h" namespace java { namespace lang { enum { mid__init_, mid_floatValue, max_mid }; Class *Float::class$ = NULL; jmethodID *Float::_mids = NULL; jclass Float::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Float"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(F)V"); _mids[mid_floatValue] = env->getMethodID(cls, "floatValue", "()F"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Float::Float(jfloat f) : Object(env->newObject(initializeClass, &_mids, mid__init_, f)) { } jfloat Float::floatValue() const { return env->callFloatMethod(this$, _mids[mid_floatValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Float__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Float)[] = { { Py_tp_methods, t_Float__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Float)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Float, t_Float, java::lang::Float); } } JCC-3.6/_jcc3/java/lang/Throwable.h0000644000076500000000000000310213121703103017072 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Throwable_H #define _Throwable_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace io { class PrintWriter; } namespace lang { class String; class Throwable : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Throwable(jobject obj) : Object(obj) { initializeClass(false); } void printStackTrace() const; void printStackTrace(java::io::PrintWriter) const; String getMessage() const; }; DECLARE_TYPE(Throwable); class t_Throwable { public: PyObject_HEAD Throwable object; static PyObject *wrap_Object(const Throwable& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Throwable_H */ JCC-3.6/_jcc3/java/lang/Short.cpp0000644000076500000000000000450013122243437016612 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Short.h" namespace java { namespace lang { enum { mid__init_, mid_shortValue, max_mid }; Class *Short::class$ = NULL; jmethodID *Short::_mids = NULL; jclass Short::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Short"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(S)V"); _mids[mid_shortValue] = env->getMethodID(cls, "shortValue", "()S"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Short::Short(jshort n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jshort Short::shortValue() const { return env->callShortMethod(this$, _mids[mid_shortValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Short__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Short)[] = { { Py_tp_methods, t_Short__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Short)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Short, t_Short, java::lang::Short); } } JCC-3.6/_jcc3/java/lang/Class.h0000644000076500000000000000612513121703031016220 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Class_H #define _Class_H #include #include "JArray.h" #include "java/lang/Object.h" namespace java { namespace lang { namespace reflect { class Method; class Constructor; class Field; #ifdef _java_generics class Type; class TypeVariable; #endif } using namespace reflect; class Class : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Class(jobject obj) : Object(obj) { initializeClass(false); } Class(const Class& obj) : Object(obj) {} static Class forName(const String& className); JArray getDeclaredMethods() const; JArray getMethods() const; Method getMethod(const String &name, const JArray& params) const; Method getDeclaredMethod(const String &name, const JArray& params) const; JArray getDeclaredConstructors() const; JArray getDeclaredFields() const; JArray getDeclaredClasses() const; int isArray() const; int isPrimitive() const; int isInterface() const; int isAssignableFrom(const Class& obj) const; Class getComponentType() const; Class getSuperclass() const; Class getDeclaringClass() const; Class getEnclosingClass() const; JArray getInterfaces() const; String getName() const; int getModifiers() const; int isInstance(const Object &obj) const; #ifdef _java_generics JArray getTypeParameters() const; JArray getGenericInterfaces() const; Type getGenericSuperclass() const; #endif }; DECLARE_TYPE(Class); class t_Class { public: PyObject_HEAD Class object; #ifdef _java_generics PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_Class *self) { return (PyTypeObject **) &(self->parameters); } #endif static PyObject *wrap_Object(const Class& object); #ifdef _java_generics static PyObject *wrap_Object(const Class& object, PyTypeObject *T); #endif static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Class_H */ JCC-3.6/_jcc3/java/lang/Double.h0000644000076500000000000000257513121703036016377 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Double_H #define _Double_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Double : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Double(jobject obj) : Object(obj) { initializeClass(false); } Double(jdouble); jdouble doubleValue() const; }; DECLARE_TYPE(Double); class t_Double { public: PyObject_HEAD Double object; static PyObject *wrap_Object(const Double& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Double_H */ JCC-3.6/_jcc3/java/lang/Object.h0000644000076500000000000000277713121703063016377 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Object_H #define _Object_H #include #include "JObject.h" namespace java { namespace lang { class Class; class String; class Object : public JObject { public: static Class *class$; static jmethodID *mids$; static jclass initializeClass(bool); explicit Object(); explicit Object(jobject obj) : JObject(obj) { initializeClass(false); } String toString() const; Class getClass() const; int hashCode() const; jboolean equals(const Object& obj) const; }; DECLARE_TYPE(Object); class t_Object { public: PyObject_HEAD Object object; static PyObject *wrap_Object(const Object& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Object_H */ JCC-3.6/_jcc3/java/lang/Integer.cpp0000644000076500000000000000451613122243422017111 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Integer.h" namespace java { namespace lang { enum { mid__init_, mid_intValue, max_mid }; Class *Integer::class$ = NULL; jmethodID *Integer::_mids = NULL; jclass Integer::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Integer"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(I)V"); _mids[mid_intValue] = env->getMethodID(cls, "intValue", "()I"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Integer::Integer(jint n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jint Integer::intValue() const { return env->callIntMethod(this$, _mids[mid_intValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Integer__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Integer)[] = { { Py_tp_methods, t_Integer__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Integer)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Integer, t_Integer, java::lang::Integer); } } JCC-3.6/_jcc3/java/lang/Class.cpp0000644000076500000000000005443213122243402016561 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "JArray.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "java/lang/reflect/Method.h" #include "java/lang/reflect/Constructor.h" #include "java/lang/reflect/Field.h" #ifdef _java_generics #include "java/lang/reflect/Type.h" #include "java/lang/reflect/TypeVariable.h" #endif namespace java { namespace lang { using namespace reflect; enum { mid_forName, mid_getDeclaredMethods, mid_getMethods, mid_getMethod, mid_getDeclaredMethod, mid_getDeclaredConstructors, mid_getDeclaredFields, mid_getDeclaredClasses, mid_isArray, mid_isPrimitive, mid_isInterface, mid_isAssignableFrom, mid_getComponentType, mid_getSuperclass, mid_getDeclaringClass, mid_getEnclosingClass, mid_getInterfaces, mid_getName, mid_getModifiers, mid_isInstance, #ifdef _java_generics mid_getTypeParameters, mid_getGenericInterfaces, mid_getGenericSuperclass, #endif max_mid }; Class *Class::class$ = NULL; jmethodID *Class::_mids = NULL; jclass Class::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Class"); _mids = new jmethodID[max_mid]; _mids[mid_forName] = env->getStaticMethodID(cls, "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); _mids[mid_getDeclaredMethods] = env->getMethodID(cls, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"); _mids[mid_getMethods] = env->getMethodID(cls, "getMethods", "()[Ljava/lang/reflect/Method;"); _mids[mid_getMethod] = env->getMethodID(cls, "getMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"); _mids[mid_getDeclaredMethod] = env->getMethodID(cls, "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"); _mids[mid_getDeclaredConstructors] = env->getMethodID(cls, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"); _mids[mid_getDeclaredFields] = env->getMethodID(cls, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"); _mids[mid_getDeclaredClasses] = env->getMethodID(cls, "getDeclaredClasses", "()[Ljava/lang/Class;"); _mids[mid_isArray] = env->getMethodID(cls, "isArray", "()Z"); _mids[mid_isPrimitive] = env->getMethodID(cls, "isPrimitive", "()Z"); _mids[mid_isInterface] = env->getMethodID(cls, "isInterface", "()Z"); _mids[mid_isAssignableFrom] = env->getMethodID(cls, "isAssignableFrom", "(Ljava/lang/Class;)Z"); _mids[mid_getComponentType] = env->getMethodID(cls, "getComponentType", "()Ljava/lang/Class;"); _mids[mid_getSuperclass] = env->getMethodID(cls, "getSuperclass", "()Ljava/lang/Class;"); _mids[mid_getDeclaringClass] = env->getMethodID(cls, "getDeclaringClass", "()Ljava/lang/Class;"); _mids[mid_getEnclosingClass] = env->getMethodID(cls, "getEnclosingClass", "()Ljava/lang/Class;"); _mids[mid_getInterfaces] = env->getMethodID(cls, "getInterfaces", "()[Ljava/lang/Class;"); _mids[mid_getName] = env->getMethodID(cls, "getName", "()Ljava/lang/String;"); _mids[mid_getModifiers] = env->getMethodID(cls, "getModifiers", "()I"); _mids[mid_isInstance] = env->getMethodID(cls, "isInstance", "(Ljava/lang/Object;)Z"); #ifdef _java_generics _mids[mid_getTypeParameters] = env->getMethodID(cls, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;"); _mids[mid_getGenericInterfaces] = env->getMethodID(cls, "getGenericInterfaces", "()[Ljava/lang/reflect/Type;"); _mids[mid_getGenericSuperclass] = env->getMethodID(cls, "getGenericSuperclass", "()Ljava/lang/reflect/Type;"); #endif class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Class Class::forName(const String& className) { jclass cls = initializeClass(false); jobject obj = env->callStaticObjectMethod(cls, _mids[mid_forName], className.this$); return Class((jclass) obj); } JArray Class::getDeclaredMethods() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredMethods]); return JArray(array); } JArray Class::getMethods() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getMethods]); return JArray(array); } Method Class::getMethod(const String& name, const JArray& params) const { return Method(env->callObjectMethod(this$, _mids[mid_getMethod], name.this$, params.this$)); } Method Class::getDeclaredMethod(const String& name, const JArray& params) const { return Method(env->callObjectMethod(this$, _mids[mid_getDeclaredMethod], name.this$, params.this$)); } JArray Class::getDeclaredConstructors() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredConstructors]); return JArray(array); } JArray Class::getDeclaredFields() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredFields]); return JArray(array); } JArray Class::getDeclaredClasses() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getDeclaredClasses]); return JArray(array); } int Class::isArray() const { return (int) env->callBooleanMethod(this$, _mids[mid_isArray]); } int Class::isPrimitive() const { return (int) env->callBooleanMethod(this$, _mids[mid_isPrimitive]); } int Class::isInterface() const { return (int) env->callBooleanMethod(this$, _mids[mid_isInterface]); } int Class::isAssignableFrom(const Class& obj) const { return (int) env->callBooleanMethod(this$, _mids[mid_isAssignableFrom], obj.this$); } Class Class::getComponentType() const { return Class(env->callObjectMethod(this$, _mids[mid_getComponentType])); } Class Class::getSuperclass() const { return Class(env->callObjectMethod(this$, _mids[mid_getSuperclass])); } Class Class::getDeclaringClass() const { return Class(env->callObjectMethod(this$, _mids[mid_getDeclaringClass])); } Class Class::getEnclosingClass() const { return Class(env->callObjectMethod(this$, _mids[mid_getEnclosingClass])); } JArray Class::getInterfaces() const { jobjectArray array = (jobjectArray) env->callObjectMethod(this$, _mids[mid_getInterfaces]); return JArray(array); } String Class::getName() const { return String(env->callObjectMethod(this$, _mids[mid_getName])); } int Class::getModifiers() const { return env->callIntMethod(this$, _mids[mid_getModifiers]); } int Class::isInstance(const Object &obj) const { return env->callBooleanMethod(this$, _mids[mid_isInstance], obj.this$); } #ifdef _java_generics JArray Class::getTypeParameters() const { return JArray(env->callObjectMethod(this$, _mids[mid_getTypeParameters])); } JArray Class::getGenericInterfaces() const { return JArray(env->callObjectMethod(this$, _mids[mid_getGenericInterfaces])); } Type Class::getGenericSuperclass() const { return Type(env->callObjectMethod(this$, _mids[mid_getGenericSuperclass])); } #endif } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { using namespace reflect; static PyObject *t_Class_cast_(PyTypeObject *type, PyObject *arg); static PyObject *t_Class_instance_(PyTypeObject *type, PyObject *arg); static PyObject *t_Class_forName(PyTypeObject *type, PyObject *arg); static PyObject *t_Class_getDeclaredConstructors(t_Class *self); static PyObject *t_Class_getDeclaredMethods(t_Class *self); static PyObject *t_Class_getMethods(t_Class *self); static PyObject *t_Class_getMethod(t_Class *self, PyObject *args); static PyObject *t_Class_getDeclaredMethod(t_Class *self, PyObject *args); static PyObject *t_Class_getDeclaredFields(t_Class *self); static PyObject *t_Class_getDeclaredClasses(t_Class *self); static PyObject *t_Class_isArray(t_Class *self); static PyObject *t_Class_isPrimitive(t_Class *self); static PyObject *t_Class_isInterface(t_Class *self); static PyObject *t_Class_isAssignableFrom(t_Class *self, PyObject *arg); static PyObject *t_Class_getComponentType(t_Class *self); static PyObject *t_Class_getSuperclass(t_Class *self); static PyObject *t_Class_getDeclaringClass(t_Class *self); static PyObject *t_Class_getEnclosingClass(t_Class *self); static PyObject *t_Class_getInterfaces(t_Class *self); static PyObject *t_Class_getName(t_Class *self); static PyObject *t_Class_getModifiers(t_Class *self); #ifdef _java_generics static PyObject *t_Class_getTypeParameters(t_Class *self); static PyObject *t_Class_getGenericInterfaces(t_Class *self); static PyObject *t_Class_getGenericSuperclass(t_Class *self); static PyObject *t_Class_get__parameters_(t_Class *self, void *data); static PyGetSetDef t_Class__fields_[] = { DECLARE_GET_FIELD(t_Class, parameters_), { NULL, NULL, NULL, NULL, NULL } }; #else static PyGetSetDef t_Class__fields_[] = { { NULL, NULL, NULL, NULL, NULL } }; #endif static PyMethodDef t_Class__methods_[] = { DECLARE_METHOD(t_Class, cast_, METH_O | METH_CLASS), DECLARE_METHOD(t_Class, instance_, METH_O | METH_CLASS), DECLARE_METHOD(t_Class, forName, METH_O | METH_CLASS), DECLARE_METHOD(t_Class, getDeclaredConstructors, METH_NOARGS), DECLARE_METHOD(t_Class, getDeclaredMethods, METH_NOARGS), DECLARE_METHOD(t_Class, getMethods, METH_NOARGS), DECLARE_METHOD(t_Class, getMethod, METH_VARARGS), DECLARE_METHOD(t_Class, getDeclaredMethod, METH_VARARGS), DECLARE_METHOD(t_Class, getDeclaredFields, METH_NOARGS), DECLARE_METHOD(t_Class, getDeclaredClasses, METH_NOARGS), DECLARE_METHOD(t_Class, isArray, METH_NOARGS), DECLARE_METHOD(t_Class, isPrimitive, METH_NOARGS), DECLARE_METHOD(t_Class, isInterface, METH_NOARGS), DECLARE_METHOD(t_Class, isAssignableFrom, METH_O), DECLARE_METHOD(t_Class, getComponentType, METH_NOARGS), DECLARE_METHOD(t_Class, getSuperclass, METH_NOARGS), DECLARE_METHOD(t_Class, getDeclaringClass, METH_NOARGS), DECLARE_METHOD(t_Class, getEnclosingClass, METH_NOARGS), DECLARE_METHOD(t_Class, getInterfaces, METH_NOARGS), DECLARE_METHOD(t_Class, getName, METH_NOARGS), DECLARE_METHOD(t_Class, getModifiers, METH_NOARGS), #ifdef _java_generics DECLARE_METHOD(t_Class, getTypeParameters, METH_NOARGS), DECLARE_METHOD(t_Class, getGenericInterfaces, METH_NOARGS), DECLARE_METHOD(t_Class, getGenericSuperclass, METH_NOARGS), #endif { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Class)[] = { { Py_tp_methods, t_Class__methods_ }, { Py_tp_init, (void *) abstract_init }, { Py_tp_getset, t_Class__fields_ }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Class)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Class, t_Class, java::lang::Class); #ifdef _java_generics PyObject *t_Class::wrap_Object(const Class& object, PyTypeObject *T) { PyObject *obj = t_Class::wrap_Object(object); if (obj != Py_None) { t_Class *self = (t_Class *) obj; self->parameters[0] = T; } return obj; } #endif static PyObject *t_Class_cast_(PyTypeObject *type, PyObject *arg) { if (!(arg = castCheck(arg, Class::initializeClass, 1))) return NULL; return t_Class::wrap_Object(Class(((t_Class *) arg)->object.this$)); } static PyObject *t_Class_instance_(PyTypeObject *type, PyObject *arg) { if (!castCheck(arg, Class::initializeClass, 0)) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject *t_Class_forName(PyTypeObject *type, PyObject *arg) { if (arg == Py_None) { PyErr_SetObject(PyExc_ValueError, arg); return NULL; } try { return t_Class::wrap_Object(Class::forName(p2j(arg))); } catch (int e) { switch (e) { case _EXC_JAVA: return PyErr_SetJavaError(); default: throw; } } } static PyObject *t_Class_getDeclaredConstructors(t_Class *self) { JArray constructors((jobject) NULL); OBJ_CALL(constructors = self->object.getDeclaredConstructors()); return constructors.toSequence(t_Constructor::wrap_Object); } static PyObject *t_Class_getDeclaredMethods(t_Class *self) { JArray methods((jobject) NULL); OBJ_CALL(methods = self->object.getDeclaredMethods()); return methods.toSequence(t_Method::wrap_Object); } static PyObject *t_Class_getMethods(t_Class *self) { JArray methods((jobject) NULL); OBJ_CALL(methods = self->object.getMethods()); return methods.toSequence(t_Method::wrap_Object); } static PyObject *t_Class_getMethod(t_Class *self, PyObject *args) { String name((jobject) NULL); JArray params((jobject) NULL); Method method((jobject) NULL); if (!parseArgs(args, "s[j", Class::class$, &name, ¶ms)) { OBJ_CALL(method = self->object.getMethod(name, params)); return t_Method::wrap_Object(method); } return PyErr_SetArgsError((PyObject *) self, "getMethod", args); } static PyObject *t_Class_getDeclaredMethod(t_Class *self, PyObject *args) { String name((jobject) NULL); JArray params((jobject) NULL); Method method((jobject) NULL); if (!parseArgs(args, "s[j", Class::class$, &name, ¶ms)) { OBJ_CALL(method = self->object.getDeclaredMethod(name, params)); return t_Method::wrap_Object(method); } return PyErr_SetArgsError((PyObject *) self, "getMethod", args); } static PyObject *t_Class_getDeclaredFields(t_Class *self) { JArray fields((jobject) NULL); OBJ_CALL(fields = self->object.getDeclaredFields()); return fields.toSequence(t_Field::wrap_Object); } static PyObject *t_Class_getDeclaredClasses(t_Class *self) { JArray array((jobject) NULL); OBJ_CALL(array = self->object.getDeclaredClasses()); return array.toSequence(t_Class::wrap_Object); } static PyObject *t_Class_isArray(t_Class *self) { int isArray; OBJ_CALL(isArray = self->object.isArray()); Py_RETURN_BOOL(isArray); } static PyObject *t_Class_isPrimitive(t_Class *self) { int isPrimitive; OBJ_CALL(isPrimitive = self->object.isPrimitive()); Py_RETURN_BOOL(isPrimitive); } static PyObject *t_Class_isInterface(t_Class *self) { int isInterface; OBJ_CALL(isInterface = self->object.isInterface()); Py_RETURN_BOOL(isInterface); } static PyObject *t_Class_isAssignableFrom(t_Class *self, PyObject *arg) { if (!PyObject_TypeCheck(arg, PY_TYPE(Class))) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } try { Class cls = ((t_Class *) arg)->object; int isAssignableFrom = self->object.isAssignableFrom(cls); Py_RETURN_BOOL(isAssignableFrom); } catch (int e) { switch (e) { case _EXC_JAVA: return PyErr_SetJavaError(); default: throw; } } } static PyObject *t_Class_getComponentType(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getComponentType()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getSuperclass(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getSuperclass()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getDeclaringClass(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getDeclaringClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getEnclosingClass(t_Class *self) { Class cls((jobject) NULL); OBJ_CALL(cls = self->object.getEnclosingClass()); return t_Class::wrap_Object(cls); } static PyObject *t_Class_getInterfaces(t_Class *self) { JArray interfaces((jobject) NULL); OBJ_CALL(interfaces = self->object.getInterfaces()); return interfaces.toSequence(t_Class::wrap_Object); } static PyObject *t_Class_getName(t_Class *self) { String name((jobject) NULL); OBJ_CALL(name = self->object.getName()); return j2p(name); } static PyObject *t_Class_getModifiers(t_Class *self) { jint modifiers; OBJ_CALL(modifiers = self->object.getModifiers()); return PyLong_FromLong(modifiers); } #ifdef _java_generics static PyObject *t_Class_getTypeParameters(t_Class *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getTypeParameters()); return result.toSequence(t_TypeVariable::wrap_Object); } static PyObject *t_Class_getGenericInterfaces(t_Class *self) { JArray result((jobject) NULL); OBJ_CALL(result = self->object.getGenericInterfaces()); return result.toSequence(t_Type::wrap_Object); } static PyObject *t_Class_getGenericSuperclass(t_Class *self) { Type result((jobject) NULL); OBJ_CALL(result = self->object.getGenericSuperclass()); return t_Type::wrap_Object(result); } static PyObject *t_Class_get__parameters_(t_Class *self, void *data) { return typeParameters(self->parameters, sizeof(self->parameters)); } #endif } } JCC-3.6/_jcc3/java/lang/Boolean.cpp0000644000076500000000000000521013122243362017066 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Boolean.h" namespace java { namespace lang { enum { mid__init_, mid_booleanValue, max_mid }; Class *Boolean::class$ = NULL; jmethodID *Boolean::_mids = NULL; Boolean *Boolean::TRUE = NULL; Boolean *Boolean::FALSE = NULL; jclass Boolean::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Boolean"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(Z)V"); _mids[mid_booleanValue] = env->getMethodID(cls, "booleanValue", "()Z"); class$ = (Class *) new JObject(cls); FALSE = new Boolean(env->getStaticObjectField(cls, "FALSE", "Ljava/lang/Boolean;")); TRUE = new Boolean(env->getStaticObjectField(cls, "TRUE", "Ljava/lang/Boolean;")); } return (jclass) class$->this$; } Boolean::Boolean(jboolean b) : Object(env->newObject(initializeClass, &_mids, mid__init_, b)) { } int Boolean::booleanValue() const { return (int) env->callBooleanMethod(this$, _mids[mid_booleanValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Boolean__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Boolean)[] = { { Py_tp_methods, t_Boolean__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Boolean)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Boolean, t_Boolean, java::lang::Boolean); } } JCC-3.6/_jcc3/java/lang/Exception.h0000644000076500000000000000255613121703043017120 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Exception_H #define _Exception_H #include #include "java/lang/Class.h" #include "java/lang/Throwable.h" #include "JArray.h" namespace java { namespace lang { class Exception : public Throwable { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Exception(jobject obj) : Throwable(obj) { initializeClass(false); } }; DECLARE_TYPE(Exception); class t_Exception { public: PyObject_HEAD Exception object; static PyObject *wrap_Object(const Exception& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Exception_H */ JCC-3.6/_jcc3/java/lang/Integer.h0000644000076500000000000000257613121703053016562 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Integer_H #define _Integer_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Integer : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Integer(jobject obj) : Object(obj) { initializeClass(false); } Integer(jint); jint intValue() const; }; DECLARE_TYPE(Integer); class t_Integer { public: PyObject_HEAD Integer object; static PyObject *wrap_Object(const Integer& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Integer_H */ JCC-3.6/_jcc3/java/lang/Double.cpp0000644000076500000000000000452713122243406016732 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/Double.h" namespace java { namespace lang { enum { mid__init_, mid_doubleValue, max_mid }; Class *Double::class$ = NULL; jmethodID *Double::_mids = NULL; jclass Double::initializeClass(bool getOnly) { if (getOnly) return (jclass) (class$ == NULL ? NULL : class$->this$); if (!class$) { jclass cls = env->findClass("java/lang/Double"); _mids = new jmethodID[max_mid]; _mids[mid__init_] = env->getMethodID(cls, "", "(D)V"); _mids[mid_doubleValue] = env->getMethodID(cls, "doubleValue", "()D"); class$ = (Class *) new JObject(cls); } return (jclass) class$->this$; } Double::Double(jdouble n) : Object(env->newObject(initializeClass, &_mids, mid__init_, n)) { } jdouble Double::doubleValue() const { return env->callDoubleMethod(this$, _mids[mid_doubleValue]); } } } #include "structmember.h" #include "functions.h" #include "macros.h" namespace java { namespace lang { static PyMethodDef t_Double__methods_[] = { { NULL, NULL, 0, NULL } }; static PyType_Slot PY_TYPE_SLOTS(Double)[] = { { Py_tp_methods, t_Double__methods_ }, { Py_tp_init, (void *) abstract_init }, { 0, 0 } }; static PyType_Def *PY_TYPE_BASES(Double)[] = { &PY_TYPE_DEF(Object), NULL }; DEFINE_TYPE(Double, t_Double, java::lang::Double); } } JCC-3.6/_jcc3/java/lang/Byte.h0000644000076500000000000000254313121703011016054 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _Byte_H #define _Byte_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" namespace java { namespace lang { class Byte : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit Byte(jobject obj) : Object(obj) { initializeClass(false); } Byte(jbyte); jbyte byteValue() const; }; DECLARE_TYPE(Byte); class t_Byte { public: PyObject_HEAD Byte object; static PyObject *wrap_Object(const Byte& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _Byte_H */ JCC-3.6/_jcc3/java/lang/String.h0000644000076500000000000000301213121703077016423 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _String_H #define _String_H #include #include "java/lang/Object.h" #include "java/lang/Class.h" #include "JArray.h" namespace java { namespace lang { class String : public Object { public: static Class *class$; static jmethodID *_mids; static jclass initializeClass(bool); explicit String(jobject obj) : Object(obj) { initializeClass(false); } String(); String(const String& obj) : Object(obj) {} String toString() const { return *this; } int length() const; }; DECLARE_TYPE(String); class t_String { public: PyObject_HEAD String object; static PyObject *wrap_Object(const String& object); static PyObject *wrap_jobject(const jobject& object); }; } } #endif /* _String_H */ JCC-3.6/jcc2/0000755000076500000000000000000013536235634013017 5ustar vajdawheel00000000000000JCC-3.6/jcc2/classes/0000755000076500000000000000000013536235634014454 5ustar vajdawheel00000000000000JCC-3.6/jcc2/classes/org/0000755000076500000000000000000013536235634015243 5ustar vajdawheel00000000000000JCC-3.6/jcc2/classes/org/apache/0000755000076500000000000000000013536235634016464 5ustar vajdawheel00000000000000JCC-3.6/jcc2/classes/org/apache/jcc/0000755000076500000000000000000013536235634017223 5ustar vajdawheel00000000000000JCC-3.6/jcc2/classes/org/apache/jcc/PythonVM.class0000644000076500000000000000176013503537046021776 0ustar vajdawheel00000000000000Êþº¾1. !" # $ % #& '()vmLorg/apache/jcc/PythonVM;start@(Ljava/lang/String;[Ljava/lang/String;)Lorg/apache/jcc/PythonVM;CodeLineNumberTable-(Ljava/lang/String;)Lorg/apache/jcc/PythonVM;get()Lorg/apache/jcc/PythonVM;()Vinit((Ljava/lang/String;[Ljava/lang/String;)V instantiate8(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; Exceptions*acquireThreadState()IreleaseThreadState SourceFile PythonVM.java org/apache/jcc/PythonVM   jcc+ ,-java/lang/Objectorg/apache/jcc/PythonExceptionjava/lang/System loadLibrary(Ljava/lang/String;)V!  @²Ç»Y·³²*+¶²°(*+. *¸°> ²°I!*·± MN"¸±  JCC-3.6/jcc2/classes/org/apache/jcc/PythonException.class0000644000076500000000000000174713503537046023417 0ustar vajdawheel00000000000000Êþº¾1; ' ( ) * + , -. / 01 2 3 456 withTraceZpy_error_stateJ(Ljava/lang/String;)VCodeLineNumberTablefinalize()V Exceptions7 getMessage(Z)Ljava/lang/String;()Ljava/lang/String; pythonDecRef getErrorNamegetErrorMessagegetErrorTracebacksaveErrorState SourceFilePythonException.java    $   "java/lang/StringBuilder  89 # : org/apache/jcc/PythonExceptionjava/lang/RuntimeExceptionjava/lang/Throwableappend-(Ljava/lang/String;)Ljava/lang/StringBuilder;toString! <*+·*µ* µ*¶± !*¶±  !`4*´ ”š*·°*¶M™»Y· ,¶  ¶ *¶ ¶ ¶ °,°% &(*+2-! **´¶°2 !"#$%&JCC-3.6/jcc2/patches/0000755000076500000000000000000013536235634014446 5ustar vajdawheel00000000000000JCC-3.6/jcc2/patches/patch.43.0.6c70000644000076500000000000001345613063017435016452 0ustar vajdawheel00000000000000Index: setuptools/extension.py =================================================================== --- setuptools/extension.py (revision 66382) +++ setuptools/extension.py (working copy) @@ -28,6 +28,11 @@ class Library(Extension): """Just like a regular Extension, but built as a library instead""" + def __init__(self, *args, **kwds): + self.force_shared = kwds.pop('force_shared', False) + Extension.__init__(self, *args, **kwds) + + import sys, distutils.core, distutils.extension distutils.core.Extension = Extension distutils.extension.Extension = Extension Index: setuptools/command/build_ext.py =================================================================== --- setuptools/command/build_ext.py (revision 66382) +++ setuptools/command/build_ext.py (working copy) @@ -84,8 +84,12 @@ filename = _build_ext.get_ext_filename(self,fullname) ext = self.ext_map[fullname] if isinstance(ext,Library): + if ext.force_shared and not use_stubs: + _libtype = 'shared' + else: + _libtype = libtype fn, ext = os.path.splitext(filename) - return self.shlib_compiler.library_filename(fn,libtype) + return self.shlib_compiler.library_filename(fn,_libtype) elif use_stubs and ext._links_to_dynamic: d,fn = os.path.split(filename) return os.path.join(d,'dl-'+fn) @@ -170,14 +174,22 @@ def build_extension(self, ext): _compiler = self.compiler try: + force_shared = False if isinstance(ext,Library): self.compiler = self.shlib_compiler + force_shared = ext.force_shared and not use_stubs + if force_shared: + self.compiler.link_shared_object = \ + sh_link_shared_object.__get__(self.compiler) _build_ext.build_extension(self,ext) if ext._needs_stub: self.write_stub( self.get_finalized_command('build_py').build_lib, ext ) finally: + if force_shared: + self.compiler.link_shared_object = \ + link_shared_object.__get__(self.compiler) self.compiler = _compiler def links_to_dynamic(self, ext): @@ -244,44 +256,41 @@ os.unlink(stub_file) -if use_stubs or os.name=='nt': - # Build shared libraries - # - def link_shared_object(self, objects, output_libname, output_dir=None, - libraries=None, library_dirs=None, runtime_library_dirs=None, - export_symbols=None, debug=0, extra_preargs=None, - extra_postargs=None, build_temp=None, target_lang=None - ): self.link( - self.SHARED_LIBRARY, objects, output_libname, - output_dir, libraries, library_dirs, runtime_library_dirs, - export_symbols, debug, extra_preargs, extra_postargs, - build_temp, target_lang - ) -else: - # Build static libraries everywhere else - libtype = 'static' +def sh_link_shared_object(self, objects, output_libname, output_dir=None, + libraries=None, library_dirs=None, runtime_library_dirs=None, + export_symbols=None, debug=0, extra_preargs=None, + extra_postargs=None, build_temp=None, target_lang=None +): self.link(self.SHARED_LIBRARY, objects, output_libname, + output_dir, libraries, library_dirs, runtime_library_dirs, + export_symbols, debug, extra_preargs, extra_postargs, + build_temp, target_lang) - def link_shared_object(self, objects, output_libname, output_dir=None, - libraries=None, library_dirs=None, runtime_library_dirs=None, - export_symbols=None, debug=0, extra_preargs=None, - extra_postargs=None, build_temp=None, target_lang=None - ): - # XXX we need to either disallow these attrs on Library instances, - # or warn/abort here if set, or something... - #libraries=None, library_dirs=None, runtime_library_dirs=None, - #export_symbols=None, extra_preargs=None, extra_postargs=None, - #build_temp=None +def st_link_shared_object(self, objects, output_libname, output_dir=None, + libraries=None, library_dirs=None, runtime_library_dirs=None, + export_symbols=None, debug=0, extra_preargs=None, + extra_postargs=None, build_temp=None, target_lang=None +): + # XXX we need to either disallow these attrs on Library instances, + # or warn/abort here if set, or something... + #libraries=None, library_dirs=None, runtime_library_dirs=None, + #export_symbols=None, extra_preargs=None, extra_postargs=None, + #build_temp=None - assert output_dir is None # distutils build_ext doesn't pass this - output_dir,filename = os.path.split(output_libname) - basename, ext = os.path.splitext(filename) - if self.library_filename("x").startswith('lib'): - # strip 'lib' prefix; this is kludgy if some platform uses - # a different prefix - basename = basename[3:] + assert output_dir is None # distutils build_ext doesn't pass this + output_dir,filename = os.path.split(output_libname) + basename, ext = os.path.splitext(filename) + if self.library_filename("x").startswith('lib'): + # strip 'lib' prefix; this is kludgy if some platform uses + # a different prefix + basename = basename[3:] - self.create_static_lib( - objects, basename, output_dir, debug, target_lang - ) + self.create_static_lib(objects, basename, output_dir, debug, target_lang) +if use_stubs or os.name=='nt': + # Build shared libraries + link_shared_object = sh_link_shared_object +else: + # Build static libraries everywhere else (unless force_shared) + libtype = 'static' + link_shared_object = st_link_shared_object JCC-3.6/jcc2/patches/patch.43.0.6c110000644000076500000000000001350513063017435016520 0ustar vajdawheel00000000000000Index: setuptools/extension.py =================================================================== --- setuptools/extension.py (revision 75864) +++ setuptools/extension.py (working copy) @@ -28,6 +28,11 @@ class Library(Extension): """Just like a regular Extension, but built as a library instead""" + def __init__(self, *args, **kwds): + self.force_shared = kwds.pop('force_shared', False) + Extension.__init__(self, *args, **kwds) + + import sys, distutils.core, distutils.extension distutils.core.Extension = Extension distutils.extension.Extension = Extension Index: setuptools/command/build_ext.py =================================================================== --- setuptools/command/build_ext.py (revision 75864) +++ setuptools/command/build_ext.py (working copy) @@ -85,8 +85,12 @@ if fullname in self.ext_map: ext = self.ext_map[fullname] if isinstance(ext,Library): + if ext.force_shared and not use_stubs: + _libtype = 'shared' + else: + _libtype = libtype fn, ext = os.path.splitext(filename) - return self.shlib_compiler.library_filename(fn,libtype) + return self.shlib_compiler.library_filename(fn,_libtype) elif use_stubs and ext._links_to_dynamic: d,fn = os.path.split(filename) return os.path.join(d,'dl-'+fn) @@ -170,14 +174,22 @@ def build_extension(self, ext): _compiler = self.compiler try: + force_shared = False if isinstance(ext,Library): self.compiler = self.shlib_compiler + force_shared = ext.force_shared and not use_stubs + if force_shared: + self.compiler.link_shared_object = \ + sh_link_shared_object.__get__(self.compiler) _build_ext.build_extension(self,ext) if ext._needs_stub: self.write_stub( self.get_finalized_command('build_py').build_lib, ext ) finally: + if force_shared: + self.compiler.link_shared_object = \ + link_shared_object.__get__(self.compiler) self.compiler = _compiler def links_to_dynamic(self, ext): @@ -244,44 +256,41 @@ os.unlink(stub_file) -if use_stubs or os.name=='nt': - # Build shared libraries - # - def link_shared_object(self, objects, output_libname, output_dir=None, - libraries=None, library_dirs=None, runtime_library_dirs=None, - export_symbols=None, debug=0, extra_preargs=None, - extra_postargs=None, build_temp=None, target_lang=None - ): self.link( - self.SHARED_LIBRARY, objects, output_libname, - output_dir, libraries, library_dirs, runtime_library_dirs, - export_symbols, debug, extra_preargs, extra_postargs, - build_temp, target_lang - ) -else: - # Build static libraries everywhere else - libtype = 'static' +def sh_link_shared_object(self, objects, output_libname, output_dir=None, + libraries=None, library_dirs=None, runtime_library_dirs=None, + export_symbols=None, debug=0, extra_preargs=None, + extra_postargs=None, build_temp=None, target_lang=None +): self.link(self.SHARED_LIBRARY, objects, output_libname, + output_dir, libraries, library_dirs, runtime_library_dirs, + export_symbols, debug, extra_preargs, extra_postargs, + build_temp, target_lang) - def link_shared_object(self, objects, output_libname, output_dir=None, - libraries=None, library_dirs=None, runtime_library_dirs=None, - export_symbols=None, debug=0, extra_preargs=None, - extra_postargs=None, build_temp=None, target_lang=None - ): - # XXX we need to either disallow these attrs on Library instances, - # or warn/abort here if set, or something... - #libraries=None, library_dirs=None, runtime_library_dirs=None, - #export_symbols=None, extra_preargs=None, extra_postargs=None, - #build_temp=None +def st_link_shared_object(self, objects, output_libname, output_dir=None, + libraries=None, library_dirs=None, runtime_library_dirs=None, + export_symbols=None, debug=0, extra_preargs=None, + extra_postargs=None, build_temp=None, target_lang=None +): + # XXX we need to either disallow these attrs on Library instances, + # or warn/abort here if set, or something... + #libraries=None, library_dirs=None, runtime_library_dirs=None, + #export_symbols=None, extra_preargs=None, extra_postargs=None, + #build_temp=None - assert output_dir is None # distutils build_ext doesn't pass this - output_dir,filename = os.path.split(output_libname) - basename, ext = os.path.splitext(filename) - if self.library_filename("x").startswith('lib'): - # strip 'lib' prefix; this is kludgy if some platform uses - # a different prefix - basename = basename[3:] + assert output_dir is None # distutils build_ext doesn't pass this + output_dir,filename = os.path.split(output_libname) + basename, ext = os.path.splitext(filename) + if self.library_filename("x").startswith('lib'): + # strip 'lib' prefix; this is kludgy if some platform uses + # a different prefix + basename = basename[3:] - self.create_static_lib( - objects, basename, output_dir, debug, target_lang - ) + self.create_static_lib(objects, basename, output_dir, debug, target_lang) +if use_stubs or os.name=='nt': + # Build shared libraries + link_shared_object = sh_link_shared_object +else: + # Build static libraries everywhere else (unless force_shared) + libtype = 'static' + link_shared_object = st_link_shared_object JCC-3.6/jcc2/patches/patch.41950000644000076500000000000000151213063017435016060 0ustar vajdawheel00000000000000--- runpy.py.old 2008-10-19 16:02:18.000000000 -0700 +++ runpy.py 2008-10-19 16:13:44.000000000 -0700 @@ -79,10 +79,13 @@ loader = get_loader(mod_name) if loader is None: raise ImportError("No module named %s" % mod_name) if loader.is_package(mod_name): - raise ImportError(("%s is a package and cannot " + - "be directly executed") % mod_name) + try: + return _get_module_details('.'.join((mod_name, '__main__'))) + except ImportError, e: + raise ImportError(("%s; %s is a package and cannot " + + "be directly executed") %(e, mod_name)) code = loader.get_code(mod_name) if code is None: raise ImportError("No code object available for %s" % mod_name) filename = _get_filename(loader, mod_name) JCC-3.6/jcc2/__init__.py0000644000076500000000000000246113067253217015127 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # jcc package import os, sys if sys.platform == 'win32': if '--find-jvm-dll' in sys.argv: from windows import add_jvm_dll_directory_to_path add_jvm_dll_directory_to_path() from jcc.config import SHARED if SHARED: path = os.environ['Path'].split(os.pathsep) eggpath = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if eggpath not in path: path.insert(0, eggpath) os.environ['Path'] = os.pathsep.join(path) from jcc import _jcc2 # used when jcc is invoked with -m from python 2.5 if __name__ == '__main__': import jcc.__main__ else: from _jcc2 import initVM CLASSPATH=os.path.join(os.path.abspath(os.path.dirname(__file__)), "classes") _jcc2.CLASSPATH = CLASSPATH JCC-3.6/jcc2/cpp.py0000644000076500000000000013241513457462571014165 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, sys, zipfile, _jcc2 from itertools import izip python_ver = '%d.%d.%d' %(sys.version_info[0:3]) if python_ver < '2.4': from sets import Set as set def split_pkg(string, sep): parts = string.split(sep) if len(parts) > 1: return sep.join(parts[:-1]), parts[-1] return parts def sort(list, fn=None, key=None): if fn: list.sort(fn) elif key: def fn(x, y): return cmp(key(x), key(y)) list.sort(fn) else: list.sort() else: def split_pkg(string, sep): return string.rsplit(sep, 1) def sort(list, fn=None, key=None): if fn: list.sort(cmp=fn) elif key: list.sort(key=key) else: list.sort() class JavaError(Exception): def getJavaException(self): return self.args[0] def __str__(self): writer = StringWriter() self.getJavaException().printStackTrace(PrintWriter(writer)) return '\n'.join((super(JavaError, self).__str__(), "Java stacktrace:", str(writer))) class InvalidArgsError(Exception): pass _jcc2._set_exception_types(JavaError, InvalidArgsError) from _jcc2 import findClass as _findClass from _jcc2 import * def findClass(className): try: cls = _findClass(className) except: print >>sys.stderr, "While loading", className raise if cls is None: raise ValueError, className return cls # fix for PYLUCENE-47: method overloads need to be sorted deterministically # and heuristically by the so-called rank of their parameter types, trying # to match parameters whose classes are deeper in the class hierarchy first def sortSignatures(signatures, groupByName=False): def _compare(sig0, sig1): # group signatures by name, lexicographically if groupByName: diff = cmp(sig0.getName(), sig1.getName()) if diff != 0: return diff sig0_types = sig0.getParameterTypes() sig1_types = sig1.getParameterTypes() # group signatures by number of parameters, lowest first diff = len(sig0_types) - len(sig1_types) if diff != 0: return diff def _getRank(types): rank = 0 for item in types: while item is not None: rank += 1 item = item.getSuperclass() return rank # sort signatures of equal length by the sum of class ranks # so that deepest classes are considered first during calls, # thus sort highest rank number first diff = _getRank(sig1_types) - _getRank(sig0_types) if diff != 0: return diff # sort signatures of equal rank by the names of their classes # lexicographically for (sig0_type, sig1_type) in izip(sig0_types, sig1_types): diff = cmp(sig0_type.getName(), sig1_type.getName()) if diff != 0: return diff # give up, sig1 must be larger ;-) return -1 sort(signatures, fn=_compare) INDENT = ' ' HALF_INDENT = ' ' PRIMITIVES = { 'boolean': 'Z', 'byte': 'B', 'char': 'C', 'double': 'D', 'float': 'F', 'int': 'I', 'long': 'J', 'short': 'S', 'void': 'V' } RESERVED = set(['delete', 'and', 'or', 'not', 'xor', 'union', 'register', 'const', 'bool', 'operator', 'typeof', 'asm', 'mutable', 'inline', 'typedef', 'struct', 'extern', 'NULL', 'DOMAIN', 'IGNORE', 'min', 'max', 'PREFIX', 'NAN']) RENAME_METHOD_SUFFIX = '_' RENAME_FIELD_SUFFIX = '__' def cppname(name): if name in RESERVED: return name + '$' return name def cppnames(names): return [cppname(name) for name in names] def absname(names): if names: return "::%s" %('::'.join(names)) return '' def typename(cls, current, const): if cls.isArray(): componentType = cls.getComponentType() name = 'JArray< %s >' %(typename(componentType, current, False)) elif cls.isPrimitive(): name = cls.getName() if name != 'void': name = 'j' + name const = False elif cls == current: name = cppname(cls.getName().split('.')[-1]) else: name = absname([cppname(name) for name in cls.getName().split('.')]) if const: return "const %s &" %(name) return name def argnames(params, cls): if not params: return '', '' count = len(params) decls = ', '.join(["%s a%d" %(typename(params[i], cls, True), i) for i in xrange(count)]) args = ', '.join(['a%d%s' %(i, not params[i].isPrimitive() and '.this$' or '') for i in xrange(count)]) return decls, ', ' + args def line(out, indent=0, string='', *args): out.write(INDENT * indent) out.write(string % args) out.write('\n') def known(cls, typeset, declares, packages, excludes, generics): if generics: if Class.instance_(cls): cls = Class.cast_(cls) elif ParameterizedType.instance_(cls): pt = ParameterizedType.cast_(cls) if not known(pt.getRawType(), typeset, declares, packages, excludes, True): return False for ta in pt.getActualTypeArguments(): if TypeVariable.instance_(ta): continue if not known(ta, typeset, declares, packages, excludes, True): return False return True elif WildcardType.instance_(cls): wc = WildcardType.cast_(cls) for ub in wc.getUpperBounds(): if not known(ub, typeset, declares, packages, excludes, True): return False return True elif TypeVariable.instance_(cls): for bounds in TypeVariable.cast_(cls).getBounds(): if not known(bounds, typeset, declares, packages, excludes, True): return False return True elif GenericArrayType.instance_(cls): return known(GenericArrayType.cast_(cls).getGenericComponentType(), typeset, declares, packages, excludes, True) else: raise TypeError, (cls, cls.getClass()) while cls.isArray(): cls = cls.getComponentType() className = cls.getName() if className.split('$', 1)[0] in excludes or className in excludes: return False if cls.isPrimitive(): return True if cls in typeset: declares.add(cls) return True if split_pkg(className, '.')[0] in packages: typeset.add(cls) declares.add(cls) cls = cls.getSuperclass() while cls and cls not in typeset: typeset.add(cls) cls = cls.getSuperclass() return True return False def addRequiredTypes(cls, typeset, generics): if generics: if Class.instance_(cls): cls = Class.cast_(cls) if not (cls.isPrimitive() or cls in typeset): if cls.isArray(): addRequiredTypes(cls.getComponentType(), typeset, True) else: typeset.add(cls) cls = cls.getGenericSuperclass() if cls is not None: addRequiredTypes(cls, typeset, True) elif ParameterizedType.instance_(cls): pt = ParameterizedType.cast_(cls) addRequiredTypes(pt.getRawType(), typeset, True) for ta in pt.getActualTypeArguments(): addRequiredTypes(ta, typeset, True) elif GenericArrayType.instance_(cls): gat = GenericArrayType.cast_(cls) addRequiredTypes(gat.getGenericComponentType(), typeset, True) elif not (TypeVariable.instance_(cls) or WildcardType.instance_(cls)): raise NotImplementedError, repr(cls) else: if cls not in typeset: typeset.add(cls) cls = cls.getSuperclass() if cls is not None: addRequiredTypes(cls, typeset, False) def getActualTypeArguments(pt): while True: arguments = pt.getActualTypeArguments() if arguments: return arguments pt = pt.getOwnerType() if pt is None or not ParameterizedType.instance_(pt): return [] pt = ParameterizedType.cast_(pt) def getTypeParameters(cls): if cls is None: return [] parameters = cls.getTypeParameters() if parameters: return parameters superCls = cls.getGenericSuperclass() if Class.instance_(superCls): parameters = getTypeParameters(Class.cast_(superCls)) if parameters: return parameters elif ParameterizedType.instance_(superCls): parameters = getActualTypeArguments(ParameterizedType.cast_(superCls)) if parameters: return parameters parameters = getTypeParameters(cls.getDeclaringClass()) if parameters: return parameters return [] def find_method(cls, name, params): declared = False while True: try: if declared: method = cls.getDeclaredMethod(name, params) else: method = cls.getMethod(name, params) break except JavaError, e: if (e.getJavaException().getClass().getName() == 'java.lang.NoSuchMethodException'): if not declared: declared = True else: cls = cls.getSuperclass() if not cls: return None continue raise modifiers = method.getModifiers() if Modifier.isAbstract(modifiers): return None if Modifier.isPrivate(modifiers): return None return method def signature(fn, argsOnly=False): def typename(cls): array = '' while cls.isArray(): array += '[' cls = cls.getComponentType() if cls.isPrimitive(): return array + PRIMITIVES[cls.getName()] return '%sL%s;' %(array, cls.getName().replace('.', '/')) if isinstance(fn, Constructor): returnType = 'V' elif isinstance(fn, Method): returnType = typename(fn.getReturnType()) elif isinstance(fn, Field): return typename(fn.getType()) if argsOnly: return '(%s)' %(''.join([typename(param) for param in fn.getParameterTypes()])) return '(%s)%s' %(''.join([typename(param) for param in fn.getParameterTypes()]), returnType) def forward(out, namespace, indent): for name, entries in namespace.iteritems(): if entries is True: line(out, indent, 'class %s;', cppname(name)) else: line(out, indent, 'namespace %s {', cppname(name)) forward(out, entries, indent + 1) line(out, indent, '}') def expandjar(path): jar = zipfile.ZipFile(path, 'r') for member in jar.infolist(): f = member.filename if not f.startswith('META-INF/') and f.endswith('.class'): yield f.split('.')[0].replace('/', '.') jar.close() def jcc(args): classNames = set() listedClassNames = set() listedMethodOrFieldNames = {} packages = set() jars = [] classpath = [_jcc2.CLASSPATH] libpath = [] vmargs = ['-Djava.awt.headless=true'] moduleName = None modules = [] build = False install = False recompile = False egg_info = False output = 'build' debug = False excludes = [] version = '' mappings = {} sequences = {} renames = {} use_full_names = False env = None wrapperFiles = 1 prefix = None root = None install_dir = None home_dir = None use_distutils = False shared = False dist = False wininst = False find_jvm_dll = False compiler = None generics = hasattr(_jcc2, "Type") arch = [] resources = [] imports = {} extra_setup_args = [] initvm_args = {} i = 1 while i < len(args): arg = args[i] if arg.startswith('-'): if arg == '--jar': i += 1 classpath.append(args[i]) classNames.update(expandjar(args[i])) jars.append(args[i]) elif arg == '--include': i += 1 classpath.append(args[i]) jars.append(args[i]) elif arg == '--package': i += 1 packages.add(args[i]) elif arg == '--classpath': i += 1 classpath.append(args[i]) elif arg == '--libpath': i += 1 libpath.append(args[i]) elif arg == '--vmarg': i += 1 vmargs.append(args[i]) elif arg == '--maxheap': i += 1 initvm_args['maxheap'] = args[i] elif arg == '--python': from python import python, module i += 1 moduleName = args[i] elif arg == '--module': i += 1 modules.append(args[i]) elif arg == '--build': from python import compile build = True elif arg == '--install': from python import compile install = True elif arg == '--compile': from python import compile recompile = True elif arg == '--egg-info': from python import compile egg_info = True elif arg == '--extra-setup-arg': i += 1 extra_setup_args.append(args[i]) elif arg == '--output': i += 1 output = args[i] elif arg == '--debug': debug = True elif arg == '--exclude': i += 1 excludes.append(args[i]) elif arg == '--version': i += 1 version = args[i] elif arg == '--mapping': mappings[args[i + 1]] = args[i + 2] i += 2 elif arg == '--sequence': sequences[args[i + 1]] = (args[i + 2], args[i + 3]) i += 3 elif arg == '--rename': i += 1 renames.update(dict([arg.split('=') for arg in args[i].split(',')])) elif arg == '--use_full_names': use_full_names = True elif arg == '--files': i += 1 wrapperFiles = args[i] if wrapperFiles != 'separate': wrapperFiles = int(wrapperFiles) elif arg == '--prefix': i += 1 prefix = args[i] elif arg == '--root': i += 1 root = args[i] elif arg == '--install-dir': i += 1 install_dir = args[i] elif arg == '--home': i += 1 home_dir = args[i] elif arg == '--use-distutils': use_distutils = True elif arg == '--shared': shared = True elif arg == '--bdist': from python import compile dist = True elif arg == '--wininst': from python import compile wininst = True dist = True elif arg == '--compiler': i += 1 compiler = args[i] elif arg == '--reserved': i += 1 RESERVED.update(args[i].split(',')) elif arg == '--arch': i += 1 arch.append(args[i]) elif arg == '--no-generics': generics = False elif arg == '--find-jvm-dll': find_jvm_dll = True elif arg == '--resources': i += 1 resources.append(args[i]) elif arg == '--import': i += 1 imports[args[i]] = () else: raise ValueError, "Invalid argument: %s" %(arg) else: if ':' in arg: arg, method = arg.split(':', 1) listedMethodOrFieldNames.setdefault(arg, set()).add(method) classNames.add(arg) listedClassNames.add(arg) i += 1 if libpath: vmargs.append('-Djava.library.path=' + os.pathsep.join(libpath)) initvm_args['maxstack'] = '512k' initvm_args['vmargs'] = vmargs env = initVM(os.pathsep.join(classpath) or None, **initvm_args) typeset = set() excludes = set(excludes) if imports: if shared: imports = dict((__import__(import_), set()) for import_ in imports) else: raise ValueError, "--shared must be used when using --import" if recompile or not build and (install or dist or egg_info): if moduleName is None: raise ValueError, 'module name not specified (use --python)' else: compile(env, os.path.dirname(args[0]), output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, home_dir, use_distutils, shared, compiler, modules, wininst, find_jvm_dll, arch, generics, resources, imports, use_full_names, egg_info, extra_setup_args) else: if imports: def walk((include, importset), dirname, names): for name in names: if name.endswith('.h'): className = os.path.join(dirname[len(include) + 1:], name[:-2]) if os.path.sep != '/': className = className.replace(os.path.sep, '/') importset.add(findClass(className)) for import_, importset in imports.iteritems(): env._addClassPath(import_.CLASSPATH) include = os.path.join(import_.__dir__, 'include') os.path.walk(include, walk, (include, importset)) typeset.update(importset) typeset.add(findClass('java/lang/Object')) typeset.add(findClass('java/lang/Class')) typeset.add(findClass('java/lang/String')) typeset.add(findClass('java/lang/Throwable')) typeset.add(findClass('java/lang/Exception')) typeset.add(findClass('java/lang/RuntimeException')) if moduleName: typeset.add(findClass('java/lang/Number')) typeset.add(findClass('java/lang/Boolean')) typeset.add(findClass('java/lang/Byte')) typeset.add(findClass('java/lang/Character')) typeset.add(findClass('java/lang/Double')) typeset.add(findClass('java/lang/Float')) typeset.add(findClass('java/lang/Integer')) typeset.add(findClass('java/lang/Long')) typeset.add(findClass('java/lang/Short')) typeset.add(findClass('java/util/Iterator')) typeset.add(findClass('java/util/Enumeration')) typeset.add(findClass('java/io/StringWriter')) typeset.add(findClass('java/io/PrintWriter')) typeset.add(findClass('java/io/Writer')) packages.add('java.lang') for className in classNames: if className.split('$', 1)[0] in excludes or className in excludes: continue cls = findClass(className.replace('.', '/')) if (Modifier.isPublic(cls.getModifiers()) or className in listedClassNames): addRequiredTypes(cls, typeset, generics) _dll_export = '' if moduleName: cppdir = os.path.join(output, '_%s' %(moduleName)) if shared and sys.platform == 'win32': _dll_export = "_dll_%s " %(moduleName) else: cppdir = output allInOne = wrapperFiles != 'separate' if allInOne: if not os.path.isdir(cppdir): os.makedirs(cppdir) if wrapperFiles <= 1: out_cpp = file(os.path.join(cppdir, '__wrap__.cpp'), 'w') else: fileCount = 1 fileName = '__wrap%02d__.cpp' %(fileCount) out_cpp = file(os.path.join(cppdir, fileName), 'w') done = set() pythonNames = {} for importset in imports.itervalues(): done.update(importset) if moduleName: for cls in importset: name = split_pkg(cls.getName(), '.')[-1] if not use_full_names: if name in pythonNames: raise ValueError, (cls, 'python class name already in use, use --rename', name, pythonNames[name]) else: pythonNames[name] = cls todo = typeset - done if allInOne and wrapperFiles > 1: classesPerFile = max(1, len(todo) / wrapperFiles) classCount = 0 while todo: for cls in todo: classCount += 1 className = cls.getName() names = className.split('.') dir = os.path.join(cppdir, *names[:-1]) if not os.path.isdir(dir): os.makedirs(dir) fileName = os.path.join(dir, names[-1]) out_h = file(fileName + '.h', "w") line(out_h, 0, '#ifndef %s_H', '_'.join(names)) line(out_h, 0, '#define %s_H', '_'.join(names)) (superCls, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares) = \ header(env, out_h, cls, typeset, packages, excludes, generics, listedMethodOrFieldNames.get(cls.getName(), ()), _dll_export) if not allInOne: out_cpp = file(fileName + '.cpp', 'w') names, superNames = code(env, out_cpp, cls, superCls, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares, typeset) if moduleName: name = renames.get(className) or names[-1] if not use_full_names: if name in pythonNames: raise ValueError, (cls, 'python class name already in use, use --rename', name, pythonNames[name]) else: pythonNames[name] = cls python(env, out_h, out_cpp, cls, superCls, names, superNames, constructors, methods, protectedMethods, methodNames, fields, instanceFields, mappings.get(className), sequences.get(className), renames.get(className), declares, typeset, moduleName, generics, _dll_export) line(out_h) line(out_h, 0, '#endif') out_h.close() if not allInOne: out_cpp.close() elif wrapperFiles > 1: if classCount >= classesPerFile: out_cpp.close() fileCount += 1 fileName = '__wrap%02d__.cpp' %(fileCount) out_cpp = file(os.path.join(cppdir, fileName), 'w') classCount = 0 done.update(todo) todo = typeset - done if allInOne: out_cpp.close() if moduleName: out = file(os.path.join(cppdir, moduleName) + '.cpp', 'w') module(out, allInOne, done, imports, cppdir, moduleName, shared, generics, use_full_names) out.close() if build or install or dist or egg_info: compile(env, os.path.dirname(args[0]), output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, home_dir, use_distutils, shared, compiler, modules, wininst, find_jvm_dll, arch, generics, resources, imports, use_full_names, egg_info, extra_setup_args) def header(env, out, cls, typeset, packages, excludes, generics, listedMethodOrFieldNames, _dll_export): names = cls.getName().split('.') superCls = cls.getSuperclass() declares = set([cls.getClass()]) interfaces = [] if generics: for interface in cls.getGenericInterfaces(): if Class.instance_(interface): pt = None interface = Class.cast_(interface) elif ParameterizedType.instance_(interface): pt = ParameterizedType.cast_(interface) interface = Class.cast_(pt.getRawType()) else: raise NotImplementedError, repr(interface) if superCls and interface.isAssignableFrom(superCls): continue if known(interface, typeset, declares, packages, excludes, False): interfaces.append(interface) if pt is not None: for ta in pt.getActualTypeArguments(): addRequiredTypes(ta, typeset, True) else: for interface in cls.getInterfaces(): if superCls and interface.isAssignableFrom(superCls): continue if known(interface, typeset, declares, packages, excludes, False): interfaces.append(interface) if cls.isInterface(): if interfaces: superCls = interfaces.pop(0) else: superCls = findClass('java/lang/Object') superClsName = superCls.getName() elif superCls: superClsName = superCls.getName() if generics: for clsParam in getTypeParameters(cls): if Class.instance_(clsParam): addRequiredTypes(clsParam, typeset, True) known(clsParam, typeset, declares, packages, excludes, True) else: superClsName = 'JObject' constructors = [] for constructor in cls.getDeclaredConstructors(): if Modifier.isPublic(constructor.getModifiers()): if generics: genericParams = constructor.getGenericParameterTypes() params = constructor.getParameterTypes() # It appears that the implicit instance-of-the-declaring-class # parameter of a non-static inner class is missing from # getGenericParameterTypes() if len(params) == len(genericParams) + 1: params[1:] = genericParams else: params = genericParams if len(params) == 1: if params[0] == cls: continue if ParameterizedType.instance_(params[0]): param = ParameterizedType.cast_(params[0]) if param.getRawType() == cls: continue else: params = constructor.getParameterTypes() if len(params) == 1 and params[0] == cls: continue for param in params: if not known(param, typeset, declares, packages, excludes, generics): break else: constructors.append(constructor) sortSignatures(constructors) methods = {} protectedMethods = [] for method in cls.getDeclaredMethods(): if method.isSynthetic(): continue modifiers = method.getModifiers() if (Modifier.isPublic(modifiers) or method.getName() in listedMethodOrFieldNames): if generics: returnType = method.getGenericReturnType() else: returnType = method.getReturnType() if not known(returnType, typeset, declares, packages, excludes, generics): continue sig = "%s:%s" %(method.getName(), signature(method, True)) # Apparently, overridden clone() methods are still returned via # getDeclaredMethods(), so keep the one with the more precise # return type, equal to cls. if sig in methods and returnType != cls: continue if generics: params = method.getGenericParameterTypes() else: params = method.getParameterTypes() for param in params: if not known(param, typeset, declares, packages, excludes, generics): break else: methods[sig] = method elif Modifier.isProtected(modifiers): protectedMethods.append(method) methods = methods.values() sortSignatures(methods, groupByName=True) methodNames = set([cppname(method.getName()) for method in methods]) for constructor in constructors: if generics: exceptions = constructor.getGenericExceptionTypes() else: exceptions = constructor.getExceptionTypes() for exception in exceptions: known(exception, typeset, declares, packages, excludes, generics) for method in methods: if generics: exceptions = method.getGenericExceptionTypes() else: exceptions = method.getExceptionTypes() for exception in exceptions: known(exception, typeset, declares, packages, excludes, generics) fields = [] instanceFields = [] for field in cls.getDeclaredFields(): modifiers = field.getModifiers() if (Modifier.isPublic(modifiers) or field.getName() in listedMethodOrFieldNames): if generics: fieldType = field.getGenericType() else: fieldType = field.getType() if not known(fieldType, typeset, declares, packages, excludes, generics): continue if Modifier.isStatic(modifiers): fields.append(field) else: instanceFields.append(field) sort(fields, key=lambda x: x.getName()) sort(instanceFields, key=lambda x: x.getName()) line(out) superNames = superClsName.split('.') line(out, 0, '#include "%s.h"', '/'.join(superNames)) line(out, 0) namespaces = {} for declare in declares: namespace = namespaces if declare not in (cls, superCls): declareNames = declare.getName().split('.') for declareName in declareNames[:-1]: namespace = namespace.setdefault(declareName, {}) namespace[declareNames[-1]] = True forward(out, namespaces, 0) line(out, 0, 'template class JArray;') indent = 0; line(out) for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out) if superClsName == 'JObject': line(out, indent, 'class %s%s : public JObject {', _dll_export, cppname(names[-1])) else: line(out, indent, 'class %s%s : public %s {', _dll_export, cppname(names[-1]), absname(cppnames(superNames))) line(out, indent, 'public:') indent += 1 if methods or protectedMethods or constructors: line(out, indent, 'enum {') for constructor in constructors: line(out, indent + 1, 'mid_init$_%s,', env.strhash(signature(constructor))) for method in methods: line(out, indent + 1, 'mid_%s_%s,', method.getName(), env.strhash(signature(method))) for method in protectedMethods: line(out, indent + 1, 'mid_%s_%s,', method.getName(), env.strhash(signature(method))) line(out, indent + 1, 'max_mid') line(out, indent, '};') if instanceFields: line(out) line(out, indent, 'enum {') for field in instanceFields: line(out, indent + 1, 'fid_%s,', field.getName()) line(out, indent + 1, 'max_fid') line(out, indent, '};') line(out) line(out, indent, 'static ::java::lang::Class *class$;'); line(out, indent, 'static jmethodID *mids$;'); if instanceFields: line(out, indent, 'static jfieldID *fids$;'); line(out, indent, 'static bool live$;'); line(out, indent, 'static jclass initializeClass(bool);'); line(out) line(out, indent, 'explicit %s(jobject obj) : %s(obj) {', cppname(names[-1]), absname(cppnames(superNames))) line(out, indent + 1, 'if (obj != NULL)'); line(out, indent + 2, 'env->getClass(initializeClass);') line(out, indent, '}') line(out, indent, '%s(const %s& obj) : %s(obj) {}', cppname(names[-1]), cppname(names[-1]), absname(cppnames(superNames))) if fields: line(out) for field in fields: fieldType = field.getType() fieldName = cppname(field.getName()) if fieldName in methodNames: print >>sys.stderr, " Warning: renaming static variable '%s' on class %s to '%s%s' since it is shadowed by a method of same name." %(fieldName, '.'.join(names), fieldName, RENAME_FIELD_SUFFIX) fieldName += RENAME_FIELD_SUFFIX if fieldType.isPrimitive(): line(out, indent, 'static %s %s;', typename(fieldType, cls, False), fieldName) else: line(out, indent, 'static %s *%s;', typename(fieldType, cls, False), fieldName) if instanceFields: line(out) for field in instanceFields: fieldType = field.getType() fieldName = field.getName() modifiers = field.getModifiers() line(out, indent, '%s _get_%s() const;', typename(fieldType, cls, False), fieldName) if not Modifier.isFinal(modifiers): line(out, indent, 'void _set_%s(%s) const;', fieldName, typename(fieldType, cls, True)) if constructors: line(out) for constructor in constructors: params = [typename(param, cls, True) for param in constructor.getParameterTypes()] line(out, indent, '%s(%s);', cppname(names[-1]), ', '.join(params)) if methods: line(out) for method in methods: modifiers = method.getModifiers() if Modifier.isStatic(modifiers): prefix = 'static ' const = '' else: prefix = '' const = ' const' params = [typename(param, cls, True) for param in method.getParameterTypes()] methodName = cppname(method.getName()) line(out, indent, '%s%s %s(%s)%s;', prefix, typename(method.getReturnType(), cls, False), methodName, ', '.join(params), const) indent -= 1 line(out, indent, '};') while indent: indent -= 1 line(out, indent, '}') return (superCls, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares) def code(env, out, cls, superCls, constructors, methods, protectedMethods, methodNames, fields, instanceFields, declares, typeset): className = cls.getName() names = className.split('.') if superCls: superClsName = superCls.getName() else: superClsName = 'JObject' superNames = superClsName.split('.') line(out, 0, '#include ') line(out, 0, '#include "JCCEnv.h"') line(out, 0, '#include "%s.h"', className.replace('.', '/')) for declare in declares: if declare not in (cls, superCls): line(out, 0, '#include "%s.h"', declare.getName().replace('.', '/')) line(out, 0, '#include "JArray.h"') indent = 0 line(out) for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out) line(out, indent, '::java::lang::Class *%s::class$ = NULL;', cppname(names[-1])) line(out, indent, 'jmethodID *%s::mids$ = NULL;', cppname(names[-1])) if instanceFields: line(out, indent, 'jfieldID *%s::fids$ = NULL;', cppname(names[-1])) line(out, indent, 'bool %s::live$ = false;', cppname(names[-1])) for field in fields: fieldType = field.getType() fieldName = cppname(field.getName()) if fieldName in methodNames: fieldName += RENAME_FIELD_SUFFIX typeName = typename(fieldType, cls, False) if fieldType.isPrimitive(): line(out, indent, '%s %s::%s = (%s) 0;', typeName, cppname(names[-1]), fieldName, typeName) else: line(out, indent, '%s *%s::%s = NULL;', typeName, cppname(names[-1]), fieldName) line(out) line(out, indent, 'jclass %s::initializeClass(bool getOnly)', cppname(names[-1])) line(out, indent, '{') line(out, indent + 1, 'if (getOnly)') line(out, indent + 2, 'return (jclass) (live$ ? class$->this$ : NULL);') line(out, indent + 1, 'if (class$ == NULL)') line(out, indent + 1, '{') line(out, indent + 2, 'jclass cls = (jclass) env->findClass("%s");', className.replace('.', '/')) if methods or protectedMethods or constructors: line(out) line(out, indent + 2, 'mids$ = new jmethodID[max_mid];') for constructor in constructors: sig = signature(constructor) line(out, indent + 2, 'mids$[mid_init$_%s] = env->getMethodID(cls, "", "%s");', env.strhash(sig), sig) isExtension = False for method in methods: methodName = method.getName() if methodName == 'pythonExtension': isExtension = True sig = signature(method) line(out, indent + 2, 'mids$[mid_%s_%s] = env->get%sMethodID(cls, "%s", "%s");', methodName, env.strhash(sig), Modifier.isStatic(method.getModifiers()) and 'Static' or '', methodName, sig) for method in protectedMethods: methodName = method.getName() sig = signature(method) line(out, indent + 2, 'mids$[mid_%s_%s] = env->get%sMethodID(cls, "%s", "%s");', methodName, env.strhash(sig), Modifier.isStatic(method.getModifiers()) and 'Static' or '', methodName, sig) if instanceFields: line(out) line(out, indent + 2, 'fids$ = new jfieldID[max_fid];') for field in instanceFields: fieldName = field.getName() line(out, indent + 2, 'fids$[fid_%s] = env->getFieldID(cls, "%s", "%s");', fieldName, fieldName, signature(field)) line(out) line(out, indent + 2, 'class$ = (::java::lang::Class *) new JObject(cls);') if fields: line(out, indent + 2, 'cls = (jclass) class$->this$;') line(out) for field in fields: fieldType = field.getType() fieldName = field.getName() cppFieldName = cppname(fieldName) if cppFieldName in methodNames: cppFieldName += RENAME_FIELD_SUFFIX if fieldType.isPrimitive(): line(out, indent + 2, '%s = env->getStatic%sField(cls, "%s");', cppFieldName, fieldType.getName().capitalize(), fieldName) else: line(out, indent + 2, '%s = new %s(env->getStaticObjectField(cls, "%s", "%s"));', cppFieldName, typename(fieldType, cls, False), fieldName, signature(field)) line(out, indent + 2, "live$ = true;") line(out, indent + 1, '}') line(out, indent + 1, 'return (jclass) class$->this$;') line(out, indent, '}') for constructor in constructors: line(out) sig = signature(constructor) decls, args = argnames(constructor.getParameterTypes(), cls) line(out, indent, "%s::%s(%s) : %s(env->newObject(initializeClass, &mids$, mid_init$_%s%s)) {}", cppname(names[-1]), cppname(names[-1]), decls, absname(cppnames(superNames)), env.strhash(sig), args) for method in methods: modifiers = method.getModifiers() returnType = method.getReturnType() params = method.getParameterTypes() methodName = method.getName() superMethod = None isStatic = Modifier.isStatic(modifiers) if (isExtension and not isStatic and superCls and Modifier.isNative(modifiers)): superMethod = find_method(superCls, methodName, params) if superMethod is None: continue if isStatic: qualifier = 'Static' this = 'cls' midns = '' const = '' sig = signature(method) else: isStatic = False if superMethod is not None: qualifier = 'Nonvirtual' this = 'this$, (jclass) %s::class$->this$' %(absname(cppnames(superNames))) declaringClass = superMethod.getDeclaringClass() midns = '%s::' %(typename(declaringClass, cls, False)) sig = signature(superMethod) else: qualifier = '' this = 'this$' midns = '' sig = signature(method) const = ' const' decls, args = argnames(params, cls) line(out) line(out, indent, '%s %s::%s(%s)%s', typename(returnType, cls, False), cppname(names[-1]), cppname(methodName), decls, const) line(out, indent, '{') if isStatic: line(out, indent + 1, 'jclass cls = env->getClass(initializeClass);'); if returnType.isPrimitive(): line(out, indent + 1, '%senv->call%s%sMethod(%s, %smids$[%smid_%s_%s]%s);', not returnType.getName() == 'void' and 'return ' or '', qualifier, returnType.getName().capitalize(), this, midns, midns, methodName, env.strhash(sig), args) else: line(out, indent + 1, 'return %s(env->call%sObjectMethod(%s, %smids$[%smid_%s_%s]%s));', typename(returnType, cls, False), qualifier, this, midns, midns, methodName, env.strhash(sig), args) line(out, indent, '}') if instanceFields: for field in instanceFields: fieldType = field.getType() fieldName = field.getName() line(out) line(out, indent, '%s %s::_get_%s() const', typename(fieldType, cls, False), cppname(names[-1]), fieldName) line(out, indent, '{') if fieldType.isPrimitive(): line(out, indent + 1, 'return env->get%sField(this$, fids$[fid_%s]);', fieldType.getName().capitalize(), fieldName) else: line(out, indent + 1, 'return %s(env->getObjectField(this$, fids$[fid_%s]));', typename(fieldType, cls, False), fieldName) line(out, indent, '}') if not Modifier.isFinal(field.getModifiers()): line(out) line(out, indent, 'void %s::_set_%s(%s a0) const', cppname(names[-1]), fieldName, typename(fieldType, cls, True)) line(out, indent, '{') if fieldType.isPrimitive(): line(out, indent + 1, 'env->set%sField(this$, fids$[fid_%s], a0);', fieldType.getName().capitalize(), fieldName) else: line(out, indent + 1, 'env->setObjectField(this$, fids$[fid_%s], a0.this$);', fieldName) line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') return names, superNames if __name__ == '__main__': jcc(sys.argv) JCC-3.6/jcc2/python.py0000644000076500000000000022403113457642724014720 0ustar vajdawheel00000000000000# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os, sys, platform, shutil, _jcc2 from itertools import izip from cpp import PRIMITIVES, INDENT, HALF_INDENT from cpp import RENAME_METHOD_SUFFIX, RENAME_FIELD_SUFFIX from cpp import cppname, cppnames, absname, typename, findClass from cpp import line, signature, find_method, split_pkg, sort, sortSignatures from cpp import Modifier, Class, Method from cpp import getActualTypeArguments, getTypeParameters from config import INCLUDES, CFLAGS, DEBUG_CFLAGS, LFLAGS, IMPLIB_LFLAGS, \ SHARED, VERSION as JCC_VER try: from cpp import ParameterizedType, TypeVariable except ImportError: pass python_ver = '%d.%d.%d' %(sys.version_info[0:3]) if python_ver < '2.4': from sets import Set as set RESULTS = { 'boolean': 'Py_RETURN_BOOL(%s);', 'byte': 'return PyInt_FromLong((long) %s);', 'char': 'return PyUnicode_FromUnicode((Py_UNICODE *) &%s, 1);', 'double': 'return PyFloat_FromDouble((double) %s);', 'float': 'return PyFloat_FromDouble((double) %s);', 'int': 'return PyInt_FromLong((long) %s);', 'long': 'return PyLong_FromLongLong((PY_LONG_LONG) %s);', 'short': 'return PyInt_FromLong((long) %s);', 'java.lang.String': 'return j2p(%s);' } CALLARGS = { 'boolean': ('O', '(%s ? Py_True : Py_False)', False), 'byte': ('O', 'PyInt_FromLong(%s)', True), 'char': ('O', 'PyUnicode_FromUnicode((Py_UNICODE *) &%s, 1)', True), 'double': ('d', '(double) %s', False), 'float': ('f', '(float) %s', False), 'int': ('i', '(int) %s', False), 'long': ('L', '(long long) %s', False), 'short': ('i', '(int) %s', False), 'java.lang.String': ('O', 'env->fromJString((jstring) %s, 0)', True) } BOXED = { 'java.lang.Boolean': (True, True), 'java.lang.Byte': (True, True), 'java.lang.Character': (True, True), 'java.lang.CharSequence': (True, False), 'java.lang.Double': (True, True), 'java.lang.Float': (True, True), 'java.lang.Integer': (True, True), 'java.lang.Long': (True, True), 'java.lang.Number': (True, False), 'java.lang.Short': (True, True), 'java.lang.String': (True, True) } def is_boxed(clsName): return BOXED.get(clsName, (False, False))[0] def is_unboxed(clsName): return BOXED.get(clsName, (False, False))[1] def parseArgs(params, current, generics, genericParams=None): def signature(cls, genericPT=None): if generics and TypeVariable.instance_(genericPT): if cls.getName() == 'java.lang.Object': gd = TypeVariable.cast_(genericPT).getGenericDeclaration() if gd == current: for clsParam in getTypeParameters(gd): if genericPT == clsParam: return 'O' array = '' while cls.isArray(): array += '[' cls = cls.getComponentType() clsName = cls.getName() if cls.isPrimitive(): return array + PRIMITIVES[clsName] if clsName == 'java.lang.String': return array + 's' if clsName == 'java.lang.Object': return array + 'o' if is_boxed(clsName): return array + 'O' if generics and getTypeParameters(cls): return array + 'K' else: return array + 'k' def checkarg(cls, genericPT=None): if generics and TypeVariable.instance_(genericPT): if cls.getName() == 'java.lang.Object': gd = TypeVariable.cast_(genericPT).getGenericDeclaration() if gd == current: i = 0 for clsParam in getTypeParameters(gd): if genericPT == clsParam: return ', self->parameters[%d]' %(i) i += 1 while cls.isArray(): cls = cls.getComponentType() clsName = cls.getName() if (cls.isPrimitive() or clsName in ('java.lang.String', 'java.lang.Object')): return '' if is_boxed(clsName): clsNames = clsName.split('.') return ', &%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) return ', %s::initializeClass' %(typename(cls, current, False)) def callarg(cls, i): if generics: while cls.isArray(): cls = cls.getComponentType() if getTypeParameters(cls): ns, sep, n = rpartition(typename(cls, current, False), '::') return ', &a%d, &p%d, %s%st_%s::parameters_' %(i, i, ns, sep, n) return ', &a%d' %(i) if genericParams: sig = ''.join([signature(param, genericParam) for param, genericParam in izip(params, genericParams)]) chk = ''.join([checkarg(param, genericParam) for param, genericParam in izip(params, genericParams)]) else: sig = ''.join([signature(param) for param in params]) chk = ''.join([checkarg(param) for param in params]) return (sig, chk, ''.join([callarg(params[i], i) for i in xrange(len(params))])) def declareVars(out, indent, params, current, generics, typeParams): for i in xrange(len(params)): param = params[i] line(out, indent, '%s a%d%s;', typename(param, current, False), i, not param.isPrimitive() and '((jobject) NULL)' or '') if generics: while param.isArray(): param = param.getComponentType() if getTypeParameters(param): line(out, indent, 'PyTypeObject **p%d;', i) typeParams.add(i) def construct(out, indent, cls, inCase, constructor, names, generics): if inCase: line(out, indent, '{') indent += 1 params = constructor.getParameterTypes() if generics: typeParams = set() else: typeParams = None count = len(params) declareVars(out, indent, params, cls, generics, typeParams) line(out, indent, '%s object((jobject) NULL);', cppname(names[-1])) line(out) if count: line(out, indent, 'if (!parseArgs(args, "%s"%s%s))', *parseArgs(params, cls, generics)) line(out, indent, '{') indent += 1 line(out, indent, 'INT_CALL(object = %s(%s));', cppname(names[-1]), ', '.join(['a%d' %(i) for i in xrange(count)])) line(out, indent, 'self->object = object;') if generics: clsParams = getTypeParameters(cls) i = 0 for clsParam in clsParams: if Class.instance_(clsParam): cls = Class.cast_(clsParam) if cls.isArray(): cls = cls.getComponentType() if cls.isArray(): clsNames = 'java.lang.Object'.split('.') clsArg = '&%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) elif cls.isPrimitive(): clsArg = 'PY_TYPE(JArray%s)' %(cls.getName().capitalize()) else: clsArg = 'PY_TYPE(JArrayObject)' else: clsNames = cls.getName().split('.') clsArg = '&%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) line(out, indent, 'self->parameters[%d] = %s;', i, clsArg) i += 1 if inCase: line(out, indent, 'break;') if count: indent -= 1 line(out, indent, '}') if inCase: indent -= 1 line(out, indent, '}') def rpartition(string, sep): if python_ver >= '2.5.0': return string.rpartition(sep) else: parts = split_pkg(string, sep) if len(parts) == 1: return ('', '', parts[0]) return (parts[0], sep, parts[1]) def fieldValue(cls, value, fieldType): if fieldType.isArray(): fieldType = fieldType.getComponentType() if fieldType.isArray(): result = 'JArray(%s->this$).wrap(NULL)' elif fieldType.isPrimitive(): result = '%s->wrap()' elif fieldType.getName() == 'java.lang.String': result = 'JArray(%s->this$).wrap()' else: parts = rpartition(typename(fieldType, cls, False), '::') result = 'JArray(%%s->this$).wrap(%s%st_%s::wrap_jobject)' %(parts) elif fieldType.getName() == 'java.lang.String': result = 'j2p(*%s)' elif not fieldType.isPrimitive(): parts = rpartition(typename(fieldType, cls, False), '::') result = '%s%st_%s::wrap_Object(*%%s)' %(parts) else: return value return result %(value) def returnValue(cls, returnType, value, genericRT=None, typeParams=None): result = RESULTS.get(returnType.getName()) if result: return result %(value) if returnType.isArray(): returnType = returnType.getComponentType() depth = 1 while returnType.isArray(): returnType = returnType.getComponentType() depth += 1 if depth > 1: return 'return JArray(%s.this$).wrap(NULL);' %(value) elif returnType.isPrimitive(): return 'return %s.wrap();' %(value) elif returnType.getName() == 'java.lang.String': return 'return JArray(%s.this$).wrap();' %(value) ns, sep, n = rpartition(typename(returnType, cls, False), '::') return 'return JArray(%s.this$).wrap(%s%st_%s::wrap_jobject);' %(value, ns, sep, n) ns, sep, n = rpartition(typename(returnType, cls, False), '::') if genericRT is not None: if ParameterizedType.instance_(genericRT): genericRT = ParameterizedType.cast_(genericRT) clsArgs = [] for clsArg in getActualTypeArguments(genericRT): if Class.instance_(clsArg): clsArg = Class.cast_(clsArg) if clsArg.isArray(): clsArg = Class.forName('java.lang.Object') clsNames = clsArg.getName().split('.') clsArg = '&%s::PY_TYPE(%s)' %(absname(cppnames(clsNames[:-1])), cppname(clsNames[-1])) clsArgs.append(clsArg) elif TypeVariable.instance_(clsArg): gd = TypeVariable.cast_(clsArg).getGenericDeclaration() if Class.instance_(gd): i = 0 for clsParam in getTypeParameters(gd): if clsArg == clsParam: clsArgs.append('self->parameters[%d]' %(i)) break i += 1 else: break else: break else: break else: return 'return %s%st_%s::wrap_Object(%s, %s);' %(ns, sep, n, value, ', '.join(clsArgs)) elif TypeVariable.instance_(genericRT): gd = TypeVariable.cast_(genericRT).getGenericDeclaration() i = 0 if Class.instance_(gd): for clsParam in getTypeParameters(gd): if genericRT == clsParam: return 'return self->parameters[%d] != NULL ? wrapType(self->parameters[%d], %s.this$) : %s%st_%s::wrap_Object(%s);' %(i, i, value, ns, sep, n, value) i += 1 elif Method.instance_(gd): for clsParam in getTypeParameters(gd): if genericRT == clsParam and i in typeParams: return 'return p%d != NULL && p%d[0] != NULL ? wrapType(p%d[0], %s.this$) : %s%st_%s::wrap_Object(%s);' %(i, i, i, value, ns, sep, n, value) i += 1 return 'return %s%st_%s::wrap_Object(%s);' %(ns, sep, n, value) def call(out, indent, cls, inCase, method, names, cardinality, isExtension, generics): if inCase: line(out, indent, '{') indent += 1 name = method.getName() modifiers = method.getModifiers() params = method.getParameterTypes() returnType = method.getReturnType() if generics: genericRT = method.getGenericReturnType() genericParams = method.getGenericParameterTypes() typeParams = set() else: genericRT = None genericParams = None typeParams = None count = len(params) declareVars(out, indent, params, cls, generics, typeParams) returnName = returnType.getName() if returnName != 'void': line(out, indent, '%s result%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') result = 'result = ' else: result = '' if cardinality and (count or not inCase): s = cardinality > 1 and 's' or '' line(out) if isExtension and name == 'clone' and Modifier.isNative(modifiers): line(out, indent, 'if (arg)') else: line(out, indent, 'if (!parseArg%s(arg%s, "%s"%s%s))', s, s, *parseArgs(params, cls, generics, genericParams)) line(out, indent, '{') indent += 1 name = cppname(name) if Modifier.isStatic(modifiers): line(out, indent, 'OBJ_CALL(%s%s::%s(%s));', result, absname(cppnames(names)), name, ', '.join(['a%d' %(i) for i in xrange(count)])) else: line(out, indent, 'OBJ_CALL(%sself->object.%s(%s));', result, name, ', '.join(['a%d' %(i) for i in xrange(count)])) if isExtension and name == 'clone' and Modifier.isNative(modifiers): line(out) line(out, indent, '%s object(result.this$);', typename(cls, cls, False)) line(out, indent, 'if (PyObject_TypeCheck(arg, &PY_TYPE(FinalizerProxy)) &&') line(out, indent, ' PyObject_TypeCheck(((t_fp *) arg)->object, self->ob_type))') line(out, indent, '{') line(out, indent + 1, 'PyObject *_arg = ((t_fp *) arg)->object;') line(out, indent + 1, '((t_JObject *) _arg)->object = object;') line(out, indent + 1, 'Py_INCREF(_arg);') line(out, indent + 1, 'object.pythonExtension((jlong) (Py_intptr_t) (void *) _arg);') line(out, indent + 1, 'Py_INCREF(arg);') line(out, indent + 1, 'return arg;') line(out, indent, '}') line(out, indent, 'return PyErr_SetArgsError("%s", arg);' %(name)) elif returnName != 'void': line(out, indent, returnValue(cls, returnType, 'result', genericRT, typeParams)) else: line(out, indent, 'Py_RETURN_NONE;') if cardinality and (count or not inCase): indent -= 1 line(out, indent, '}') if inCase: indent -= 1 line(out, indent, '}') def methodargs(methods, superMethods): if len(methods) == 1 and methods[0].getName() not in superMethods: count = len(methods[0].getParameterTypes()) if count == 0: return '', '', 0 elif count == 1: return ', PyObject *arg', ', arg', 1 return ', PyObject *args', ', args', 2 def jniname(cls): if cls.isPrimitive(): name = cls.getName() if name != 'void': name = 'j' + name else: name = 'jobject' return name def jniargs(params): count = len(params) decls = ', '.join(['%s a%d' %(jniname(params[i]), i) for i in xrange(count)]) if decls: return ', ' + decls return '' def wrapper_typename(returnType, cls): if returnType.isArray(): componentType = returnType.getComponentType() componentName = typename(componentType, cls, False) if componentType.isPrimitive(): return "t_JArrayWrapper< %s >" %(componentName) ns, sep, n = rpartition(componentName, '::') return "t_JArrayWrapper< jobject,%s%st_%s >" %(ns, sep, n) returnName = typename(returnType, cls, False) ns, sep, n = rpartition(returnName, '::') return "%s%st_%s" %(ns, sep, n) def extension(env, out, indent, cls, names, name, count, method, generics): line(out, indent, 'jlong ptr = jenv->CallLongMethod(jobj, %s::mids$[%s::mid_pythonExtension_%s]);', cppname(names[-1]), cppname(names[-1]), env.strhash('()J')) line(out, indent, 'PyObject *obj = (PyObject *) (Py_intptr_t) ptr;') if name == 'pythonDecRef': line(out) line(out, indent, 'if (obj != NULL)') line(out, indent, '{') line(out, indent + 1, 'jenv->CallVoidMethod(jobj, %s::mids$[%s::mid_pythonExtension_%s], (jlong) 0);', cppname(names[-1]), cppname(names[-1]), env.strhash('(J)V')) line(out, indent + 1, 'env->finalizeObject(jenv, obj);') line(out, indent, '}') return line(out, indent, 'PythonGIL gil(jenv);') returnType = method.getReturnType() returnName = returnType.getName() if returnName != 'void': line(out, indent, '%s value%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') sigs = [] decrefs = [] args = [] i = 0 for param in method.getParameterTypes(): typeName = param.getName() if typeName in CALLARGS: sig, code, decref = CALLARGS[typeName] elif param.isArray(): param = param.getComponentType() if param.isPrimitive(): code = 'JArray(%%s).wrap()' %(param.getName()) elif param.isArray(): code = 'JArray(%s).wrap(NULL)' elif param.getName() == 'java.lang.String': code = 'JArray(%s).wrap()' else: parts = rpartition(typename(param, cls, False), '::') code = 'JArray(%%s).wrap(%s%st_%s::wrap_jobject)' %(parts) sig, decref = 'O', True elif param.getName() == 'java.lang.String': sig, code, decref = 'O', 'j2p(%%s))', True else: parts = rpartition(typename(param, cls, False), '::') sig, code, decref = 'O', '%s%st_%s::wrap_Object(%s%s%s(%%s))' %(parts*2), True if sig == 'O': line(out, indent, 'PyObject *o%d = %s;', i, code %('a%d' %(i))) args.append('o%d' %(i)) else: args.append(code %('a%d' %(i))) sigs.append(sig) decrefs.append(decref) i += 1 args = ', '.join(args) if args: args = ', ' + args line(out, indent, 'PyObject *result = PyObject_CallMethod(obj, "%s", "%s"%s);', name, ''.join(sigs), args) i = 0 for decref in decrefs: if decref: line(out, indent, 'Py_DECREF(o%d);', i) i += 1 line(out, indent, 'if (!result)') line(out, indent + 1, 'throwPythonError();') if returnName == 'void': line(out, indent, 'else') line(out, indent + 1, 'Py_DECREF(result);') else: signature, check, x = parseArgs([returnType], cls, False) line(out, indent, 'else if (parseArg(result, "%s"%s, &value))', signature, check) line(out, indent, '{') line(out, indent + 1, 'throwTypeError("%s", result);', name) line(out, indent + 1, 'Py_DECREF(result);') line(out, indent, '}') line(out, indent, 'else') line(out, indent, '{') if not returnType.isPrimitive(): line(out, indent + 1, 'jobj = jenv->NewLocalRef(value.this$);') line(out, indent + 1, 'Py_DECREF(result);') if returnType.isPrimitive(): line(out, indent + 1, 'return value;') else: line(out, indent + 1, 'return jobj;') line(out, indent, '}') line(out) if returnType.isPrimitive(): line(out, indent, 'return (j%s) 0;', returnName) else: line(out, indent, 'return (jobject) NULL;') def python(env, out_h, out, cls, superCls, names, superNames, constructors, methods, protectedMethods, methodNames, fields, instanceFields, mapping, sequence, rename, declares, typeset, moduleName, generics, _dll_export): line(out_h) line(out_h, 0, '#include ') line(out_h) indent = 0 for name in names[:-1]: line(out_h, indent, 'namespace %s {', cppname(name)) indent += 1 line(out_h, indent, '%sextern PyTypeObject PY_TYPE(%s);', _dll_export, names[-1]) if generics: clsParams = getTypeParameters(cls) else: clsParams = None line(out_h) line(out_h, indent, 'class %st_%s {', _dll_export, names[-1]) line(out_h, indent, 'public:') line(out_h, indent + 1, 'PyObject_HEAD') line(out_h, indent + 1, '%s object;', cppname(names[-1])) if clsParams: line(out_h, indent + 1, 'PyTypeObject *parameters[%d];', len(clsParams)) line(out_h, indent + 1, 'static PyTypeObject **parameters_(t_%s *self)', cppname(names[-1])) line(out_h, indent + 1, '{') line(out_h, indent + 2, 'return (PyTypeObject **) &(self->parameters);') line(out_h, indent + 1, '}') line(out_h, indent + 1, 'static PyObject *wrap_Object(const %s&);', cppname(names[-1])) line(out_h, indent + 1, 'static PyObject *wrap_jobject(const jobject&);') if clsParams: _clsParams = ', '.join(['PyTypeObject *'] * len(clsParams)) line(out_h, indent + 1, 'static PyObject *wrap_Object(const %s&, %s);', cppname(names[-1]), _clsParams) line(out_h, indent + 1, 'static PyObject *wrap_jobject(const jobject&, %s);', _clsParams) line(out_h, indent + 1, 'static void install(PyObject *module);') line(out_h, indent + 1, 'static void initialize(PyObject *module);') line(out_h, indent, '};') if env.java_version >= '1.5': iterable = findClass('java/lang/Iterable') iterator = findClass('java/util/Iterator') else: iterable = iterator = None enumeration = findClass('java/util/Enumeration') while indent: indent -= 1 line(out_h, indent, '}') line(out) line(out, 0, '#include "structmember.h"') line(out, 0, '#include "functions.h"') line(out, 0, '#include "macros.h"') for inner in cls.getDeclaredClasses(): if inner in typeset and not inner in declares: if Modifier.isStatic(inner.getModifiers()): line(out, 0, '#include "%s.h"', inner.getName().replace('.', '/')) for method in methods: if method.getName() == 'pythonExtension': isExtension = True break else: isExtension = False line(out) indent = 0 for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out, indent, 'static PyObject *t_%s_cast_(PyTypeObject *type, PyObject *arg);', names[-1]) line(out, indent, 'static PyObject *t_%s_instance_(PyTypeObject *type, PyObject *arg);', names[-1]) if clsParams: line(out, indent, 'static PyObject *t_%s_of_(t_%s *self, PyObject *args);', names[-1], names[-1]) if constructors: line(out, indent, 'static int t_%s_init_(t_%s *self, PyObject *args, PyObject *kwds);', names[-1], names[-1]) constructorName = 't_%s_init_' %(names[-1]) else: constructorName = 'abstract_init' if superCls: superMethods = set([method.getName() for method in superCls.getMethods()]) else: superMethods = () allMethods = {} extMethods = {} propMethods = {} if methods: for method in methods: modifiers = method.getModifiers() name = method.getName() params = method.getParameterTypes() superMethod = None isNative = Modifier.isNative(modifiers) isStatic = Modifier.isStatic(modifiers) if (isExtension and not isStatic and superCls and isNative): superMethod = find_method(superCls, name, params) if isExtension and isNative and not isStatic: extMethods.setdefault(name, []).append(method) if superMethod or not (isExtension and isNative and not isStatic): if isStatic: if name in allMethods: if Modifier.isStatic(allMethods[name][0].getModifiers()): allMethods[name].append(method) elif name + RENAME_METHOD_SUFFIX in allMethods: allMethods[name + RENAME_METHOD_SUFFIX].append(method) else: print >>sys.stderr, " Warning: renaming static method '%s' on class %s to '%s%s' since it is shadowed by non-static method of same name." %(name, '.'.join(names), name, RENAME_METHOD_SUFFIX) allMethods[name + RENAME_METHOD_SUFFIX] = [method] else: allMethods[name] = [method] else: if name in allMethods: if Modifier.isStatic(allMethods[name][0].getModifiers()): print >>sys.stderr, " Warning: renaming static method '%s' on class %s to '%s%s' since it is shadowed by non-static method of same name." %(name, '.'.join(names), name, RENAME_METHOD_SUFFIX) allMethods[name + RENAME_METHOD_SUFFIX] = allMethods[name] allMethods[name] = [method] else: allMethods[name].append(method) else: allMethods[name] = [method] if not (isExtension and isNative): nameLen = len(name) paramsLen = len(params) if nameLen > 3 and paramsLen == 0 and name.startswith('get'): if method.getReturnType().getName() != 'void': propMethods.setdefault(name[3].lower() + name[4:], []).append(method) elif nameLen > 3 and paramsLen == 1 and name.startswith('set'): propMethods.setdefault(name[3].lower() + name[4:], []).append(method) elif nameLen > 2 and paramsLen == 0 and name.startswith('is'): if method.getReturnType().getName() != 'void': propMethods.setdefault(name[2].lower() + name[3:], []).append(method) properties = set([name for name in propMethods.iterkeys() if name not in allMethods]) propMethods = [(name, propMethods[name]) for name in properties] sort(propMethods, key=lambda x: x[0]) extMethods = extMethods.items() sort(extMethods, key=lambda x: x[0]) allMethods = allMethods.items() sort(allMethods, key=lambda x: x[0]) iteratorMethod = None iteratorExt = False nextMethod = None nextExt = False nextElementMethod = None nextElementExt = False mappingMethod = None if mapping: mappingName, mappingSig = mapping.split(':') sequenceLenMethod = None sequenceGetMethod = None if sequence: sequenceLenName, sequenceLenSig = sequence[0].split(':') sequenceGetName, sequenceGetSig = sequence[1].split(':') for name, methods in allMethods: args, x, cardinality = methodargs(methods, superMethods) sortSignatures(methods) method = methods[0] modifiers = method.getModifiers() if name == 'iterator' and iteratorMethod is None: if (iterable is not None and not method.getParameterTypes() and iterable.isAssignableFrom(cls) and iterator.isAssignableFrom(method.getReturnType())): iteratorMethod = method elif name == 'next' and nextMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextMethod = method elif name == 'nextElement' and nextElementMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextElementMethod = method elif mapping and name == mappingName and mappingMethod is None: if signature(method) == mappingSig: mappingMethod = (method, cardinality) elif sequence and name == sequenceLenName and sequenceLenMethod is None: if signature(method) == sequenceLenSig: sequenceLenMethod = (method, cardinality) elif sequence and name == sequenceGetName and sequenceGetMethod is None: if signature(method) == sequenceGetSig: sequenceGetMethod = (method, cardinality) elif isExtension and name == 'clone' and Modifier.isNative(modifiers): args, x, cardinality = ', PyObject *arg', ', arg', 1 if Modifier.isStatic(modifiers): line(out, indent, 'static PyObject *t_%s_%s(PyTypeObject *type%s);', names[-1], name, args) else: line(out, indent, 'static PyObject *t_%s_%s(t_%s *self%s);', names[-1], name, names[-1], args) for name, methods in extMethods: args, x, cardinality = methodargs(methods, superMethods) sortSignatures(methods) method = methods[0] modifiers = method.getModifiers() if name == 'iterator' and iteratorMethod is None: if (iterable is not None and not method.getParameterTypes() and iterable.isAssignableFrom(cls) and iterator.isAssignableFrom(method.getReturnType())): iteratorMethod = method iteratorExt = True elif name == 'next' and nextMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextMethod = method nextExt = True elif name == 'nextElement' and nextElementMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextElementMethod = method nextElementExt = True if isExtension: count = 0 for name, methods in extMethods: for method in methods: line(out, indent, 'static %s JNICALL t_%s_%s%d(JNIEnv *jenv, jobject jobj%s);', jniname(method.getReturnType()), names[-1], name, count, jniargs(method.getParameterTypes())) count += 1 line(out, indent, 'static PyObject *t_%s_get__self(t_%s *self, void *data);', names[-1], names[-1]) if instanceFields: for field in instanceFields: fieldName = field.getName() if fieldName not in properties: line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data);', names[-1], fieldName, names[-1]) if not Modifier.isFinal(field.getModifiers()): line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data);', names[-1], field.getName(), names[-1]) line(out) for fieldName, methods in propMethods: getter = False setter = False for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = True line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data);', names[-1], fieldName, names[-1]) elif not setter and methodName.startswith('set'): setter = True line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data);', names[-1], fieldName, names[-1]) if clsParams: line(out, indent, 'static PyObject *t_%s_get__parameters_(t_%s *self, void *data);', names[-1], names[-1]) if instanceFields or propMethods or isExtension or clsParams: line(out, indent, 'static PyGetSetDef t_%s__fields_[] = {', names[-1]) for field in instanceFields: fieldName = field.getName() if fieldName not in properties: if Modifier.isFinal(field.getModifiers()): line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, %s),', names[-1], fieldName) else: line(out, indent + 1, 'DECLARE_GETSET_FIELD(t_%s, %s),', names[-1], fieldName) for fieldName, methods in propMethods: getter = False setter = False for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = True elif not setter and methodName.startswith('set'): setter = True if getter and setter: op = 'GETSET' elif getter: op = 'GET' elif setter: op = 'SET' line(out, indent + 1, 'DECLARE_%s_FIELD(t_%s, %s),', op, names[-1], fieldName) if isExtension: line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, self),', names[-1]) if clsParams: line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, parameters_),', names[-1]) line(out, indent + 1, '{ NULL, NULL, NULL, NULL, NULL }') line(out, indent, '};') line(out) line(out, indent, 'static PyMethodDef t_%s__methods_[] = {', names[-1]) line(out, indent + 1, 'DECLARE_METHOD(t_%s, cast_, METH_O | METH_CLASS),', names[-1]) line(out, indent + 1, 'DECLARE_METHOD(t_%s, instance_, METH_O | METH_CLASS),', names[-1]) if clsParams: line(out, indent + 1, 'DECLARE_METHOD(t_%s, of_, METH_VARARGS),', names[-1]) for name, methods in allMethods: modifiers = methods[0].getModifiers() if len(methods) == 1 and not name in superMethods: count = len(methods[0].getParameterTypes()) if count == 0: args = 'METH_NOARGS' elif count == 1: args = 'METH_O' else: args = 'METH_VARARGS' elif isExtension and name == 'clone' and Modifier.isNative(modifiers): args = 'METH_O' else: args = 'METH_VARARGS' if Modifier.isStatic(modifiers): args += ' | METH_CLASS' line(out, indent + 1, 'DECLARE_METHOD(t_%s, %s, %s),', names[-1], name, args) line(out, indent + 1, '{ NULL, NULL, 0, NULL }') line(out, indent, '};') if instanceFields or propMethods or isExtension or clsParams: tp_getset = 't_%s__fields_' %(names[-1]) else: tp_getset = '0' if iteratorMethod: if iteratorExt: tp_iter = 'get_extension_iterator' else: tp_iter = '((PyObject *(*)(t_%s *)) get_%siterator< t_%s >)' %(names[-1], clsParams and 'generic_' or '', names[-1]) tp_iternext = '0' elif nextMethod and iterable is not None and iterator.isAssignableFrom(cls): tp_iter = 'PyObject_SelfIter' if nextExt: tp_iternext = 'get_extension_next' else: tp_iternext = '((PyObject *(*)(::java::util::t_Iterator *)) get_%siterator_next< ::java::util::t_Iterator,%s >)' %(clsParams and 'generic_' or '', wrapper_typename(nextMethod.getReturnType(), cls)) elif nextElementMethod and enumeration.isAssignableFrom(cls): tp_iter = 'PyObject_SelfIter' returnName = typename(nextElementMethod.getReturnType(), cls, False) ns, sep, n = rpartition(returnName, '::') if nextElementExt: tp_iternext = 'get_extension_nextElement' else: tp_iternext = '((PyObject *(*)(::java::util::t_Enumeration *)) get_%senumeration_next< ::java::util::t_Enumeration,%s >)' %(clsParams and 'generic_' or '', wrapper_typename(nextElementMethod.getReturnType(), cls)) elif nextMethod: tp_iter = 'PyObject_SelfIter' if nextExt: tp_iternext = 'get_extension_next' else: returnType = nextMethod.getReturnType() tp_iternext = '((PyObject *(*)(t_%s *)) get_%snext< t_%s,%s,%s >)' %(names[-1], clsParams and 'generic_' or '', names[-1], wrapper_typename(returnType, cls), typename(returnType, cls, False)) else: tp_iter = '0' tp_iternext = '0' if mappingMethod: method, cardinality = mappingMethod if cardinality > 1: getName = 't_%s_%s_map_' %(names[-1], method.getName()) line(out, indent, 'static PyObject *%s(t_%s *self, PyObject *key);', getName, names[-1]) else: getName = 't_%s_%s' %(names[-1], method.getName()) line(out) line(out, indent, 'static PyMappingMethods t_%s_as_mapping = {', names[-1]) line(out, indent + 1, '0,') line(out, indent + 1, '(binaryfunc) %s,', getName) line(out, indent + 1, '0,') line(out, indent, '};') tp_as_mapping = '&t_%s_as_mapping' %(names[-1]) else: tp_as_mapping = '0' if sequenceLenMethod or sequenceGetMethod: if sequenceLenMethod: method, cardinality = sequenceLenMethod lenName = 't_%s_%s_seq_' %(names[-1], method.getName()) line(out, indent, 'static int %s(t_%s *self);', lenName, names[-1]) else: lenName = '0' if sequenceGetMethod: method, cardinality = sequenceGetMethod getName = 't_%s_%s_seq_' %(names[-1], method.getName()) line(out, indent, 'static PyObject *%s(t_%s *self, int n);', getName, names[-1]) else: getName = '0' line(out) line(out, indent, 'static PySequenceMethods t_%s_as_sequence = {', names[-1]) if python_ver < '2.5.0': line(out, indent + 1, '(inquiry) %s,', lenName) line(out, indent + 1, '0,') line(out, indent + 1, '0,') line(out, indent + 1, '(intargfunc) %s', getName) line(out, indent, '};') else: line(out, indent + 1, '(lenfunc) %s,', lenName) line(out, indent + 1, '0,') line(out, indent + 1, '0,') line(out, indent + 1, '(ssizeargfunc) %s', getName) line(out, indent, '};') tp_as_sequence = '&t_%s_as_sequence' %(names[-1]) else: tp_as_sequence = '0' if len(superNames) > 1: base = '::'.join((absname(cppnames(superNames[:-1])), superNames[-1])) else: base = superNames[-1] line(out) line(out, indent, 'DECLARE_TYPE(%s, t_%s, %s, %s, %s, %s, %s, %s, %s, %s);', names[-1], names[-1], base, cppname(names[-1]), constructorName, tp_iter, tp_iternext, tp_getset, tp_as_mapping, tp_as_sequence) if clsParams: clsArgs = [] i = 0 for clsParam in clsParams: clsArgs.append("PyTypeObject *p%d" %(i)) i += 1 line(out, indent, "PyObject *t_%s::wrap_Object(const %s& object, %s)", cppname(names[-1]), names[-1], ', '.join(clsArgs)) line(out, indent, "{") line(out, indent + 1, "PyObject *obj = t_%s::wrap_Object(object);", names[-1]) line(out, indent + 1, "if (obj != NULL && obj != Py_None)") line(out, indent + 1, "{") line(out, indent + 2, "t_%s *self = (t_%s *) obj;", names[-1], names[-1]) i = 0; for clsParam in clsParams: line(out, indent + 2, "self->parameters[%d] = p%d;", i, i) i += 1 line(out, indent + 1, "}") line(out, indent + 1, "return obj;"); line(out, indent, "}") line(out) line(out, indent, "PyObject *t_%s::wrap_jobject(const jobject& object, %s)", cppname(names[-1]), ', '.join(clsArgs)) line(out, indent, "{") line(out, indent + 1, "PyObject *obj = t_%s::wrap_jobject(object);", names[-1]) line(out, indent + 1, "if (obj != NULL && obj != Py_None)") line(out, indent + 1, "{") line(out, indent + 2, "t_%s *self = (t_%s *) obj;", names[-1], names[-1]) i = 0; for clsParam in clsParams: line(out, indent + 2, "self->parameters[%d] = p%d;", i, i) i += 1 line(out, indent + 1, "}") line(out, indent + 1, "return obj;"); line(out, indent, "}") line(out) line(out, indent, 'void t_%s::install(PyObject *module)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'installType(&PY_TYPE(%s), module, "%s", %d);', names[-1], rename or names[-1], isExtension and 1 or 0) for inner in cls.getDeclaredClasses(): if inner in typeset: if Modifier.isStatic(inner.getModifiers()): innerName = inner.getName().split('.')[-1] line(out, indent + 1, 'PyDict_SetItemString(PY_TYPE(%s).tp_dict, "%s", make_descriptor(&PY_TYPE(%s)));', names[-1], innerName[len(names[-1])+1:], innerName) line(out, indent, '}') line(out) line(out, indent, 'void t_%s::initialize(PyObject *module)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'PyDict_SetItemString(PY_TYPE(%s).tp_dict, "class_", make_descriptor(%s::initializeClass, %s));', names[-1], cppname(names[-1]), generics and 1 or 0) if is_unboxed(cls.getName()): wrapfn_ = "unbox%s" %(names[-1]) boxfn_ = "box%s" %(names[-1]) else: wrapfn_ = "t_%s::wrap_jobject" %(names[-1]) boxfn_ = "boxObject" line(out, indent + 1, 'PyDict_SetItemString(PY_TYPE(%s).tp_dict, "wrapfn_", make_descriptor(%s));', names[-1], wrapfn_) line(out, indent + 1, 'PyDict_SetItemString(PY_TYPE(%s).tp_dict, "boxfn_", make_descriptor(%s));', names[-1], boxfn_) if isExtension: line(out, indent + 1, 'jclass cls = env->getClass(%s::initializeClass);', cppname(names[-1])) elif fields: line(out, indent + 1, 'env->getClass(%s::initializeClass);', cppname(names[-1])) if isExtension: count = 0 line(out, indent + 1, 'JNINativeMethod methods[] = {') for name, methods in extMethods: for method in methods: line(out, indent + 2, '{ "%s", "%s", (void *) t_%s_%s%d },', name, signature(method), names[-1], name, count) count += 1 line(out, indent + 1, '};') line(out, indent + 1, 'env->registerNatives(cls, methods, %d);', count) for field in fields: fieldType = field.getType() fieldName = field.getName() cppFieldName = cppname(fieldName) if cppFieldName in methodNames: fieldName += RENAME_FIELD_SUFFIX cppFieldName += RENAME_FIELD_SUFFIX value = '%s::%s' %(cppname(names[-1]), cppFieldName) value = fieldValue(cls, value, fieldType) line(out, indent + 1, 'PyDict_SetItemString(PY_TYPE(%s).tp_dict, "%s", make_descriptor(%s));', names[-1], fieldName, value) line(out, indent, '}') line(out) line(out, indent, 'static PyObject *t_%s_cast_(PyTypeObject *type, PyObject *arg)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!(arg = castCheck(arg, %s::initializeClass, 1)))', cppname(names[-1])) line(out, indent + 2, 'return NULL;') line(out, indent + 1, 'return t_%s::wrap_Object(%s(((t_%s *) arg)->object.this$));', names[-1], cppname(names[-1]), names[-1]) line(out, indent, '}') line(out, indent, 'static PyObject *t_%s_instance_(PyTypeObject *type, PyObject *arg)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!castCheck(arg, %s::initializeClass, 0))', cppname(names[-1])) line(out, indent + 2, 'Py_RETURN_FALSE;') line(out, indent + 1, 'Py_RETURN_TRUE;') line(out, indent, '}') if clsParams: line(out) line(out, indent, 'static PyObject *t_%s_of_(t_%s *self, PyObject *args)', names[-1], names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!parseArg(args, "T", %d, &(self->parameters)))', len(clsParams)) line(out, indent + 2, 'Py_RETURN_SELF;'); line(out, indent + 1, 'return PyErr_SetArgsError((PyObject *) self, "of_", args);') line(out, indent, '}') if constructors: line(out) line(out, indent, 'static int t_%s_init_(t_%s *self, PyObject *args, PyObject *kwds)', names[-1], names[-1]) line(out, indent, '{') if len(constructors) > 1: currLen = -1 line(out, indent + 1, 'switch (PyTuple_GET_SIZE(args)) {') withErr = False for constructor in constructors: params = constructor.getParameterTypes() if len(params) != currLen: if currLen >= 0: withErr = True line(out, indent + 2, 'goto err;') currLen = len(params) line(out, indent + 1, '%scase %d:', HALF_INDENT, currLen) construct(out, indent + 2, cls, True, constructor, names, generics) line(out, indent + 1, '%sdefault:', HALF_INDENT) if withErr: line(out, indent + 1, '%serr:', HALF_INDENT) line(out, indent + 2, 'PyErr_SetArgsError((PyObject *) self, "__init__", args);') line(out, indent + 2, 'return -1;') line(out, indent + 1, '}') else: construct(out, indent + 1, cls, False, constructors[0], names, generics) if constructors[0].getParameterTypes(): line(out, indent + 1, 'else') line(out, indent + 1, '{') line(out, indent + 2, 'PyErr_SetArgsError((PyObject *) self, "__init__", args);') line(out, indent + 2, 'return -1;') line(out, indent + 1, '}') if isExtension: line(out) line(out, indent + 1, 'Py_INCREF((PyObject *) self);') line(out, indent + 1, 'self->object.pythonExtension((jlong) (Py_intptr_t) (void *) self);') line(out) line(out, indent + 1, 'return 0;') line(out, indent , '}') for name, methods in allMethods: line(out) modifiers = methods[0].getModifiers() if isExtension and name == 'clone' and Modifier.isNative(modifiers): declargs, args, cardinality = ', PyObject *arg', ', arg', 1 else: declargs, args, cardinality = methodargs(methods, superMethods) static = Modifier.isStatic(modifiers) if static: line(out, indent, 'static PyObject *t_%s_%s(PyTypeObject *type%s)', names[-1], name, declargs) else: line(out, indent, 'static PyObject *t_%s_%s(t_%s *self%s)', names[-1], name, names[-1], declargs) line(out, indent, '{') if len(methods) > 1: currLen = -1 line(out, indent + 1, 'switch (PyTuple_GET_SIZE(args)) {') for method in methods: params = method.getParameterTypes() if len(params) != currLen: if currLen >= 0: line(out, indent + 2, 'break;') currLen = len(params) line(out, indent + 1, '%scase %d:', HALF_INDENT, currLen) call(out, indent + 2, cls, True, method, names, cardinality, isExtension, generics) line(out, indent + 1, '}') else: call(out, indent + 1, cls, False, methods[0], names, cardinality, isExtension, generics) if args: line(out) if name in superMethods: if static: line(out, indent + 1, 'return callSuper(type, "%s"%s, %d);', name, args, cardinality) else: line(out, indent + 1, 'return callSuper(&PY_TYPE(%s), (PyObject *) self, "%s"%s, %d);', names[-1], name, args, cardinality) else: line(out, indent + 1, 'PyErr_SetArgsError(%s, "%s"%s);', static and 'type' or '(PyObject *) self', name, args) line(out, indent + 1, 'return NULL;') line(out, indent, '}') if isExtension: count = 0 for name, methods in extMethods: for method in methods: line(out) line(out, indent, 'static %s JNICALL t_%s_%s%d(JNIEnv *jenv, jobject jobj%s)', jniname(method.getReturnType()), names[-1], name, count, jniargs(method.getParameterTypes())) count += 1 line(out, indent, '{') extension(env, out, indent + 1, cls, names, name, count, method, generics) line(out, indent, '}') line(out) line(out, indent, 'static PyObject *t_%s_get__self(t_%s *self, void *data)', names[-1], names[-1]) line(out, indent, '{') indent += 1 line(out, indent, 'jlong ptr;') line(out, indent, 'OBJ_CALL(ptr = self->object.pythonExtension());') line(out, indent, 'PyObject *obj = (PyObject *) (Py_intptr_t) ptr;') line(out) line(out, indent, 'if (obj != NULL)') line(out, indent, '{') line(out, indent + 1, 'Py_INCREF(obj);') line(out, indent + 1, 'return obj;') line(out, indent, '}') line(out, indent, 'else') line(out, indent + 1, 'Py_RETURN_NONE;') indent -= 1 line(out, indent, '}') if clsParams: line(out, indent, 'static PyObject *t_%s_get__parameters_(t_%s *self, void *data)', names[-1], names[-1]) line(out, indent, '{') line(out, indent + 1, 'return typeParameters(self->parameters, sizeof(self->parameters));') line(out, indent, '}') if instanceFields: for field in instanceFields: fieldName = field.getName() if fieldName not in properties: line(out) fieldType = field.getType() typeName = typename(fieldType, cls, False) line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not fieldType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(value = self->object._get_%s());', fieldName) line(out, indent + 1, returnValue(cls, fieldType, 'value')) line(out, indent, '}') if not Modifier.isFinal(field.getModifiers()): line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not fieldType.isPrimitive() and '((jobject) NULL)' or '') sig, check, x = parseArgs([fieldType], cls, False) line(out, indent + 1, 'if (!parseArg(arg, "%s"%s, &value))', sig, check) line(out, indent + 1, '{') line(out, indent + 2, 'INT_CALL(self->object._set_%s(value));', fieldName) line(out, indent + 2, 'return 0;') line(out, indent + 1, '}') line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', fieldName) line(out, indent + 1, 'return -1;') line(out, indent, '}') if propMethods: for fieldName, methods in propMethods: line(out) getter = None setters = [] sort(methods, key=lambda x: x.getName()) for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = method elif methodName.startswith('set'): setters.append(method) if getter: methodName = getter.getName() returnType = getter.getReturnType() typeName = typename(returnType, cls, False) line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not returnType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(value = self->object.%s());', methodName) line(out, indent + 1, returnValue(cls, returnType, 'value')) line(out, indent, '}') if setters: line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') methodName = setters[0].getName() for method in setters: argType = method.getParameterTypes()[0] typeName = typename(argType, cls, False) line(out, indent + 1, '{') line(out, indent + 2, '%s value%s;', typeName, not argType.isPrimitive() and '((jobject) NULL)' or '') sig, check, x = parseArgs([argType], cls, False) line(out, indent + 2, 'if (!parseArg(arg, "%s"%s, &value))', sig, check) line(out, indent + 2, '{') line(out, indent + 3, 'INT_CALL(self->object.%s(value));', methodName) line(out, indent + 3, 'return 0;') line(out, indent + 2, '}') line(out, indent + 1, '}') line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', fieldName) line(out, indent + 1, 'return -1;') line(out, indent, '}') if mappingMethod: method, cardinality = mappingMethod if cardinality > 1: methodName = method.getName() getName = 't_%s_%s_map_' %(names[-1], methodName) line(out) line(out, indent, 'static PyObject *%s(t_%s *self, PyObject *arg)', getName, names[-1]) line(out, indent, '{') call(out, indent + 1, cls, False, method, names, 1, isExtension, generics) line(out) line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', methodName) line(out, indent + 1, 'return NULL;') line(out, indent, '}') if sequenceLenMethod: method, cardinality = sequenceLenMethod methodName = method.getName() lenName = 't_%s_%s_seq_' %(names[-1], methodName) line(out) line(out, indent, 'static int %s(t_%s *self)', lenName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s len;', typename(method.getReturnType(), cls, False)) line(out, indent + 1, 'INT_CALL(len = self->object.%s());', methodName) line(out, indent + 1, 'return (int) len;') line(out, indent, '}') if sequenceGetMethod: method, cardinality = sequenceGetMethod methodName = method.getName() returnType = method.getReturnType() getName = 't_%s_%s_seq_' %(names[-1], methodName) line(out) line(out, indent, 'static PyObject *%s(t_%s *self, int n)', getName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s result%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(result = self->object.%s((%s) n));', methodName, typename(method.getParameterTypes()[0], cls, False)) if generics: line(out, indent + 1, returnValue(cls, returnType, 'result', method.getGenericReturnType())) else: line(out, indent + 1, returnValue(cls, returnType, 'result')) line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') def package(out, allInOne, cppdir, namespace, names, use_full_names): if not allInOne: out = file(os.path.join(os.path.join(cppdir, *names), '__init__.cpp'), 'w') if allInOne and not names or not allInOne: line(out, 0, '#include ') line(out, 0, '#include ') line(out, 0, '#include "JCCEnv.h"') line(out, 0, '#include "functions.h"') if not names or not allInOne: line(out) line(out, 0, 'PyObject *initVM(PyObject *module, PyObject *args, PyObject *kwds);') if use_full_names: line(out, 0, 'PyObject *getJavaModule(PyObject *module, const char *parent, const char *name);') packages = [] types = [] namespaces = namespace.items() sort(namespaces, key=lambda x: x[0]) for name, entries in namespaces: if entries is True: if names: line(out, 0, '#include "%s/%s.h"', '/'.join(names), name) else: line(out, 0, '#include "%s.h"', name) types.append(name) else: packages.append((name, entries)) indent = 0 if names: line(out) for name in names: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out); for name, entries in packages: line(out, indent, 'namespace %s {', cppname(name)) line(out, indent + 1, 'void __install__(PyObject *module);') line(out, indent + 1, 'void __initialize__(PyObject *module);') line(out, indent, '}') line(out) line(out, indent, 'void __install__(PyObject *module)') line(out, indent, '{') if use_full_names and names: parent_name = '.'.join(names[:-1]) line(out, indent + 1, 'module = getJavaModule(module, "%s", "%s");', parent_name, names[-1]) line(out) for name in types: line(out, indent + 1, 't_%s::install(module);', name) for name, entries in packages: line(out, indent + 1, '%s::__install__(module);', cppname(name)) line(out, indent, '}') line(out) if not names: line(out, indent, 'PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds)') line(out, indent, '{') line(out, indent + 1, 'PyObject *env = initVM(module, args, kwds);') line(out) line(out, indent + 1, 'if (env == NULL)') line(out, indent + 2, 'return NULL;') line(out) line(out, indent + 1, 'try {'); indent += 1 else: line(out, indent, 'void __initialize__(PyObject *module)') line(out, indent, '{') if use_full_names and names: line(out, indent + 1, 'module = getJavaModule(module, "%s", "%s");', parent_name, names[-1]) line(out) for name in types: line(out, indent + 1, 't_%s::initialize(module);', name) for name, entries in packages: line(out, indent + 1, '%s::__initialize__(module);', cppname(name)) if not names: line(out, indent + 1, 'return env;') indent -= 1 line(out, indent + 1, '} catch (int e) {') line(out, indent + 2, 'switch(e) {') line(out, indent + 2, ' case _EXC_JAVA:') line(out, indent + 3, 'return PyErr_SetJavaError();') line(out, indent + 2, ' default:') line(out, indent + 3, 'throw;') line(out, indent + 2, '}') line(out, indent + 1, '}') line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') if not allInOne: out.close() else: line(out) for name, entries in packages: package(out, allInOne, cppdir, entries, names + (name,), use_full_names) def module(out, allInOne, classes, imports, cppdir, moduleName, shared, generics, use_full_names): extname = '_%s' %(moduleName) line(out, 0, '#include ') line(out, 0, '#include "macros.h"') line(out, 0, '#include "jccfuncs.h"') if allInOne: out_init = file(os.path.join(cppdir, '__init__.cpp'), 'w') namespaces = {} for cls in classes: for importset in imports.itervalues(): if cls in importset: break else: namespace = namespaces classNames = cls.getName().split('.') for className in classNames[:-1]: namespace = namespace.setdefault(className, {}) namespace[classNames[-1]] = True if allInOne: package(out_init, True, cppdir, namespaces, (), use_full_names) out_init.close() else: package(None, False, cppdir, namespaces, (), use_full_names) line(out) line(out, 0, 'PyObject *initJCC(PyObject *module);') line(out, 0, 'void __install__(PyObject *module);') line(out, 0, 'extern PyTypeObject PY_TYPE(JObject), PY_TYPE(ConstVariableDescriptor), PY_TYPE(FinalizerClass), PY_TYPE(FinalizerProxy);') line(out, 0, 'extern void _install_jarray(PyObject *);') line(out) line(out, 0, 'extern "C" {') line(out) line(out, 1, 'void init%s(void)', extname) line(out, 1, '{') line(out, 2, 'PyObject *module = Py_InitModule3("%s", jcc_funcs, "");', extname); line(out) line(out, 2, 'initJCC(module);') line(out) line(out, 2, 'INSTALL_TYPE(JObject, module);') line(out, 2, 'INSTALL_TYPE(ConstVariableDescriptor, module);') line(out, 2, 'INSTALL_TYPE(FinalizerClass, module);') line(out, 2, 'INSTALL_TYPE(FinalizerProxy, module);') line(out, 2, '_install_jarray(module);') line(out, 2, '__install__(module);') line(out, 1, '}') line(out, 0, '}') def compile(env, jccPath, output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, home_dir, use_distutils, shared, compiler, modules, wininst, find_jvm_dll, arch, generics, resources, imports, use_full_names, egg_info, extra_setup_args): try: if use_distutils: raise ImportError from setuptools import setup, Extension with_setuptools = True if shared and not SHARED: raise NotImplementedError, "JCC was not built with --shared mode support, see JCC's INSTALL file for more information" except ImportError: if python_ver < '2.4': raise ImportError, 'setuptools is required when using Python 2.3' if shared: raise ImportError, 'setuptools is required when using --shared' from distutils.core import setup, Extension with_setuptools = False extname = '_%s' %(moduleName) modulePath = os.path.join(output, moduleName) if not os.path.isdir(modulePath): os.makedirs(modulePath) out = file(os.path.join(modulePath, '__init__.py'), 'w') line(out) if shared: line(out, 0, "import os, sys") line(out) line(out, 0, "if sys.platform == 'win32':") if find_jvm_dll: line(out, 1, "from jcc.windows import add_jvm_dll_directory_to_path") line(out, 1, "add_jvm_dll_directory_to_path()") line(out, 1, "import jcc, %s", extname) line(out, 0, "else:") line(out, 1, "import %s", extname) else: line(out, 0, 'import os, %s', extname) line(out) line(out, 0, '__dir__ = os.path.abspath(os.path.dirname(__file__))') package_data = [] for jar in jars: shutil.copy2(jar, modulePath) package_data.append(os.path.basename(jar)) if resources: def copytree(src, dst): _dst = os.path.join(modulePath, dst) if not os.path.exists(_dst): os.mkdir(_dst) for name in os.listdir(src): if name.startswith('.'): continue _src = os.path.join(src, name) if os.path.islink(_src): continue _dst = os.path.join(dst, name) if os.path.isdir(_src): copytree(_src, _dst) else: shutil.copy2(_src, os.path.join(modulePath, _dst)) package_data.append(_dst) for resource in resources: copytree(resource, os.path.split(resource)[-1]) packages = [moduleName] package = [moduleName] if modules: for module in modules: if os.path.isdir(module): def copytree(src, dst, is_package): if is_package: packages.append('.'.join(package)) if not os.path.exists(dst): os.mkdir(dst) for name in os.listdir(src): if name.startswith('.'): continue _src = os.path.join(src, name) if os.path.islink(_src): continue _dst = os.path.join(dst, name) if os.path.isdir(_src): package.append(os.path.basename(_src)) copytree(_src, _dst, os.path.exists(os.path.join(_src, '__init__.py'))) package.pop() elif not is_package or name.endswith('.py'): shutil.copy2(_src, _dst) dst = modulePath if os.path.exists(os.path.join(module, '__init__.py')): dst = os.path.join(modulePath, os.path.basename(module)) package.append(os.path.basename(module)) copytree(module, dst, True) package.pop() else: copytree(module, dst, False) else: shutil.copy2(rpartition(module, '.')[0] + '.py', modulePath) line(out) line(out, 0, 'class JavaError(Exception):') line(out, 1, 'def getJavaException(self):') line(out, 2, 'return self.args[0]') line(out, 1, 'def __str__(self):') line(out, 2, 'writer = StringWriter()') line(out, 2, 'self.getJavaException().printStackTrace(PrintWriter(writer))') line(out, 2, 'return u"\\n".join((unicode(super(JavaError, self)), u" Java stacktrace:", unicode(writer)))') line(out) line(out, 0, 'class InvalidArgsError(Exception):') line(out, 1, 'pass') line(out) line(out, 0, '%s._set_exception_types(JavaError, InvalidArgsError)', extname) if version: line(out) line(out, 0, 'VERSION = "%s"', version) line(out, 0, 'CLASSPATH = [%s]' %(', '.join(['os.path.join(__dir__, "%s")' %(os.path.basename(jar)) for jar in jars]))) line(out, 0, 'CLASSPATH = os.pathsep.join(CLASSPATH)') line(out, 0, '%s.CLASSPATH = CLASSPATH', extname) line(out, 0, '%s._set_function_self(%s.initVM, %s)', extname, extname, extname) line(out) for import_ in imports: line(out, 0, 'from %s._%s import *', import_.__name__, import_.__name__) line(out, 0, 'from %s import *', extname) if use_full_names: line(out, 0, 'from java.io import PrintWriter, StringWriter') out.close() includes = [os.path.join(output, extname), os.path.join(jccPath, 'sources')] for import_ in imports: includes.append(os.path.join(import_.__dir__, 'include')) sources = ['JObject.cpp', 'JArray.cpp', 'functions.cpp', 'types.cpp'] if not shared: sources.append('jcc.cpp') sources.append('JCCEnv.cpp') for source in sources: shutil.copy2(os.path.join(jccPath, 'sources', source), os.path.join(output, extname)) if shared: def copytree(src, dst): _dst = os.path.join(modulePath, dst) if not os.path.exists(_dst): os.mkdir(_dst) for name in os.listdir(src): if name.startswith('.'): continue _src = os.path.join(src, name) if os.path.islink(_src): continue _dst = os.path.join(dst, name) if os.path.isdir(_src): copytree(_src, _dst) elif name.endswith('.h'): shutil.copy2(_src, os.path.join(modulePath, _dst)) package_data.append(_dst) copytree(os.path.join(output, extname), 'include') sources = [] for path, dirs, names in os.walk(os.path.join(output, extname)): for name in names: if name.endswith('.cpp'): sources.append(os.path.join(path, name)) if egg_info: script_args = ['egg_info'] else: script_args = ['build_ext'] includes[0:0] = INCLUDES compile_args = CFLAGS link_args = LFLAGS defines=[('PYTHON', None), ('JCC_VER', '"%s"' %(JCC_VER))] if shared: defines.append(('_jcc_shared', None)) if generics: defines.append(('_java_generics', None)) if compiler: script_args.append('--compiler=%s' %(compiler)) if debug: script_args.append('--debug') compile_args += DEBUG_CFLAGS elif sys.platform == 'win32': pass elif sys.platform == 'sunos5': link_args.append('-Wl,-s') else: link_args.append('-Wl,-S') if install: script_args.append('install') if prefix: script_args.append('--prefix=%s' % prefix) if root: script_args.append('--root=%s' % root) if install_dir: script_args.append('--install-lib=%s' % install_dir) if home_dir: script_args.append('--home=%s' % home_dir) if dist: if wininst: script_args.append('bdist_wininst') elif with_setuptools: script_args.append('bdist_egg') else: script_args.append('bdist') args = { 'extra_compile_args': compile_args, 'extra_link_args': link_args, 'include_dirs': includes, 'sources': sources, 'define_macros': defines } if shared: shlibdir = os.path.dirname(os.path.dirname(_jcc2.__file__)) if sys.platform == 'darwin': # distutils no good with -R machine = platform.machine() if machine.startswith('iPod') or machine.startswith('iPhone'): args['extra_link_args'] += ['-L' + shlibdir] else: args['extra_link_args'] += ['-Wl,-rpath', shlibdir] args['library_dirs'] = [shlibdir] args['libraries'] = ['jcc2'] elif sys.platform == 'linux2': # distutils no good with -R args['extra_link_args'] += ['-Wl,-rpath', shlibdir] args['library_dirs'] = [shlibdir] args['libraries'] = ['jcc2'] args['extra_link_args'] += [ getattr(import_, "_%s" %(import_.__name__)).__file__ for import_ in imports ] elif sys.platform == 'win32': _d = debug and '_d' or '' libdir = os.path.join(modulePath, 'lib') if not os.path.exists(libdir): os.mkdir(libdir) extlib = os.path.join('lib', "%s%s.lib" %(extname, _d)) package_data.append(extlib) args['extra_link_args'] += [ os.path.join(shlibdir, 'jcc2', 'jcc2%s.lib' %(_d)), ' '.join(IMPLIB_LFLAGS) %(os.path.join(modulePath, extlib)) ] args['libraries'] = [ os.path.join(import_.__dir__, 'lib', '_%s%s' %(import_.__name__, _d)) for import_ in imports ] args['define_macros'] += [ ("_dll_%s" %(import_.__name__), '__declspec(dllimport)') for import_ in imports ] + [("_dll_%s" %(moduleName), '__declspec(dllexport)')] else: raise NotImplementedError, "shared mode on %s" %(sys.platform) if arch and sys.platform == 'darwin': from distutils import sysconfig config_vars = sysconfig.get_config_vars() cflags = config_vars['CFLAGS'].split(' ') count = len(cflags) i = 0 while i < count - 1: if cflags[i] == '-arch' and cflags[i + 1] not in arch: del cflags[i:i+2] count -= 2 else: i += 1 config_vars['CFLAGS'] = ' '.join(cflags) extensions = [Extension('.'.join([moduleName, extname]), **args)] script_args.extend(extra_setup_args) args = { 'name': moduleName, 'packages': packages, 'package_dir': {moduleName: modulePath}, 'package_data': {moduleName: package_data}, 'ext_modules': extensions, 'script_args': script_args } if version: args['version'] = version if with_setuptools: args['zip_safe'] = False print "setup args = %s" % args setup(**args) JCC-3.6/jcc2/sources/0000755000076500000000000000000013536235634014502 5ustar vajdawheel00000000000000JCC-3.6/jcc2/sources/jcc.cpp0000644000076500000000000006702413360725147015754 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #ifdef linux #include #endif #include #include "structmember.h" #include "JObject.h" #include "JCCEnv.h" #include "macros.h" _DLL_EXPORT JCCEnv *env; /* JCCEnv */ class t_jccenv { public: PyObject_HEAD JCCEnv *env; }; static void t_jccenv_dealloc(t_jccenv *self); static PyObject *t_jccenv_attachCurrentThread(PyObject *self, PyObject *args); static PyObject *t_jccenv_detachCurrentThread(PyObject *self); static PyObject *t_jccenv_isCurrentThreadAttached(PyObject *self); static PyObject *t_jccenv_isShared(PyObject *self); static PyObject *t_jccenv_strhash(PyObject *self, PyObject *arg); static PyObject *t_jccenv__dumpRefs(PyObject *self, PyObject *args, PyObject *kwds); static PyObject *t_jccenv__addClassPath(PyObject *self, PyObject *args); static PyObject *t_jccenv__get_jni_version(PyObject *self, void *data); static PyObject *t_jccenv__get_java_version(PyObject *self, void *data); static PyObject *t_jccenv__get_classpath(PyObject *self, void *data); static PyGetSetDef t_jccenv_properties[] = { { "jni_version", (getter) t_jccenv__get_jni_version, NULL, NULL, NULL }, { "java_version", (getter) t_jccenv__get_java_version, NULL, NULL, NULL }, { "classpath", (getter) t_jccenv__get_classpath, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static PyMemberDef t_jccenv_members[] = { { NULL, 0, 0, 0, NULL } }; static PyMethodDef t_jccenv_methods[] = { { "attachCurrentThread", (PyCFunction) t_jccenv_attachCurrentThread, METH_VARARGS, NULL }, { "detachCurrentThread", (PyCFunction) t_jccenv_detachCurrentThread, METH_NOARGS, NULL }, { "isCurrentThreadAttached", (PyCFunction) t_jccenv_isCurrentThreadAttached, METH_NOARGS, NULL }, { "isShared", (PyCFunction) t_jccenv_isShared, METH_NOARGS, NULL }, { "strhash", (PyCFunction) t_jccenv_strhash, METH_O, NULL }, { "_dumpRefs", (PyCFunction) t_jccenv__dumpRefs, METH_VARARGS | METH_KEYWORDS, NULL }, { "_addClassPath", (PyCFunction) t_jccenv__addClassPath, METH_VARARGS, NULL }, { NULL, NULL, 0, NULL } }; PyTypeObject PY_TYPE(JCCEnv) = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "jcc.JCCEnv", /* tp_name */ sizeof(t_jccenv), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_jccenv_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "JCCEnv", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ t_jccenv_methods, /* tp_methods */ t_jccenv_members, /* tp_members */ t_jccenv_properties, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static void t_jccenv_dealloc(t_jccenv *self) { self->ob_type->tp_free((PyObject *) self); } static void add_option(char *name, char *value, JavaVMOption *option) { char *buf = (char *) malloc(strlen(name) + strlen(value) + 1); sprintf(buf, "%s%s", name, value); option->optionString = buf; } #ifdef _jcc_lib static void add_paths(char *name, char *p0, char *p1, JavaVMOption *option) { #if defined(_MSC_VER) || defined(__WIN32) char pathsep = ';'; #else char pathsep = ':'; #endif char *buf = (char *) malloc(strlen(name) + strlen(p0) + strlen(p1) + 4); sprintf(buf, "%s%s%c%s", name, p0, pathsep, p1); option->optionString = buf; } #endif static PyObject *t_jccenv_attachCurrentThread(PyObject *self, PyObject *args) { char *name = NULL; int asDaemon = 0, result; if (!PyArg_ParseTuple(args, "|si", &name, &asDaemon)) return NULL; result = env->attachCurrentThread(name, asDaemon); return PyInt_FromLong(result); } static PyObject *t_jccenv_detachCurrentThread(PyObject *self) { int result = env->vm->DetachCurrentThread(); env->set_vm_env(NULL); return PyInt_FromLong(result); } static PyObject *t_jccenv_isCurrentThreadAttached(PyObject *self) { if (env->get_vm_env() != NULL) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyObject *t_jccenv_isShared(PyObject *self) { #ifdef _jcc_lib Py_RETURN_TRUE; #else Py_RETURN_FALSE; #endif } static PyObject *t_jccenv_strhash(PyObject *self, PyObject *arg) { int hash = PyObject_Hash(arg); char buffer[10]; sprintf(buffer, "%08x", (unsigned int) hash); return PyString_FromStringAndSize(buffer, 8); } static PyObject *t_jccenv__dumpRefs(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwnames[] = { "classes", "values", NULL }; int classes = 0, values = 0; PyObject *result; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwnames, &classes, &values)) return NULL; if (classes) result = PyDict_New(); else result = PyList_New(env->refs.size()); int count = 0; for (std::multimap::iterator iter = env->refs.begin(); iter != env->refs.end(); iter++) { if (classes) // return dict of { class name: instance count } { char *name = env->getClassName(iter->second.global); PyObject *key = PyString_FromString(name); PyObject *value = PyDict_GetItem(result, key); if (value == NULL) value = PyInt_FromLong(1); else value = PyInt_FromLong(PyInt_AS_LONG(value) + 1); PyDict_SetItem(result, key, value); Py_DECREF(key); Py_DECREF(value); delete name; } else if (values) // return list of (value string, ref count) { char *str = env->toString(iter->second.global); PyObject *key = PyString_FromString(str); PyObject *value = PyInt_FromLong(iter->second.count); #if PY_VERSION_HEX < 0x02040000 PyList_SET_ITEM(result, count++, Py_BuildValue("(OO)", key, value)); #else PyList_SET_ITEM(result, count++, PyTuple_Pack(2, key, value)); #endif Py_DECREF(key); Py_DECREF(value); delete str; } else // return list of (id hash code, ref count) { PyObject *key = PyInt_FromLong(iter->first); PyObject *value = PyInt_FromLong(iter->second.count); #if PY_VERSION_HEX < 0x02040000 PyList_SET_ITEM(result, count++, Py_BuildValue("(OO)", key, value)); #else PyList_SET_ITEM(result, count++, PyTuple_Pack(2, key, value)); #endif Py_DECREF(key); Py_DECREF(value); } } return result; } static PyObject *t_jccenv__addClassPath(PyObject *self, PyObject *args) { const char *classpath; if (!PyArg_ParseTuple(args, "s", &classpath)) return NULL; env->setClassPath(classpath); Py_RETURN_NONE; } static PyObject *t_jccenv__get_jni_version(PyObject *self, void *data) { return PyInt_FromLong(env->getJNIVersion()); } static PyObject *t_jccenv__get_java_version(PyObject *self, void *data) { return env->fromJString(env->getJavaVersion(), 1); } static PyObject *t_jccenv__get_classpath(PyObject *self, void *data) { char *classpath = env->getClassPath(); if (classpath) { PyObject *result = PyString_FromString(classpath); free(classpath); return result; } Py_RETURN_NONE; } _DLL_EXPORT PyObject *getVMEnv(PyObject *self) { if (env->vm != NULL) { t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv).tp_alloc(&PY_TYPE(JCCEnv), 0); jccenv->env = env; return (PyObject *) jccenv; } Py_RETURN_NONE; } #ifdef _jcc_lib static void registerNatives(JNIEnv *vm_env); #endif _DLL_EXPORT PyObject *initJCC(PyObject *module) { static int _once_only = 1; #if defined(_MSC_VER) || defined(__WIN32) #define verstring(n) #n PyObject *ver = PyString_FromString(verstring(JCC_VER)); #else PyObject *ver = PyString_FromString(JCC_VER); #endif PyObject_SetAttrString(module, "JCC_VERSION", ver); Py_DECREF(ver); if (_once_only) { PyEval_InitThreads(); INSTALL_TYPE(JCCEnv, module); if (env == NULL) env = new JCCEnv(NULL, NULL); _once_only = 0; Py_RETURN_TRUE; } Py_RETURN_FALSE; } _DLL_EXPORT PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwnames[] = { "classpath", "initialheap", "maxheap", "maxstack", "vmargs", NULL }; char *classpath = NULL; char *initialheap = NULL, *maxheap = NULL, *maxstack = NULL; PyObject *vmargs = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zzzzO", kwnames, &classpath, &initialheap, &maxheap, &maxstack, &vmargs)) return NULL; if (env->vm) { PyObject *module_cp = NULL; if (initialheap || maxheap || maxstack || vmargs) { PyErr_SetString(PyExc_ValueError, "JVM is already running, options are ineffective"); return NULL; } if (classpath == NULL && self != NULL) { module_cp = PyObject_GetAttrString(self, "CLASSPATH"); if (module_cp != NULL) classpath = PyString_AsString(module_cp); } if (classpath && classpath[0]) env->setClassPath(classpath); Py_XDECREF(module_cp); return getVMEnv(self); } else { JavaVMInitArgs vm_args; JavaVMOption vm_options[32]; JNIEnv *vm_env; JavaVM *vm; unsigned int nOptions = 0; PyObject *module_cp = NULL; vm_args.version = JNI_VERSION_1_4; JNI_GetDefaultJavaVMInitArgs(&vm_args); if (classpath == NULL && self != NULL) { module_cp = PyObject_GetAttrString(self, "CLASSPATH"); if (module_cp != NULL) classpath = PyString_AsString(module_cp); } #ifdef _jcc_lib PyObject *jcc = PyImport_ImportModule("jcc"); PyObject *cp = PyObject_GetAttrString(jcc, "CLASSPATH"); if (classpath) add_paths("-Djava.class.path=", PyString_AsString(cp), classpath, &vm_options[nOptions++]); else add_option("-Djava.class.path=", PyString_AsString(cp), &vm_options[nOptions++]); Py_DECREF(cp); Py_DECREF(jcc); #else if (classpath) add_option("-Djava.class.path=", classpath, &vm_options[nOptions++]); #endif Py_XDECREF(module_cp); if (initialheap) add_option("-Xms", initialheap, &vm_options[nOptions++]); if (maxheap) add_option("-Xmx", maxheap, &vm_options[nOptions++]); if (maxstack) add_option("-Xss", maxstack, &vm_options[nOptions++]); if (vmargs != NULL && PyString_Check(vmargs)) { #ifdef _MSC_VER char *buf = _strdup(PyString_AS_STRING(vmargs)); #else char *buf = strdup(PyString_AS_STRING(vmargs)); #endif char *sep = ","; char *option; for (option = strtok(buf, sep); option != NULL; option = strtok(NULL, sep)) { if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption)) add_option("", option, &vm_options[nOptions++]); else { free(buf); for (unsigned int i = 0; i < nOptions; i++) free(vm_options[i].optionString); PyErr_Format(PyExc_ValueError, "Too many options (> %d)", nOptions); return NULL; } } free(buf); } else if (vmargs != NULL && PySequence_Check(vmargs)) { PyObject *fast = PySequence_Fast(vmargs, "error converting vmargs to a tuple"); if (fast == NULL) return NULL; for (int i = 0; i < PySequence_Fast_GET_SIZE(fast); ++i) { PyObject *arg = PySequence_Fast_GET_ITEM(fast, i); if (PyString_Check(arg)) { char *option = PyString_AS_STRING(arg); if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption)) add_option("", option, &vm_options[nOptions++]); else { for (unsigned int j = 0; j < nOptions; j++) free(vm_options[j].optionString); PyErr_Format(PyExc_ValueError, "Too many options (> %d)", nOptions); Py_DECREF(fast); return NULL; } } else { for (unsigned int j = 0; j < nOptions; j++) free(vm_options[j].optionString); PyErr_Format(PyExc_TypeError, "vmargs arg %d is not a string", i); Py_DECREF(fast); return NULL; } } Py_DECREF(fast); } else if (vmargs != NULL) { PyErr_SetString(PyExc_TypeError, "vmargs is not a string or sequence"); return NULL; } //vm_options[nOptions++].optionString = "-verbose:gc"; //vm_options[nOptions++].optionString = "-Xcheck:jni"; vm_args.nOptions = nOptions; vm_args.ignoreUnrecognized = JNI_FALSE; vm_args.options = vm_options; if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0) { for (unsigned int i = 0; i < nOptions; i++) free(vm_options[i].optionString); PyErr_Format(PyExc_ValueError, "An error occurred while creating Java VM"); return NULL; } env->set_vm(vm, vm_env); for (unsigned int i = 0; i < nOptions; i++) free(vm_options[i].optionString); t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv).tp_alloc(&PY_TYPE(JCCEnv), 0); jccenv->env = env; #ifdef _jcc_lib registerNatives(vm_env); #endif return (PyObject *) jccenv; } } /* returns borrowed reference */ _DLL_EXPORT PyObject *getJavaModule(PyObject *module, const char *parent, const char *name) { PyObject *modules = PyImport_GetModuleDict(); PyObject *parent_module, *full_name; if (parent[0] == '\0') { parent_module = NULL; full_name = PyString_FromString(name); } else if ((parent_module = PyDict_GetItemString(modules, parent)) == NULL) { PyErr_Format(PyExc_ValueError, "Parent module '%s' not found", parent); return NULL; } else full_name = PyString_FromFormat("%s.%s", parent, name); PyObject *child_module = PyDict_GetItem(modules, full_name); if (child_module == NULL) { child_module = PyModule_New(PyString_AS_STRING(full_name)); if (child_module != NULL) { if (parent_module != NULL) PyDict_SetItemString(PyModule_GetDict(parent_module), name, child_module); PyDict_SetItem(modules, full_name, child_module); Py_DECREF(child_module); /* borrow reference */ } } Py_DECREF(full_name); /* During __install__ pass, __file__ is not yet set on module. * During __initialize__ pass, __file__ is passed down to child_module. */ if (child_module != NULL) { PyObject *__file__ = PyString_FromString("__file__"); PyObject *file = PyDict_GetItem(PyModule_GetDict(module), __file__); if (file != NULL) PyDict_SetItem(PyModule_GetDict(child_module), __file__, file); Py_DECREF(__file__); } return child_module; } #ifdef _jcc_lib static void raise_error(JNIEnv *vm_env, const char *message) { jclass cls = vm_env->FindClass("org/apache/jcc/PythonException"); vm_env->ThrowNew(cls, message); } static void _PythonVM_init(JNIEnv *vm_env, jobject self, jstring programName, jobjectArray args) { const char *str = vm_env->GetStringUTFChars(programName, JNI_FALSE); #ifdef linux char buf[32]; // load python runtime for other .so modules to link (such as _time.so) sprintf(buf, "libpython%d.%d.so", PY_MAJOR_VERSION, PY_MINOR_VERSION); dlopen(buf, RTLD_NOW | RTLD_GLOBAL); #endif Py_SetProgramName((char *) str); PyEval_InitThreads(); Py_Initialize(); if (args) { int argc = vm_env->GetArrayLength(args); char **argv = (char **) calloc(argc + 1, sizeof(char *)); argv[0] = (char *) str; for (int i = 0; i < argc; i++) { jstring arg = (jstring) vm_env->GetObjectArrayElement(args, i); argv[i + 1] = (char *) vm_env->GetStringUTFChars(arg, JNI_FALSE); } PySys_SetArgv(argc + 1, argv); for (int i = 0; i < argc; i++) { jstring arg = (jstring) vm_env->GetObjectArrayElement(args, i); vm_env->ReleaseStringUTFChars(arg, argv[i + 1]); } free(argv); } else PySys_SetArgv(1, (char **) &str); vm_env->ReleaseStringUTFChars(programName, str); PyEval_ReleaseLock(); } static jobject _PythonVM_instantiate(JNIEnv *vm_env, jobject self, jstring moduleName, jstring className) { PythonGIL gil(vm_env); const char *modStr = vm_env->GetStringUTFChars(moduleName, JNI_FALSE); PyObject *module = PyImport_ImportModule((char *) modStr); // python 2.4 cast vm_env->ReleaseStringUTFChars(moduleName, modStr); if (!module) { raise_error(vm_env, "import failed"); return NULL; } const char *clsStr = vm_env->GetStringUTFChars(className, JNI_FALSE); PyObject *cls = PyObject_GetAttrString(module, (char *) clsStr); // python 2.4 cast PyObject *obj; jobject jobj; vm_env->ReleaseStringUTFChars(className, clsStr); Py_DECREF(module); if (!cls) { raise_error(vm_env, "class not found"); return NULL; } obj = PyObject_CallFunctionObjArgs(cls, NULL); Py_DECREF(cls); if (!obj) { raise_error(vm_env, "instantiation failed"); return NULL; } PyObject *cObj = PyObject_GetAttrString(obj, "_jobject"); if (!cObj) { raise_error(vm_env, "instance does not proxy a java object"); Py_DECREF(obj); return NULL; } jobj = (jobject) PyCObject_AsVoidPtr(cObj); Py_DECREF(cObj); jobj = vm_env->NewLocalRef(jobj); Py_DECREF(obj); return jobj; } extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *vm_env; if (!vm->GetEnv((void **) &vm_env, JNI_VERSION_1_4)) env = new JCCEnv(vm, vm_env); registerNatives(vm_env); return JNI_VERSION_1_4; } JNIEXPORT void JNICALL Java_org_apache_jcc_PythonVM_init(JNIEnv *vm_env, jobject self, jstring programName, jobjectArray args) { return _PythonVM_init(vm_env, self, programName, args); } JNIEXPORT jobject JNICALL Java_org_apache_jcc_PythonVM_instantiate(JNIEnv *vm_env, jobject self, jstring moduleName, jstring className) { return _PythonVM_instantiate(vm_env, self, moduleName, className); } JNIEXPORT jint JNICALL Java_org_apache_jcc_PythonVM_acquireThreadState(JNIEnv *vm_env) { PyGILState_STATE state = PyGILState_Ensure(); PyThreadState *tstate = PyGILState_GetThisThreadState(); int result = -1; if (tstate != NULL && tstate->gilstate_counter >= 1) result = ++tstate->gilstate_counter; PyGILState_Release(state); return result; } JNIEXPORT jint JNICALL Java_org_apache_jcc_PythonVM_releaseThreadState(JNIEnv *vm_env) { PyGILState_STATE state = PyGILState_Ensure(); PyThreadState *tstate = PyGILState_GetThisThreadState(); int result = -1; if (tstate != NULL && tstate->gilstate_counter >= 1) result = --tstate->gilstate_counter; PyGILState_Release(state); return result; } }; static void JNICALL _PythonException_pythonDecRef(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state != NULL) { PythonGIL gil(vm_env); Py_DECREF(state); vm_env->SetLongField(self, fid, (jlong) 0); } } static void JNICALL _PythonException_saveErrorState(JNIEnv *vm_env, jobject self) { PythonGIL gil(vm_env); PyObject *type, *value, *tb; PyErr_Fetch(&type, &value, &tb); if (type != NULL) { PyObject *state = PyTuple_New(3); PyErr_NormalizeException(&type, &value, &tb); PyTuple_SET_ITEM(state, 0, type); if (value == NULL) { PyTuple_SET_ITEM(state, 1, Py_None); Py_INCREF(Py_None); } else PyTuple_SET_ITEM(state, 1, value); if (tb == NULL) { PyTuple_SET_ITEM(state, 2, Py_None); Py_INCREF(Py_None); } else PyTuple_SET_ITEM(state, 2, tb); jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); vm_env->SetLongField(self, fid, (jlong) state); } } static jstring JNICALL _PythonException_getErrorName(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state == NULL) return NULL; PythonGIL gil(vm_env); PyObject *errorName = PyObject_GetAttrString(PyTuple_GET_ITEM(state, 0), "__name__"); if (errorName != NULL) { jstring str = env->fromPyString(errorName); Py_DECREF(errorName); return str; } return NULL; } static jstring JNICALL _PythonException_getErrorMessage(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state == NULL) return NULL; PythonGIL gil(vm_env); PyObject *value = PyTuple_GET_ITEM(state, 1); if (value != Py_None) { PyObject *message = PyObject_Str(value); if (message != NULL) { jstring str = env->fromPyString(message); Py_DECREF(message); return str; } } return NULL; } static jstring JNICALL _PythonException_getErrorTraceback(JNIEnv *vm_env, jobject self) { jclass jcls = vm_env->GetObjectClass(self); jfieldID fid = vm_env->GetFieldID(jcls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(self, fid); if (state == NULL) return NULL; PythonGIL gil(vm_env); PyObject *module = NULL, *cls = NULL, *stringIO = NULL, *result = NULL; PyObject *_stderr = PySys_GetObject("stderr"); if (!_stderr) return NULL; module = PyImport_ImportModule("cStringIO"); if (!module) return NULL; cls = PyObject_GetAttrString(module, "StringIO"); Py_DECREF(module); if (!cls) return NULL; stringIO = PyObject_CallObject(cls, NULL); Py_DECREF(cls); if (!stringIO) return NULL; Py_INCREF(_stderr); PySys_SetObject("stderr", stringIO); PyObject *type = PyTuple_GET_ITEM(state, 0); PyObject *value = PyTuple_GET_ITEM(state, 1); PyObject *tb = PyTuple_GET_ITEM(state, 2); jstring str = NULL; Py_INCREF(type); if (value == Py_None) value = NULL; else Py_INCREF(value); if (tb == Py_None) tb = NULL; else Py_INCREF(tb); PyErr_Restore(type, value, tb); PyErr_Print(); result = PyObject_CallMethod(stringIO, "getvalue", NULL); Py_DECREF(stringIO); if (result != NULL) { str = env->fromPyString(result); Py_DECREF(result); } PySys_SetObject("stderr", _stderr); Py_DECREF(_stderr); return str; } static void registerNatives(JNIEnv *vm_env) { jclass cls = vm_env->FindClass("org/apache/jcc/PythonException"); JNINativeMethod methods[] = { { "pythonDecRef", "()V", (void *) _PythonException_pythonDecRef }, { "saveErrorState", "()V", (void *) _PythonException_saveErrorState }, { "getErrorName", "()Ljava/lang/String;", (void *) _PythonException_getErrorName }, { "getErrorMessage", "()Ljava/lang/String;", (void *) _PythonException_getErrorMessage }, { "getErrorTraceback", "()Ljava/lang/String;", (void *) _PythonException_getErrorTraceback }, }; vm_env->RegisterNatives(cls, methods, sizeof(methods) / sizeof(methods[0])); } #endif /* _jcc_lib */ JCC-3.6/jcc2/sources/JArray.cpp0000644000076500000000000007617713360725246016416 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef PYTHON #include #include #include "structmember.h" #include "JArray.h" #include "functions.h" #include "java/lang/Class.h" using namespace java::lang; template class _t_JArray : public t_JArray { public: static PyObject *format; }; template static PyObject *get(U *self, Py_ssize_t n) { return self->array.get(n); } template static PyObject *toSequence(U *self) { return self->array.toSequence(); } template static PyObject *toSequence(U *self, Py_ssize_t lo, Py_ssize_t hi) { return self->array.toSequence(lo, hi); } template class _t_iterator { public: PyObject_HEAD U *obj; Py_ssize_t position; static void dealloc(_t_iterator *self) { Py_XDECREF(self->obj); self->ob_type->tp_free((PyObject *) self); } static PyObject *iternext(_t_iterator *self) { if (self->position < (Py_ssize_t) self->obj->array.length) return get(self->obj, self->position++); PyErr_SetNone(PyExc_StopIteration); return NULL; } static PyTypeObject *JArrayIterator; }; template static int init(U *self, PyObject *args, PyObject *kwds) { PyObject *obj; if (!PyArg_ParseTuple(args, "O", &obj)) return -1; if (PySequence_Check(obj)) { self->array = JArray(obj); if (PyErr_Occurred()) return -1; } else if (PyGen_Check(obj)) { PyObject *tuple = PyObject_CallFunctionObjArgs((PyObject *) &PyTuple_Type, obj, NULL); if (!tuple) return -1; self->array = JArray(tuple); Py_DECREF(tuple); if (PyErr_Occurred()) return -1; } else if (PyInt_Check(obj)) { int n = PyInt_AsLong(obj); if (n < 0) { PyErr_SetObject(PyExc_ValueError, obj); return -1; } self->array = JArray(n); } else { PyErr_SetObject(PyExc_TypeError, obj); return -1; } return 0; } template static void dealloc(U *self) { self->array = JArray((jobject) NULL); self->ob_type->tp_free((PyObject *) self); } template static PyObject *_format(U *self, PyObject *(*fn)(PyObject *)) { if (self->array.this$) { PyObject *list = toSequence(self); if (list) { PyObject *result = (*fn)(list); Py_DECREF(list); if (result) { PyObject *args = PyTuple_New(1); PyTuple_SET_ITEM(args, 0, result); result = PyString_Format(U::format, args); Py_DECREF(args); return result; } } return NULL; } return PyString_FromString(""); } template static PyObject *repr(U *self) { return _format(self, (PyObject *(*)(PyObject *)) PyObject_Repr); } template static PyObject *str(U *self) { return _format(self, (PyObject *(*)(PyObject *)) PyObject_Str); } template static int _compare(U *self, PyObject *value, int i0, int i1, int op, int *cmp) { PyObject *v0 = get(self, i0); PyObject *v1 = PySequence_Fast_GET_ITEM(value, i1); /* borrowed */ if (!v0) return -1; if (!v1) { Py_DECREF(v0); return -1; } *cmp = PyObject_RichCompareBool(v0, v1, op); Py_DECREF(v0); if (*cmp < 0) return -1; return 0; } template static PyObject *richcompare(U *self, PyObject *value, int op) { PyObject *result = NULL; int s0, s1; if (!PySequence_Check(value)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } value = PySequence_Fast(value, "not a sequence"); if (!value) return NULL; s0 = PySequence_Fast_GET_SIZE(value); s1 = self->array.length; if (s1 < 0) { Py_DECREF(value); return NULL; } if (s0 != s1) { switch (op) { case Py_EQ: result = Py_False; break; case Py_NE: result = Py_True; break; } } if (!result) { int i0, i1, cmp = 1; for (i0 = 0, i1 = 0; i0 < s0 && i1 < s1 && cmp; i0++, i1++) { if (_compare(self, value, i0, i1, Py_EQ, &cmp) < 0) { Py_DECREF(value); return NULL; } } if (cmp) { switch (op) { case Py_LT: cmp = s0 < s1; break; case Py_LE: cmp = s0 <= s1; break; case Py_EQ: cmp = s0 == s1; break; case Py_NE: cmp = s0 != s1; break; case Py_GT: cmp = s0 > s1; break; case Py_GE: cmp = s0 >= s1; break; default: cmp = 0; } result = cmp ? Py_True : Py_False; } else if (op == Py_EQ) result = Py_False; else if (op == Py_NE) result = Py_True; else if (_compare(self, value, i0, i1, op, &cmp) < 0) { Py_DECREF(value); return NULL; } else result = cmp ? Py_True : Py_False; } Py_DECREF(value); Py_INCREF(result); return result; } template static PyObject *iter(U *self) { _t_iterator *it = PyObject_New(_t_iterator, _t_iterator::JArrayIterator); if (it) { it->position = 0; it->obj = self; Py_INCREF((PyObject *) self); } return (PyObject *) it; } template static Py_ssize_t seq_length(U *self) { if (self->array.this$) return self->array.length; return 0; } template static PyObject *seq_get(U *self, Py_ssize_t n) { return get(self, n); } template static int seq_contains(U *self, PyObject *value) { return 0; } template static PyObject *seq_concat(U *self, PyObject *arg) { PyObject *list = toSequence(self); if (list != NULL && PyList_Type.tp_as_sequence->sq_inplace_concat(list, arg) == NULL) { Py_DECREF(list); return NULL; } return list; } template static PyObject *seq_repeat(U *self, Py_ssize_t n) { PyObject *list = toSequence(self); if (list != NULL && PyList_Type.tp_as_sequence->sq_inplace_repeat(list, n) == NULL) { Py_DECREF(list); return NULL; } return list; } template static PyObject *seq_getslice(U *self, Py_ssize_t lo, Py_ssize_t hi) { return toSequence(self, lo, hi); } template static int seq_set(U *self, Py_ssize_t n, PyObject *value) { return self->array.set(n, value); } template static int seq_setslice(U *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *values) { Py_ssize_t length = self->array.length; if (values == NULL) { PyErr_SetString(PyExc_ValueError, "array size cannot change"); return -1; } if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *sequence = PySequence_Fast(values, "not a sequence"); if (!sequence) return -1; Py_ssize_t size = PySequence_Fast_GET_SIZE(sequence); if (size < 0) goto error; if (size != hi - lo) { PyErr_SetString(PyExc_ValueError, "array size cannot change"); goto error; } for (Py_ssize_t i = lo; i < hi; i++) { PyObject *value = PySequence_Fast_GET_ITEM(sequence, i - lo); if (value == NULL) goto error; if (self->array.set(i, value) < 0) goto error; } Py_DECREF(sequence); return 0; error: Py_DECREF(sequence); return -1; } template static jclass initializeClass(bool getOnly) { return env->get_vm_env()->GetObjectClass(JArray((Py_ssize_t) 0).this$); } template static PyObject *cast_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsObj; if (!PyArg_ParseTuple(args, "O", &arg)) return NULL; if (!PyObject_TypeCheck(arg, &PY_TYPE(Object))) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } clsObj = PyObject_GetAttrString((PyObject *) type, "class_"); if (!clsObj) return NULL; Class arrayCls = ((t_Class *) clsObj)->object; if (!arrayCls.isAssignableFrom(argCls)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } return JArray(((t_JObject *) arg)->object.this$).wrap(); } template static PyObject *wrapfn_(const jobject &object) { return JArray(object).wrap(); } template static PyObject *instance_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsObj; if (!PyArg_ParseTuple(args, "O", &arg)) return NULL; if (!PyObject_TypeCheck(arg, &PY_TYPE(Object))) Py_RETURN_FALSE; Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) Py_RETURN_FALSE; clsObj = PyObject_GetAttrString((PyObject *) type, "class_"); if (!clsObj) return NULL; Class arrayCls = ((t_Class *) clsObj)->object; if (!arrayCls.isAssignableFrom(argCls)) Py_RETURN_FALSE; Py_RETURN_TRUE; } template static PyObject *assignable_(PyTypeObject *type, PyObject *args, PyObject *kwds) { return instance_(type, args, kwds); } template< typename T, typename U = _t_JArray > class jarray_type { public: PySequenceMethods seq_methods; PyTypeObject type_object; class iterator_type { public: PyTypeObject type_object; void install(char *name, PyObject *module) { type_object.tp_name = name; if (PyType_Ready(&type_object) == 0) { Py_INCREF((PyObject *) &type_object); PyModule_AddObject(module, name, (PyObject *) &type_object); } _t_iterator::JArrayIterator = &type_object; } iterator_type() { memset(&type_object, 0, sizeof(type_object)); type_object.ob_refcnt = 1; type_object.ob_type = NULL; type_object.tp_basicsize = sizeof(_t_iterator); type_object.tp_dealloc = (destructor) _t_iterator::dealloc; type_object.tp_flags = Py_TPFLAGS_DEFAULT; type_object.tp_doc = "JArrayIterator wrapper type"; type_object.tp_iter = (getiterfunc) PyObject_SelfIter; type_object.tp_iternext = (iternextfunc) _t_iterator::iternext; } }; iterator_type iterator_type_object; void install(char *name, char *type_name, char *iterator_name, PyObject *module) { type_object.tp_name = name; if (PyType_Ready(&type_object) == 0) { Py_INCREF((PyObject *) &type_object); PyDict_SetItemString(type_object.tp_dict, "class_", make_descriptor(initializeClass)); PyDict_SetItemString(type_object.tp_dict, "wrapfn_", make_descriptor(wrapfn_)); PyModule_AddObject(module, name, (PyObject *) &type_object); } U::format = PyString_FromFormat("JArray<%s>%%s", type_name); iterator_type_object.install(iterator_name, module); } static PyObject *_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { U *self = (U *) type->tp_alloc(type, 0); if (self) self->array = JArray((jobject) NULL); return (PyObject *) self; } jarray_type() { memset(&seq_methods, 0, sizeof(seq_methods)); memset(&type_object, 0, sizeof(type_object)); static PyMethodDef methods[] = { { "cast_", (PyCFunction) (PyObject *(*)(PyTypeObject *, PyObject *, PyObject *)) cast_, METH_VARARGS | METH_CLASS, NULL }, { "instance_", (PyCFunction) (PyObject *(*)(PyTypeObject *, PyObject *, PyObject *)) instance_, METH_VARARGS | METH_CLASS, NULL }, { "assignable_", (PyCFunction) (PyObject *(*)(PyTypeObject *, PyObject *, PyObject *)) assignable_, METH_VARARGS | METH_CLASS, NULL }, { NULL, NULL, 0, NULL } }; seq_methods.sq_length = (lenfunc) (Py_ssize_t (*)(U *)) seq_length; seq_methods.sq_concat = (binaryfunc) (PyObject *(*)(U *, PyObject *)) seq_concat; seq_methods.sq_repeat = (ssizeargfunc) (PyObject *(*)(U *, Py_ssize_t)) seq_repeat; seq_methods.sq_item = (ssizeargfunc) (PyObject *(*)(U *, Py_ssize_t)) seq_get; seq_methods.sq_slice = (ssizessizeargfunc) (PyObject *(*)(U *, Py_ssize_t, Py_ssize_t)) seq_getslice; seq_methods.sq_ass_item = (ssizeobjargproc) (int (*)(U *, Py_ssize_t, PyObject *)) seq_set; seq_methods.sq_ass_slice = (ssizessizeobjargproc) (int (*)(U *, Py_ssize_t, Py_ssize_t, PyObject *)) seq_setslice; seq_methods.sq_contains = (objobjproc) (int (*)(U *, PyObject *)) seq_contains; seq_methods.sq_inplace_concat = NULL; seq_methods.sq_inplace_repeat = NULL; type_object.ob_refcnt = 1; type_object.tp_basicsize = sizeof(U); type_object.tp_dealloc = (destructor) (void (*)(U *)) dealloc; type_object.tp_repr = (reprfunc) (PyObject *(*)(U *)) repr; type_object.tp_as_sequence = &seq_methods; type_object.tp_str = (reprfunc) (PyObject *(*)(U *)) str; type_object.tp_flags = Py_TPFLAGS_DEFAULT; type_object.tp_doc = "JArray wrapper type"; type_object.tp_richcompare = (richcmpfunc) (PyObject *(*)(U *, PyObject *, int)) richcompare; type_object.tp_iter = (getiterfunc) (PyObject *(*)(U *)) iter; type_object.tp_methods = methods; type_object.tp_base = &PY_TYPE(Object); type_object.tp_init = (initproc) (int (*)(U *, PyObject *, PyObject *)) init; type_object.tp_new = (newfunc) _new; } }; template class _t_jobjectarray : public _t_JArray { public: PyObject *(*wrapfn)(const T&); }; template<> PyObject *get(_t_jobjectarray *self, Py_ssize_t n) { return self->array.get(n, self->wrapfn); } template<> PyObject *toSequence(_t_jobjectarray *self) { return self->array.toSequence(self->wrapfn); } template<> PyObject *toSequence(_t_jobjectarray *self, Py_ssize_t lo, Py_ssize_t hi) { return self->array.toSequence(lo, hi, self->wrapfn); } template<> int init< jobject,_t_jobjectarray >(_t_jobjectarray *self, PyObject *args, PyObject *kwds) { PyObject *obj, *clsObj = NULL; PyObject *(*wrapfn)(const jobject &) = NULL; jclass cls; if (!PyArg_ParseTuple(args, "O|O", &obj, &clsObj)) return -1; if (clsObj == NULL) cls = env->findClass("java/lang/Object"); else if (PyObject_TypeCheck(clsObj, &PY_TYPE(Class))) cls = (jclass) ((t_Class *) clsObj)->object.this$; else if (PyType_Check(clsObj)) { if (PyType_IsSubtype((PyTypeObject *) clsObj, &PY_TYPE(JObject))) { PyObject *cobj = PyObject_GetAttrString(clsObj, "wrapfn_"); if (cobj == NULL) PyErr_Clear(); else { wrapfn = (PyObject *(*)(const jobject &)) PyCObject_AsVoidPtr(cobj); Py_DECREF(cobj); } clsObj = PyObject_GetAttrString(clsObj, "class_"); if (clsObj == NULL) return -1; cls = (jclass) ((t_Class *) clsObj)->object.this$; Py_DECREF(clsObj); } else { PyErr_SetObject(PyExc_ValueError, clsObj); return -1; } } else { PyErr_SetObject(PyExc_TypeError, clsObj); return -1; } if (PySequence_Check(obj)) { self->array = JArray(cls, obj); if (PyErr_Occurred()) return -1; } else if (PyGen_Check(obj)) { PyObject *tuple = PyObject_CallFunctionObjArgs((PyObject *) &PyTuple_Type, obj, NULL); if (!tuple) return -1; self->array = JArray(cls, tuple); Py_DECREF(tuple); if (PyErr_Occurred()) return -1; } else if (PyInt_Check(obj)) { int n = PyInt_AsLong(obj); if (n < 0) { PyErr_SetObject(PyExc_ValueError, obj); return -1; } self->array = JArray(cls, n); } else { PyErr_SetObject(PyExc_TypeError, obj); return -1; } self->wrapfn = wrapfn; return 0; } template<> jclass initializeClass(bool getOnly) { jclass cls = env->findClass("java/lang/Object"); return env->get_vm_env()->GetObjectClass(JArray(cls, (Py_ssize_t) 0).this$); } template<> PyObject *cast_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsArg = NULL; PyObject *(*wrapfn)(const jobject&) = NULL; jclass elementCls; if (!PyArg_ParseTuple(args, "O|O", &arg, &clsArg)) return NULL; if (!PyObject_TypeCheck(arg, &PY_TYPE(Object))) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } if (clsArg != NULL) { if (!PyType_Check(clsArg)) { PyErr_SetObject(PyExc_TypeError, clsArg); return NULL; } else if (!PyType_IsSubtype((PyTypeObject *) clsArg, &PY_TYPE(JObject))) { PyErr_SetObject(PyExc_ValueError, clsArg); return NULL; } PyObject *cobj = PyObject_GetAttrString(clsArg, "wrapfn_"); if (cobj == NULL) PyErr_Clear(); else { wrapfn = (PyObject *(*)(const jobject &)) PyCObject_AsVoidPtr(cobj); Py_DECREF(cobj); } clsArg = PyObject_GetAttrString(clsArg, "class_"); if (clsArg == NULL) return NULL; elementCls = (jclass) ((t_Class *) clsArg)->object.this$; Py_DECREF(clsArg); } else elementCls = env->findClass("java/lang/Object"); JNIEnv *vm_env = env->get_vm_env(); jobjectArray array = vm_env->NewObjectArray(0, elementCls, NULL); Class arrayCls(vm_env->GetObjectClass((jobject) array)); if (!arrayCls.isAssignableFrom(argCls)) { PyErr_SetObject(PyExc_TypeError, arg); return NULL; } return JArray(((t_JObject *) arg)->object.this$).wrap(wrapfn); } template<> PyObject *wrapfn_(const jobject &object) { PyObject *cobj = PyObject_GetAttrString( (PyObject *) &PY_TYPE(Object), "wrapfn_"); PyObject *(*wrapfn)(const jobject&) = NULL; if (cobj == NULL) PyErr_Clear(); else { wrapfn = (PyObject *(*)(const jobject &)) PyCObject_AsVoidPtr(cobj); Py_DECREF(cobj); } return JArray(object).wrap(wrapfn); } template<> PyObject *instance_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsArg = NULL; jclass elementCls; if (!PyArg_ParseTuple(args, "O|O", &arg, &clsArg)) return NULL; if (!PyObject_TypeCheck(arg, &PY_TYPE(Object))) Py_RETURN_FALSE; Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) Py_RETURN_FALSE; if (clsArg != NULL) { if (!PyType_Check(clsArg)) { PyErr_SetObject(PyExc_TypeError, clsArg); return NULL; } else if (!PyType_IsSubtype((PyTypeObject *) clsArg, &PY_TYPE(JObject))) { PyErr_SetObject(PyExc_ValueError, clsArg); return NULL; } clsArg = PyObject_GetAttrString(clsArg, "class_"); if (clsArg == NULL) return NULL; elementCls = (jclass) ((t_Class *) clsArg)->object.this$; Py_DECREF(clsArg); } else elementCls = env->findClass("java/lang/Object"); JNIEnv *vm_env = env->get_vm_env(); jobjectArray array = vm_env->NewObjectArray(0, elementCls, NULL); Class arrayCls(vm_env->GetObjectClass((jobject) array)); if (!arrayCls.isAssignableFrom(argCls)) Py_RETURN_FALSE; Py_RETURN_TRUE; } template<> PyObject *assignable_(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg, *clsArg = NULL; jclass elementCls; if (!PyArg_ParseTuple(args, "O|O", &arg, &clsArg)) return NULL; if (!PyObject_TypeCheck(arg, &PY_TYPE(Object))) Py_RETURN_FALSE; Class argCls = ((t_Object *) arg)->object.getClass(); if (!argCls.isArray()) Py_RETURN_FALSE; if (clsArg != NULL) { if (!PyType_Check(clsArg)) { PyErr_SetObject(PyExc_TypeError, clsArg); return NULL; } else if (!PyType_IsSubtype((PyTypeObject *) clsArg, &PY_TYPE(JObject))) { PyErr_SetObject(PyExc_ValueError, clsArg); return NULL; } clsArg = PyObject_GetAttrString(clsArg, "class_"); if (clsArg == NULL) return NULL; elementCls = (jclass) ((t_Class *) clsArg)->object.this$; Py_DECREF(clsArg); } else elementCls = env->findClass("java/lang/Object"); JNIEnv *vm_env = env->get_vm_env(); jobjectArray array = vm_env->NewObjectArray(0, elementCls, NULL); Class arrayCls(vm_env->GetObjectClass((jobject) array)); if (!argCls.isAssignableFrom(arrayCls)) Py_RETURN_FALSE; Py_RETURN_TRUE; } template PyTypeObject *_t_iterator::JArrayIterator; template PyObject *_t_JArray::format; static jarray_type< jobject, _t_jobjectarray > jarray_jobject; static jarray_type jarray_jstring; static jarray_type jarray_jboolean; static jarray_type jarray_jbyte; static jarray_type jarray_jchar; static jarray_type jarray_jdouble; static jarray_type jarray_jfloat; static jarray_type jarray_jint; static jarray_type jarray_jlong; static jarray_type jarray_jshort; PyObject *JArray::wrap(PyObject *(*wrapfn)(const jobject&)) const { if (this$ != NULL) { _t_jobjectarray *obj = PyObject_New(_t_jobjectarray, &jarray_jobject.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; obj->wrapfn = wrapfn; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jstring.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jboolean.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jbyte.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jchar.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jdouble.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jfloat.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jint.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jlong.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray::wrap() const { if (this$ != NULL) { _t_JArray *obj = PyObject_New(_t_JArray, &jarray_jshort.type_object); memset((void *) &(obj->array), 0, sizeof(JArray)); obj->array = *this; return (PyObject *) obj; } Py_RETURN_NONE; } PyObject *JArray_Type(PyObject *self, PyObject *arg) { PyObject *type_name = NULL, *type; char const *name = NULL; if (PyType_Check(arg)) { type_name = PyObject_GetAttrString(arg, "__name__"); if (!type_name) return NULL; } else if (PyString_Check(arg)) { type_name = arg; Py_INCREF(type_name); } else if (PyFloat_Check(arg)) { type_name = NULL; name = "double"; } else { PyObject *arg_type = (PyObject *) arg->ob_type; type_name = PyObject_GetAttrString(arg_type, "__name__"); if (!type_name) return NULL; } if (type_name != NULL) { name = PyString_AsString(type_name); if (!name) { Py_DECREF(type_name); return NULL; } } if (!strcmp(name, "object")) type = (PyObject *) &jarray_jobject.type_object; else if (!strcmp(name, "string")) type = (PyObject *) &jarray_jstring.type_object; else if (!strcmp(name, "bool")) type = (PyObject *) &jarray_jboolean.type_object; else if (!strcmp(name, "byte")) type = (PyObject *) &jarray_jbyte.type_object; else if (!strcmp(name, "char")) type = (PyObject *) &jarray_jchar.type_object; else if (!strcmp(name, "double")) type = (PyObject *) &jarray_jdouble.type_object; else if (!strcmp(name, "float")) type = (PyObject *) &jarray_jfloat.type_object; else if (!strcmp(name, "int")) type = (PyObject *) &jarray_jint.type_object; else if (!strcmp(name, "long")) type = (PyObject *) &jarray_jlong.type_object; else if (!strcmp(name, "short")) type = (PyObject *) &jarray_jshort.type_object; else { PyErr_SetObject(PyExc_ValueError, arg); Py_XDECREF(type_name); return NULL; } Py_INCREF(type); Py_XDECREF(type_name); return type; } static PyObject *t_JArray_jbyte__get_string_(t_JArray *self, void *data) { return self->array.to_string_(); } static PyGetSetDef t_JArray_jbyte__fields[] = { { "string_", (getter) t_JArray_jbyte__get_string_, NULL, "", NULL }, { NULL, NULL, NULL, NULL, NULL } }; PyTypeObject *PY_TYPE(JArrayObject); PyTypeObject *PY_TYPE(JArrayString); PyTypeObject *PY_TYPE(JArrayBool); PyTypeObject *PY_TYPE(JArrayByte); PyTypeObject *PY_TYPE(JArrayChar); PyTypeObject *PY_TYPE(JArrayDouble); PyTypeObject *PY_TYPE(JArrayFloat); PyTypeObject *PY_TYPE(JArrayInt); PyTypeObject *PY_TYPE(JArrayLong); PyTypeObject *PY_TYPE(JArrayShort); void _install_jarray(PyObject *module) { jarray_jobject.install("JArray_object", "object", "__JArray_object_iterator", module); PY_TYPE(JArrayObject) = &jarray_jobject.type_object; jarray_jstring.install("JArray_string", "string", "__JArray_string_iterator", module); PY_TYPE(JArrayString) = &jarray_jstring.type_object; jarray_jboolean.install("JArray_bool", "bool", "__JArray_bool_iterator", module); PY_TYPE(JArrayBool) = &jarray_jboolean.type_object; jarray_jbyte.type_object.tp_getset = t_JArray_jbyte__fields; jarray_jbyte.install("JArray_byte", "byte", "__JArray_byte_iterator", module); PY_TYPE(JArrayByte) = &jarray_jbyte.type_object; jarray_jchar.install("JArray_char", "char", "__JArray_char_iterator", module); PY_TYPE(JArrayChar) = &jarray_jchar.type_object; jarray_jdouble.install("JArray_double", "double", "__JArray_double_iterator", module); PY_TYPE(JArrayDouble) = &jarray_jdouble.type_object; jarray_jfloat.install("JArray_float", "float", "__JArray_float_iterator", module); PY_TYPE(JArrayFloat) = &jarray_jfloat.type_object; jarray_jint.install("JArray_int", "int", "__JArray_int_iterator", module); PY_TYPE(JArrayInt) = &jarray_jint.type_object; jarray_jlong.install("JArray_long", "long", "__JArray_long_iterator", module); PY_TYPE(JArrayLong) = &jarray_jlong.type_object; jarray_jshort.install("JArray_short", "short", "__JArray_short_iterator", module); PY_TYPE(JArrayShort) = &jarray_jshort.type_object; } #endif /* PYTHON */ JCC-3.6/jcc2/sources/types.cpp0000644000076500000000000004374613063017435016360 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "structmember.h" #include "java/lang/Object.h" #include "java/lang/Class.h" #include "functions.h" using namespace java::lang; /* FinalizerProxy */ static PyObject *t_fc_call(PyObject *self, PyObject *args, PyObject *kwds); static void t_fp_dealloc(t_fp *self); static PyObject *t_fp_getattro(t_fp *self, PyObject *name); static int t_fp_setattro(t_fp *self, PyObject *name, PyObject *value); static int t_fp_traverse(t_fp *self, visitproc visit, void *arg); static int t_fp_clear(t_fp *self); static PyObject *t_fp_repr(t_fp *self); static PyObject *t_fp_iter(t_fp *self); static Py_ssize_t t_fp_map_length(t_fp *self); static PyObject *t_fp_map_get(t_fp *self, PyObject *key); static int t_fp_map_set(t_fp *self, PyObject *key, PyObject *value); static Py_ssize_t t_fp_seq_length(t_fp *self); static PyObject *t_fp_seq_get(t_fp *self, Py_ssize_t n); static int t_fp_seq_contains(t_fp *self, PyObject *value); static PyObject *t_fp_seq_concat(t_fp *self, PyObject *arg); static PyObject *t_fp_seq_repeat(t_fp *self, Py_ssize_t n); static PyObject *t_fp_seq_getslice(t_fp *self, Py_ssize_t low, Py_ssize_t high); static int t_fp_seq_set(t_fp *self, Py_ssize_t i, PyObject *value); static int t_fp_seq_setslice(t_fp *self, Py_ssize_t low, Py_ssize_t high, PyObject *arg); static PyObject *t_fp_seq_inplace_concat(t_fp *self, PyObject *arg); static PyObject *t_fp_seq_inplace_repeat(t_fp *self, Py_ssize_t n); PyTypeObject PY_TYPE(FinalizerClass) = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "jcc.FinalizerClass", /* tp_name */ PyType_Type.tp_basicsize, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc) t_fc_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "FinalizerClass", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyType_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static PyMappingMethods t_fp_as_mapping = { (lenfunc)t_fp_map_length, /* mp_length */ (binaryfunc)t_fp_map_get, /* mp_subscript */ (objobjargproc)t_fp_map_set, /* mp_ass_subscript */ }; static PySequenceMethods t_fp_as_sequence = { (lenfunc)t_fp_seq_length, /* sq_length */ (binaryfunc)t_fp_seq_concat, /* sq_concat */ (ssizeargfunc)t_fp_seq_repeat, /* sq_repeat */ (ssizeargfunc)t_fp_seq_get, /* sq_item */ (ssizessizeargfunc)t_fp_seq_getslice, /* sq_slice */ (ssizeobjargproc)t_fp_seq_set, /* sq_ass_item */ (ssizessizeobjargproc)t_fp_seq_setslice, /* sq_ass_slice */ (objobjproc)t_fp_seq_contains, /* sq_contains */ (binaryfunc)t_fp_seq_inplace_concat, /* sq_inplace_concat */ (ssizeargfunc)t_fp_seq_inplace_repeat, /* sq_inplace_repeat */ }; PyTypeObject PY_TYPE(FinalizerProxy) = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "jcc.FinalizerProxy", /* tp_name */ sizeof(t_fp), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_fp_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)t_fp_repr, /* tp_repr */ 0, /* tp_as_number */ &t_fp_as_sequence, /* tp_as_sequence */ &t_fp_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)t_fp_getattro, /* tp_getattro */ (setattrofunc)t_fp_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC), /* tp_flags */ "FinalizerProxy", /* tp_doc */ (traverseproc)t_fp_traverse, /* tp_traverse */ (inquiry)t_fp_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)t_fp_iter, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static PyObject *t_fc_call(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *obj = PyType_Type.tp_call(self, args, kwds); if (obj) { t_fp *fp = (t_fp *) PY_TYPE(FinalizerProxy).tp_alloc(&PY_TYPE(FinalizerProxy), 0); fp->object = obj; /* released by t_fp_clear() */ obj = (PyObject *) fp; } return obj; } static void t_fp_dealloc(t_fp *self) { if (self->object) ((t_JObject *) self->object)->object.weaken$(); t_fp_clear(self); self->ob_type->tp_free((PyObject *) self); } static int t_fp_traverse(t_fp *self, visitproc visit, void *arg) { Py_VISIT(self->object); return 0; } static int t_fp_clear(t_fp *self) { Py_CLEAR(self->object); return 0; } static PyObject *t_fp_repr(t_fp *self) { return PyObject_Repr(self->object); } static PyObject *t_fp_iter(t_fp *self) { return PyObject_GetIter(self->object); } static PyObject *t_fp_getattro(t_fp *self, PyObject *name) { return PyObject_GetAttr(self->object, name); } static int t_fp_setattro(t_fp *self, PyObject *name, PyObject *value) { return PyObject_SetAttr(self->object, name, value); } static Py_ssize_t t_fp_map_length(t_fp *self) { return PyMapping_Size(self->object); } static PyObject *t_fp_map_get(t_fp *self, PyObject *key) { return PyObject_GetItem(self->object, key); } static int t_fp_map_set(t_fp *self, PyObject *key, PyObject *value) { if (value == NULL) return PyObject_DelItem(self->object, key); return PyObject_SetItem(self->object, key, value); } static Py_ssize_t t_fp_seq_length(t_fp *self) { return PySequence_Length(self->object); } static PyObject *t_fp_seq_get(t_fp *self, Py_ssize_t n) { return PySequence_GetItem(self->object, n); } static int t_fp_seq_contains(t_fp *self, PyObject *value) { return PySequence_Contains(self->object, value); } static PyObject *t_fp_seq_concat(t_fp *self, PyObject *arg) { return PySequence_Concat(self->object, arg); } static PyObject *t_fp_seq_repeat(t_fp *self, Py_ssize_t n) { return PySequence_Repeat(self->object, n); } static PyObject *t_fp_seq_getslice(t_fp *self, Py_ssize_t low, Py_ssize_t high) { return PySequence_GetSlice(self->object, low, high); } static int t_fp_seq_set(t_fp *self, Py_ssize_t i, PyObject *value) { return PySequence_SetItem(self->object, i, value); } static int t_fp_seq_setslice(t_fp *self, Py_ssize_t low, Py_ssize_t high, PyObject *arg) { return PySequence_SetSlice(self->object, low, high, arg); } static PyObject *t_fp_seq_inplace_concat(t_fp *self, PyObject *arg) { return PySequence_InPlaceConcat(self->object, arg); } static PyObject *t_fp_seq_inplace_repeat(t_fp *self, Py_ssize_t n) { return PySequence_InPlaceRepeat(self->object, n); } /* const variable descriptor */ class t_descriptor { public: PyObject_HEAD int flags; union { PyObject *value; getclassfn initializeClass; } access; }; #define DESCRIPTOR_VALUE 0x0001 #define DESCRIPTOR_CLASS 0x0002 #define DESCRIPTOR_GETFN 0x0004 #define DESCRIPTOR_GENERIC 0x0008 static void t_descriptor_dealloc(t_descriptor *self); static PyObject *t_descriptor___get__(t_descriptor *self, PyObject *obj, PyObject *type); static PyMethodDef t_descriptor_methods[] = { { NULL, NULL, 0, NULL } }; PyTypeObject PY_TYPE(ConstVariableDescriptor) = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "jcc.ConstVariableDescriptor", /* tp_name */ sizeof(t_descriptor), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_descriptor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "const variable descriptor", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ t_descriptor_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)t_descriptor___get__, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static void t_descriptor_dealloc(t_descriptor *self) { if (self->flags & DESCRIPTOR_VALUE) { Py_DECREF(self->access.value); } self->ob_type->tp_free((PyObject *) self); } PyObject *make_descriptor(PyTypeObject *value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { Py_INCREF(value); self->access.value = (PyObject *) value; self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(getclassfn initializeClass) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.initializeClass = initializeClass; self->flags = DESCRIPTOR_CLASS; } return (PyObject *) self; } PyObject *make_descriptor(getclassfn initializeClass, int generics) { t_descriptor *self = (t_descriptor *) make_descriptor(initializeClass); if (self && generics) self->flags |= DESCRIPTOR_GENERIC; return (PyObject *) self; } PyObject *make_descriptor(PyObject *value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = value; self->flags = DESCRIPTOR_VALUE; } else Py_DECREF(value); return (PyObject *) self; } PyObject *make_descriptor(PyObject *(*wrapfn)(const jobject &)) { return make_descriptor(PyCObject_FromVoidPtr((void *) wrapfn, NULL)); } PyObject *make_descriptor(boxfn fn) { return make_descriptor(PyCObject_FromVoidPtr((void *) fn, NULL)); } PyObject *make_descriptor(jboolean b) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { PyObject *value = b ? Py_True : Py_False; self->access.value = (PyObject *) value; Py_INCREF(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jbyte value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyInt_FromLong(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jchar value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { Py_UNICODE pchar = (Py_UNICODE) value; self->access.value = PyUnicode_FromUnicode(&pchar, 1); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jdouble value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyFloat_FromDouble(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jfloat value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyFloat_FromDouble((double) value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jint value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyInt_FromLong(value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jlong value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyLong_FromLongLong((long long) value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } PyObject *make_descriptor(jshort value) { t_descriptor *self = (t_descriptor *) PY_TYPE(ConstVariableDescriptor).tp_alloc(&PY_TYPE(ConstVariableDescriptor), 0); if (self) { self->access.value = PyInt_FromLong((short) value); self->flags = DESCRIPTOR_VALUE; } return (PyObject *) self; } static PyObject *t_descriptor___get__(t_descriptor *self, PyObject *obj, PyObject *type) { if (self->flags & DESCRIPTOR_VALUE) { Py_INCREF(self->access.value); return self->access.value; } if (self->flags & DESCRIPTOR_CLASS) { #ifdef _java_generics if (self->flags & DESCRIPTOR_GENERIC) return t_Class::wrap_Object(Class(env->getClass(self->access.initializeClass)), (PyTypeObject *) type); else #endif return t_Class::wrap_Object(Class(env->getClass(self->access.initializeClass))); } Py_RETURN_NONE; } JCC-3.6/jcc2/sources/JObject.h0000644000076500000000000000422713063017435016170 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JObject_H #define _JObject_H #include #include "JCCEnv.h" class _DLL_EXPORT JObject { public: jobject this$; inline explicit JObject(jobject obj) { if (obj) { id = env->id(obj); this$ = env->newGlobalRef(obj, id); } else { id = 0; this$ = NULL; } } inline JObject(const JObject& obj) { id = obj.id ? obj.id : env->id(obj.this$); this$ = env->newGlobalRef(obj.this$, id); } virtual ~JObject() { this$ = env->deleteGlobalRef(this$, id); } JObject& weaken$() { if (id) { jobject ref = env->newGlobalRef(this$, 0); env->deleteGlobalRef(this$, id); id = 0; this$ = ref; } return *this; } inline int operator!() const { return env->isSame(this$, NULL); } inline int operator==(const JObject& obj) const { return env->isSame(this$, obj.this$); } JObject& operator=(const JObject& obj) { jobject prev = this$; int objid = obj.id ? obj.id : env->id(obj.this$); this$ = env->newGlobalRef(obj.this$, objid); env->deleteGlobalRef(prev, id); id = objid; return *this; } private: int id; // zero when this$ is a weak ref */ }; #ifdef PYTHON #include #include "macros.h" class t_JObject { public: PyObject_HEAD JObject object; }; extern PyTypeObject PY_TYPE(JObject); #endif /* PYTHON */ #endif /* _JObject_H */ JCC-3.6/jcc2/sources/jccfuncs.h0000644000076500000000000000353413063017435016446 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _jccfuncs_H #define _jccfuncs_H #ifdef PYTHON PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds); PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds); PyObject *getVMEnv(PyObject *self); PyObject *_set_exception_types(PyObject *self, PyObject *args); PyObject *_set_function_self(PyObject *self, PyObject *args); PyObject *findClass(PyObject *self, PyObject *args); PyObject *makeInterface(PyObject *self, PyObject *args); PyObject *makeClass(PyObject *self, PyObject *args); PyObject *JArray_Type(PyObject *self, PyObject *arg); PyMethodDef jcc_funcs[] = { { "initVM", (PyCFunction) __initialize__, METH_VARARGS | METH_KEYWORDS, NULL }, { "getVMEnv", (PyCFunction) getVMEnv, METH_NOARGS, NULL }, { "findClass", (PyCFunction) findClass, METH_VARARGS, NULL }, { "makeInterface", (PyCFunction) makeInterface, METH_VARARGS, NULL }, { "makeClass", (PyCFunction) makeClass, METH_VARARGS, NULL }, { "_set_exception_types", (PyCFunction) _set_exception_types, METH_VARARGS, NULL }, { "_set_function_self", (PyCFunction) _set_function_self, METH_VARARGS, NULL }, { "JArray", (PyCFunction) JArray_Type, METH_O, NULL }, { NULL, NULL, 0, NULL } }; #endif #endif /* _jccfuncs_H */ JCC-3.6/jcc2/sources/JCCEnv.cpp0000644000076500000000000007613413063017435016261 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include "JCCEnv.h" #if defined(_MSC_VER) || defined(__WIN32) _DLL_EXPORT DWORD VM_ENV = 0; #else pthread_key_t JCCEnv::VM_ENV = (pthread_key_t) NULL; #endif #if defined(_MSC_VER) || defined(__WIN32) static CRITICAL_SECTION *mutex = NULL; class lock { public: lock() { EnterCriticalSection(mutex); } virtual ~lock() { LeaveCriticalSection(mutex); } }; #else static pthread_mutex_t *mutex = NULL; class lock { public: lock() { pthread_mutex_lock(mutex); } virtual ~lock() { pthread_mutex_unlock(mutex); } }; #endif JCCEnv::JCCEnv(JavaVM *vm, JNIEnv *vm_env) { #if defined(_MSC_VER) || defined(__WIN32) if (!mutex) { mutex = new CRITICAL_SECTION(); InitializeCriticalSection(mutex); // recursive by default } #else if (!mutex) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); mutex = new pthread_mutex_t(); pthread_mutex_init(mutex, &attr); } #endif if (vm) set_vm(vm, vm_env); else this->vm = NULL; } void JCCEnv::set_vm(JavaVM *vm, JNIEnv *vm_env) { this->vm = vm; set_vm_env(vm_env); _sys = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/System")); _obj = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Object")); #ifdef _jcc_lib _thr = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("org/apache/jcc/PythonException")); #else _thr = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/RuntimeException")); #endif _boo = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Boolean")); _byt = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Byte")); _cha = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Character")); _dou = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Double")); _flo = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Float")); _int = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Integer")); _lon = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Long")); _sho = (jclass) vm_env->NewGlobalRef(vm_env->FindClass("java/lang/Short")); _mids = new jmethodID[max_mid]; _mids[mid_sys_identityHashCode] = vm_env->GetStaticMethodID(_sys, "identityHashCode", "(Ljava/lang/Object;)I"); _mids[mid_sys_setProperty] = vm_env->GetStaticMethodID(_sys, "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); _mids[mid_sys_getProperty] = vm_env->GetStaticMethodID(_sys, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"); _mids[mid_obj_toString] = vm_env->GetMethodID(_obj, "toString", "()Ljava/lang/String;"); _mids[mid_obj_hashCode] = vm_env->GetMethodID(_obj, "hashCode", "()I"); _mids[mid_obj_getClass] = vm_env->GetMethodID(_obj, "getClass", "()Ljava/lang/Class;"); jclass iterable = vm_env->FindClass("java/lang/Iterable"); if (iterable == NULL) /* JDK < 1.5 */ { vm_env->ExceptionClear(); _mids[mid_iterator] = NULL; _mids[mid_iterator_next] = NULL; } else { _mids[mid_iterator] = vm_env->GetMethodID(iterable, "iterator", "()Ljava/util/Iterator;"); _mids[mid_iterator_next] = vm_env->GetMethodID(vm_env->FindClass("java/util/Iterator"), "next", "()Ljava/lang/Object;"); } _mids[mid_enumeration_nextElement] = vm_env->GetMethodID(vm_env->FindClass("java/util/Enumeration"), "nextElement", "()Ljava/lang/Object;"); _mids[mid_Boolean_booleanValue] = vm_env->GetMethodID(_boo, "booleanValue", "()Z"); _mids[mid_Byte_byteValue] = vm_env->GetMethodID(_byt, "byteValue", "()B"); _mids[mid_Character_charValue] = vm_env->GetMethodID(_cha, "charValue", "()C"); _mids[mid_Double_doubleValue] = vm_env->GetMethodID(_dou, "doubleValue", "()D"); _mids[mid_Float_floatValue] = vm_env->GetMethodID(_flo, "floatValue", "()F"); _mids[mid_Integer_intValue] = vm_env->GetMethodID(_int, "intValue", "()I"); _mids[mid_Long_longValue] = vm_env->GetMethodID(_lon, "longValue", "()J"); _mids[mid_Short_shortValue] = vm_env->GetMethodID(_sho, "shortValue", "()S"); _mids[mid_Boolean_init] = vm_env->GetMethodID(_boo, "", "(Z)V"); _mids[mid_Byte_init] = vm_env->GetMethodID(_byt, "", "(B)V"); _mids[mid_Character_init] = vm_env->GetMethodID(_cha, "", "(C)V"); _mids[mid_Double_init] = vm_env->GetMethodID(_dou, "", "(D)V"); _mids[mid_Float_init] = vm_env->GetMethodID(_flo, "", "(F)V"); _mids[mid_Integer_init] = vm_env->GetMethodID(_int, "", "(I)V"); _mids[mid_Long_init] = vm_env->GetMethodID(_lon, "", "(J)V"); _mids[mid_Short_init] = vm_env->GetMethodID(_sho, "", "(S)V"); } int JCCEnv::attachCurrentThread(char *name, int asDaemon) { JNIEnv *jenv = NULL; JavaVMAttachArgs attach = { JNI_VERSION_1_4, name, NULL }; int result; if (asDaemon) result = vm->AttachCurrentThreadAsDaemon((void **) &jenv, &attach); else result = vm->AttachCurrentThread((void **) &jenv, &attach); set_vm_env(jenv); return result; } #if defined(_MSC_VER) || defined(__WIN32) void JCCEnv::set_vm_env(JNIEnv *vm_env) { if (!VM_ENV) VM_ENV = TlsAlloc(); TlsSetValue(VM_ENV, (LPVOID) vm_env); } #else void JCCEnv::set_vm_env(JNIEnv *vm_env) { if (!VM_ENV) pthread_key_create(&VM_ENV, NULL); pthread_setspecific(VM_ENV, (void *) vm_env); } #endif jint JCCEnv::getJNIVersion() const { return get_vm_env()->GetVersion(); } jstring JCCEnv::getJavaVersion() const { return (jstring) callStaticObjectMethod(_sys, _mids[mid_sys_getProperty], get_vm_env()->NewStringUTF("java.version")); } jobject JCCEnv::iterator(jobject obj) const { return callObjectMethod(obj, _mids[mid_iterator]); } jobject JCCEnv::iteratorNext(jobject obj) const { return callObjectMethod(obj, _mids[mid_iterator_next]); } jobject JCCEnv::enumerationNext(jobject obj) const { return callObjectMethod(obj, _mids[mid_enumeration_nextElement]); } jboolean JCCEnv::isInstanceOf(jobject obj, getclassfn initializeClass) const { return get_vm_env()->IsInstanceOf(obj, getClass(initializeClass)); } jclass JCCEnv::findClass(const char *className) const { jclass cls = NULL; if (vm) { JNIEnv *vm_env = get_vm_env(); if (vm_env) { cls = vm_env->FindClass(className); if (cls == NULL) reportException(); } #ifdef PYTHON else { PythonGIL gil; PyErr_SetString(PyExc_RuntimeError, "attachCurrentThread() must be called first"); throw _EXC_PYTHON; } #else else throw _EXC_JAVA; #endif } #ifdef PYTHON else { PythonGIL gil; PyErr_SetString(PyExc_RuntimeError, "initVM() must be called first"); throw _EXC_PYTHON; } #else else throw _EXC_JAVA; #endif reportException(); return cls; } void JCCEnv::registerNatives(jclass cls, JNINativeMethod *methods, int n) const { get_vm_env()->RegisterNatives(cls, methods, n); } jobject JCCEnv::newGlobalRef(jobject obj, int id) { if (obj) { if (id) /* zero when weak global ref is desired */ { lock locked; for (std::multimap::iterator iter = refs.find(id); iter != refs.end(); iter++) { if (iter->first != id) break; if (isSame(obj, iter->second.global)) { /* If it's in the table but not the same reference, * it must be a local reference and must be deleted. */ if (obj != iter->second.global) get_vm_env()->DeleteLocalRef(obj); iter->second.count += 1; return iter->second.global; } } JNIEnv *vm_env = get_vm_env(); countedRef ref; ref.global = vm_env->NewGlobalRef(obj); ref.count = 1; refs.insert(std::pair(id, ref)); vm_env->DeleteLocalRef(obj); return ref.global; } else return (jobject) get_vm_env()->NewWeakGlobalRef(obj); } return NULL; } jobject JCCEnv::deleteGlobalRef(jobject obj, int id) { if (obj) { if (id) /* zero when obj is weak global ref */ { lock locked; for (std::multimap::iterator iter = refs.find(id); iter != refs.end(); iter++) { if (iter->first != id) break; if (isSame(obj, iter->second.global)) { if (iter->second.count == 1) { JNIEnv *vm_env = get_vm_env(); if (!vm_env) { /* Python's cyclic garbage collector may remove * an object inside a thread that is not attached * to the JVM. This makes sure the JVM doesn't * segfault. */ attachCurrentThread(NULL, 0); vm_env = get_vm_env(); } vm_env->DeleteGlobalRef(iter->second.global); refs.erase(iter); } else iter->second.count -= 1; return NULL; } } printf("deleting non-existent ref: 0x%x\n", id); } else get_vm_env()->DeleteWeakGlobalRef((jweak) obj); } return NULL; } jclass JCCEnv::getClass(getclassfn initializeClass) const { jclass cls = (*initializeClass)(true); if (cls == NULL) { lock locked; cls = (*initializeClass)(false); } return cls; } jobject JCCEnv::newObject(getclassfn initializeClass, jmethodID **mids, int m, ...) { jclass cls = getClass(initializeClass); JNIEnv *vm_env = get_vm_env(); jobject obj; if (vm_env) { va_list ap; va_start(ap, m); obj = vm_env->NewObjectV(cls, (*mids)[m], ap); va_end(ap); } #ifdef PYTHON else { PythonGIL gil; PyErr_SetString(PyExc_RuntimeError, "attachCurrentThread() must be called first"); throw _EXC_PYTHON; } #else else throw _EXC_JAVA; #endif reportException(); return obj; } jobjectArray JCCEnv::newObjectArray(jclass cls, int size) { jobjectArray array = get_vm_env()->NewObjectArray(size, cls, NULL); reportException(); return array; } void JCCEnv::setObjectArrayElement(jobjectArray array, int n, jobject obj) const { get_vm_env()->SetObjectArrayElement(array, n, obj); reportException(); } jobject JCCEnv::getObjectArrayElement(jobjectArray array, int n) const { jobject obj = get_vm_env()->GetObjectArrayElement(array, n); reportException(); return obj; } int JCCEnv::getArrayLength(jarray array) const { int len = get_vm_env()->GetArrayLength(array); reportException(); return len; } #ifdef PYTHON jclass JCCEnv::getPythonExceptionClass() const { return _thr; } // returns true if Python exception instance was successfully restored bool JCCEnv::restorePythonException(jthrowable throwable) const { #ifdef _jcc_lib // PythonException is only available in shared mode jclass pycls = getPythonExceptionClass(); JNIEnv *vm_env = get_vm_env(); // Support through-layer exceptions by taking the active PythonException // and making the enclosed exception visible to Python again. if (vm_env->IsSameObject(vm_env->GetObjectClass(throwable), pycls)) { jfieldID fid = vm_env->GetFieldID(pycls, "py_error_state", "J"); PyObject *state = (PyObject *) vm_env->GetLongField(throwable, fid); if (state != NULL) { PyObject *type = PyTuple_GET_ITEM(state, 0); PyObject *value = PyTuple_GET_ITEM(state, 1); PyObject *tb = PyTuple_GET_ITEM(state, 2); Py_INCREF(type); if (value == Py_None) value = NULL; else Py_INCREF(value); if (tb == Py_None) tb = NULL; else Py_INCREF(tb); PyErr_Restore(type, value, tb); return true; } } #endif return false; } #endif void JCCEnv::reportException() const { JNIEnv *vm_env = get_vm_env(); jthrowable throwable = vm_env->ExceptionOccurred(); if (throwable) { if (!env->handlers) vm_env->ExceptionDescribe(); #ifdef PYTHON PythonGIL gil; if (PyErr_Occurred()) { /* _thr is PythonException ifdef _jcc_lib (shared mode) * if not shared mode, _thr is RuntimeException */ jobject cls = (jobject) vm_env->GetObjectClass(throwable); if (vm_env->IsSameObject(cls, _thr)) { #ifndef _jcc_lib /* PythonException class is not available without shared mode. * Python exception information thus gets lost and exception * is reported via plain Java RuntimeException. */ PyErr_Clear(); throw _EXC_JAVA; #else throw _EXC_PYTHON; #endif } } #endif throw _EXC_JAVA; } } #define DEFINE_CALL(jtype, Type) \ jtype JCCEnv::call##Type##Method(jobject obj, \ jmethodID mid, ...) const \ { \ va_list ap; \ jtype result; \ \ va_start(ap, mid); \ result = get_vm_env()->Call##Type##MethodV(obj, mid, ap); \ va_end(ap); \ \ reportException(); \ \ return result; \ } #define DEFINE_NONVIRTUAL_CALL(jtype, Type) \ jtype JCCEnv::callNonvirtual##Type##Method(jobject obj, jclass cls, \ jmethodID mid, ...) const \ { \ va_list ap; \ jtype result; \ \ va_start(ap, mid); \ result = get_vm_env()->CallNonvirtual##Type##MethodV(obj, cls, \ mid, ap); \ va_end(ap); \ \ reportException(); \ \ return result; \ } #define DEFINE_STATIC_CALL(jtype, Type) \ jtype JCCEnv::callStatic##Type##Method(jclass cls, \ jmethodID mid, ...) const \ { \ va_list ap; \ jtype result; \ \ va_start(ap, mid); \ result = get_vm_env()->CallStatic##Type##MethodV(cls, mid, ap); \ va_end(ap); \ \ reportException(); \ \ return result; \ } DEFINE_CALL(jobject, Object) DEFINE_CALL(jboolean, Boolean) DEFINE_CALL(jbyte, Byte) DEFINE_CALL(jchar, Char) DEFINE_CALL(jdouble, Double) DEFINE_CALL(jfloat, Float) DEFINE_CALL(jint, Int) DEFINE_CALL(jlong, Long) DEFINE_CALL(jshort, Short) DEFINE_NONVIRTUAL_CALL(jobject, Object) DEFINE_NONVIRTUAL_CALL(jboolean, Boolean) DEFINE_NONVIRTUAL_CALL(jbyte, Byte) DEFINE_NONVIRTUAL_CALL(jchar, Char) DEFINE_NONVIRTUAL_CALL(jdouble, Double) DEFINE_NONVIRTUAL_CALL(jfloat, Float) DEFINE_NONVIRTUAL_CALL(jint, Int) DEFINE_NONVIRTUAL_CALL(jlong, Long) DEFINE_NONVIRTUAL_CALL(jshort, Short) DEFINE_STATIC_CALL(jobject, Object) DEFINE_STATIC_CALL(jboolean, Boolean) DEFINE_STATIC_CALL(jbyte, Byte) DEFINE_STATIC_CALL(jchar, Char) DEFINE_STATIC_CALL(jdouble, Double) DEFINE_STATIC_CALL(jfloat, Float) DEFINE_STATIC_CALL(jint, Int) DEFINE_STATIC_CALL(jlong, Long) DEFINE_STATIC_CALL(jshort, Short) void JCCEnv::callVoidMethod(jobject obj, jmethodID mid, ...) const { va_list ap; va_start(ap, mid); get_vm_env()->CallVoidMethodV(obj, mid, ap); va_end(ap); reportException(); } void JCCEnv::callNonvirtualVoidMethod(jobject obj, jclass cls, jmethodID mid, ...) const { va_list ap; va_start(ap, mid); get_vm_env()->CallNonvirtualVoidMethodV(obj, cls, mid, ap); va_end(ap); reportException(); } void JCCEnv::callStaticVoidMethod(jclass cls, jmethodID mid, ...) const { va_list ap; va_start(ap, mid); get_vm_env()->CallStaticVoidMethodV(cls, mid, ap); va_end(ap); reportException(); } jboolean JCCEnv::booleanValue(jobject obj) const { return get_vm_env()->CallBooleanMethod(obj, _mids[mid_Boolean_booleanValue]); } jbyte JCCEnv::byteValue(jobject obj) const { return get_vm_env()->CallByteMethod(obj, _mids[mid_Byte_byteValue]); } jchar JCCEnv::charValue(jobject obj) const { return get_vm_env()->CallCharMethod(obj, _mids[mid_Character_charValue]); } jdouble JCCEnv::doubleValue(jobject obj) const { return get_vm_env()->CallDoubleMethod(obj, _mids[mid_Double_doubleValue]); } jfloat JCCEnv::floatValue(jobject obj) const { return get_vm_env()->CallFloatMethod(obj, _mids[mid_Float_floatValue]); } jint JCCEnv::intValue(jobject obj) const { return get_vm_env()->CallIntMethod(obj, _mids[mid_Integer_intValue]); } jlong JCCEnv::longValue(jobject obj) const { return get_vm_env()->CallLongMethod(obj, _mids[mid_Long_longValue]); } jshort JCCEnv::shortValue(jobject obj) const { return get_vm_env()->CallShortMethod(obj, _mids[mid_Short_shortValue]); } jobject JCCEnv::boxBoolean(jboolean value) const { return get_vm_env()->NewObject(_boo, _mids[mid_Boolean_init], value); } jobject JCCEnv::boxByte(jbyte value) const { return get_vm_env()->NewObject(_byt, _mids[mid_Byte_init], value); } jobject JCCEnv::boxChar(jchar value) const { return get_vm_env()->NewObject(_cha, _mids[mid_Character_init], value); } jobject JCCEnv::boxDouble(jdouble value) const { return get_vm_env()->NewObject(_dou, _mids[mid_Double_init], value); } jobject JCCEnv::boxFloat(jfloat value) const { return get_vm_env()->NewObject(_flo, _mids[mid_Float_init], value); } jobject JCCEnv::boxInteger(jint value) const { return get_vm_env()->NewObject(_int, _mids[mid_Integer_init], value); } jobject JCCEnv::boxLong(jlong value) const { return get_vm_env()->NewObject(_lon, _mids[mid_Long_init], value); } jobject JCCEnv::boxShort(jshort value) const { return get_vm_env()->NewObject(_sho, _mids[mid_Short_init], value); } jmethodID JCCEnv::getMethodID(jclass cls, const char *name, const char *signature) const { jmethodID id = get_vm_env()->GetMethodID(cls, name, signature); reportException(); return id; } jfieldID JCCEnv::getFieldID(jclass cls, const char *name, const char *signature) const { jfieldID id = get_vm_env()->GetFieldID(cls, name, signature); reportException(); return id; } jmethodID JCCEnv::getStaticMethodID(jclass cls, const char *name, const char *signature) const { jmethodID id = get_vm_env()->GetStaticMethodID(cls, name, signature); reportException(); return id; } jobject JCCEnv::getStaticObjectField(jclass cls, const char *name, const char *signature) const { JNIEnv *vm_env = get_vm_env(); jfieldID id = vm_env->GetStaticFieldID(cls, name, signature); reportException(); return vm_env->GetStaticObjectField(cls, id); } #define DEFINE_GET_STATIC_FIELD(jtype, Type, signature) \ jtype JCCEnv::getStatic##Type##Field(jclass cls, \ const char *name) const \ { \ JNIEnv *vm_env = get_vm_env(); \ jfieldID id = vm_env->GetStaticFieldID(cls, name, #signature); \ reportException(); \ return vm_env->GetStatic##Type##Field(cls, id); \ } DEFINE_GET_STATIC_FIELD(jboolean, Boolean, Z) DEFINE_GET_STATIC_FIELD(jbyte, Byte, B) DEFINE_GET_STATIC_FIELD(jchar, Char, C) DEFINE_GET_STATIC_FIELD(jdouble, Double, D) DEFINE_GET_STATIC_FIELD(jfloat, Float, F) DEFINE_GET_STATIC_FIELD(jint, Int, I) DEFINE_GET_STATIC_FIELD(jlong, Long, J) DEFINE_GET_STATIC_FIELD(jshort, Short, S) #define DEFINE_GET_FIELD(jtype, Type) \ jtype JCCEnv::get##Type##Field(jobject obj, jfieldID id) const \ { \ jtype value = get_vm_env()->Get##Type##Field(obj, id); \ reportException(); \ return value; \ } DEFINE_GET_FIELD(jobject, Object) DEFINE_GET_FIELD(jboolean, Boolean) DEFINE_GET_FIELD(jbyte, Byte) DEFINE_GET_FIELD(jchar, Char) DEFINE_GET_FIELD(jdouble, Double) DEFINE_GET_FIELD(jfloat, Float) DEFINE_GET_FIELD(jint, Int) DEFINE_GET_FIELD(jlong, Long) DEFINE_GET_FIELD(jshort, Short) #define DEFINE_SET_FIELD(jtype, Type) \ void JCCEnv::set##Type##Field(jobject obj, jfieldID id, \ jtype value) const \ { \ get_vm_env()->Set##Type##Field(obj, id, value); \ reportException(); \ } DEFINE_SET_FIELD(jobject, Object) DEFINE_SET_FIELD(jboolean, Boolean) DEFINE_SET_FIELD(jbyte, Byte) DEFINE_SET_FIELD(jchar, Char) DEFINE_SET_FIELD(jdouble, Double) DEFINE_SET_FIELD(jfloat, Float) DEFINE_SET_FIELD(jint, Int) DEFINE_SET_FIELD(jlong, Long) DEFINE_SET_FIELD(jshort, Short) void JCCEnv::setClassPath(const char *classPath) { JNIEnv *vm_env = get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jclass _fil = (jclass) vm_env->FindClass("java/io/File"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); jmethodID mf = vm_env->GetMethodID(_fil, "", "(Ljava/lang/String;)V"); jmethodID mu = vm_env->GetMethodID(_fil, "toURL", "()Ljava/net/URL;"); jmethodID ma = vm_env->GetMethodID(_ucl, "addURL", "(Ljava/net/URL;)V"); #if defined(_MSC_VER) || defined(__WIN32) const char *pathsep = ";"; char *path = _strdup(classPath); #else const char *pathsep = ":"; char *path = strdup(classPath); #endif for (char *cp = strtok(path, pathsep); cp != NULL; cp = strtok(NULL, pathsep)) { jstring string = vm_env->NewStringUTF(cp); jobject file = vm_env->NewObject(_fil, mf, string); jobject url = vm_env->CallObjectMethod(file, mu); vm_env->CallVoidMethod(classLoader, ma, url); } free(path); } char *JCCEnv::getClassPath() { JNIEnv *vm_env = get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jclass _url = (jclass) vm_env->FindClass("java/net/URL"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); jmethodID gu = vm_env->GetMethodID(_ucl, "getURLs", "()[Ljava/net/URL;"); jmethodID gp = vm_env->GetMethodID(_url, "getPath", "()Ljava/lang/String;"); #if defined(_MSC_VER) || defined(__WIN32) const char *pathsep = ";"; #else const char *pathsep = ":"; #endif jobjectArray array = (jobjectArray) vm_env->CallObjectMethod(classLoader, gu); int count = array ? vm_env->GetArrayLength(array) : 0; int first = 1, total = 0; char *classpath = NULL; for (int i = 0; i < count; i++) { jobject url = vm_env->GetObjectArrayElement(array, i); jstring path = (jstring) vm_env->CallObjectMethod(url, gp); const char *chars = vm_env->GetStringUTFChars(path, NULL); int size = vm_env->GetStringUTFLength(path); total += size + 1; if (classpath == NULL) classpath = (char *) calloc(total, 1); else classpath = (char *) realloc(classpath, total); if (classpath == NULL) return NULL; if (first) first = 0; else strcat(classpath, pathsep); strcat(classpath, chars); } return classpath; } jstring JCCEnv::fromUTF(const char *bytes) const { jstring str = get_vm_env()->NewStringUTF(bytes); reportException(); return str; } char *JCCEnv::toUTF(jstring str) const { JNIEnv *vm_env = get_vm_env(); int len = vm_env->GetStringUTFLength(str); char *bytes = new char[len + 1]; jboolean isCopy = 0; const char *utf = vm_env->GetStringUTFChars(str, &isCopy); if (!bytes) return NULL; memcpy(bytes, utf, len); bytes[len] = '\0'; vm_env->ReleaseStringUTFChars(str, utf); return bytes; } char *JCCEnv::toString(jobject obj) const { try { return obj ? toUTF((jstring) callObjectMethod(obj, _mids[mid_obj_toString])) : NULL; } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: { JNIEnv *vm_env = get_vm_env(); vm_env->ExceptionDescribe(); vm_env->ExceptionClear(); return NULL; } default: throw; } } } char *JCCEnv::getClassName(jobject obj) const { return obj ? toString(callObjectMethod(obj, _mids[mid_obj_getClass])) : NULL; } #ifdef PYTHON jstring JCCEnv::fromPyString(PyObject *object) const { if (object == Py_None) return NULL; if (PyUnicode_Check(object)) { if (sizeof(Py_UNICODE) == sizeof(jchar)) { jchar *buf = (jchar *) PyUnicode_AS_UNICODE(object); jsize len = (jsize) PyUnicode_GET_SIZE(object); return get_vm_env()->NewString(buf, len); } else { jsize len = PyUnicode_GET_SIZE(object); Py_UNICODE *pchars = PyUnicode_AS_UNICODE(object); jchar *jchars = new jchar[len]; jstring str; for (int i = 0; i < len; i++) jchars[i] = (jchar) pchars[i]; str = get_vm_env()->NewString(jchars, len); delete[] jchars; return str; } } else if (PyString_Check(object)) return fromUTF(PyString_AS_STRING(object)); else { PyObject *tuple = Py_BuildValue("(sO)", "expected a string", object); PyErr_SetObject(PyExc_TypeError, tuple); Py_DECREF(tuple); return NULL; } } PyObject *JCCEnv::fromJString(jstring js, int delete_local_ref) const { if (!js) Py_RETURN_NONE; JNIEnv *vm_env = get_vm_env(); PyObject *string; if (sizeof(Py_UNICODE) == sizeof(jchar)) { jboolean isCopy; const jchar *buf = vm_env->GetStringChars(js, &isCopy); jsize len = vm_env->GetStringLength(js); string = PyUnicode_FromUnicode((const Py_UNICODE *) buf, len); vm_env->ReleaseStringChars(js, buf); } else { jsize len = vm_env->GetStringLength(js); string = PyUnicode_FromUnicode(NULL, len); if (string) { jboolean isCopy; const jchar *jchars = vm_env->GetStringChars(js, &isCopy); Py_UNICODE *pchars = PyUnicode_AS_UNICODE(string); for (int i = 0; i < len; i++) pchars[i] = (Py_UNICODE) jchars[i]; vm_env->ReleaseStringChars(js, jchars); } } if (delete_local_ref) vm_env->DeleteLocalRef((jobject) js); return string; } /* may be called from finalizer thread which has no vm_env thread local */ void JCCEnv::finalizeObject(JNIEnv *jenv, PyObject *obj) { PythonGIL gil; set_vm_env(jenv); Py_DECREF(obj); } #endif /* PYTHON */ JCC-3.6/jcc2/sources/JObject.cpp0000644000076500000000000001415213063017435016521 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "JCCEnv.h" #ifdef PYTHON #include #include "structmember.h" #include "JObject.h" #include "macros.h" /* JObject */ static void t_JObject_dealloc(t_JObject *self); static PyObject *t_JObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject *t_JObject_richcmp(t_JObject *, PyObject *o2, int op); static PyObject *t_JObject_str(t_JObject *self); static PyObject *t_JObject_repr(t_JObject *self); static int t_JObject_hash(t_JObject *self); static PyObject *t_JObject__getJObject(t_JObject *self, void *data); static PyMemberDef t_JObject_members[] = { { NULL, 0, 0, 0, NULL } }; static PyMethodDef t_JObject_methods[] = { { NULL, NULL, 0, NULL } }; static PyGetSetDef t_JObject_properties[] = { { "_jobject", (getter) t_JObject__getJObject, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL, NULL } }; PyTypeObject PY_TYPE(JObject) = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "jcc.JObject", /* tp_name */ sizeof(t_JObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)t_JObject_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)t_JObject_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)t_JObject_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)t_JObject_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE), /* tp_flags */ "t_JObject objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)t_JObject_richcmp, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ t_JObject_methods, /* tp_methods */ t_JObject_members, /* tp_members */ t_JObject_properties, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ (newfunc)t_JObject_new, /* tp_new */ }; static void t_JObject_dealloc(t_JObject *self) { self->object = JObject(NULL); self->ob_type->tp_free((PyObject *) self); } static PyObject *t_JObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { t_JObject *self = (t_JObject *) type->tp_alloc(type, 0); self->object = JObject(NULL); return (PyObject *) self; } static PyObject *t_JObject_richcmp(t_JObject *self, PyObject *arg, int op) { int b = 0; switch (op) { case Py_EQ: case Py_NE: if (PyObject_TypeCheck(arg, &PY_TYPE(JObject))) b = self->object == ((t_JObject *) arg)->object; if (op == Py_EQ) Py_RETURN_BOOL(b); Py_RETURN_BOOL(!b); case Py_LT: PyErr_SetString(PyExc_NotImplementedError, "<"); return NULL; case Py_LE: PyErr_SetString(PyExc_NotImplementedError, "<="); return NULL; case Py_GT: PyErr_SetString(PyExc_NotImplementedError, ">"); return NULL; case Py_GE: PyErr_SetString(PyExc_NotImplementedError, ">="); return NULL; } return NULL; } static PyObject *t_JObject_str(t_JObject *self) { if (self->object.this$) { char *utf = env->toString(self->object.this$); if (utf == NULL) utf = env->getClassName(self->object.this$); if (utf != NULL) { PyObject *unicode = PyUnicode_DecodeUTF8(utf, strlen(utf), "strict"); delete utf; return unicode; } } return PyString_FromString(""); } static PyObject *t_JObject_repr(t_JObject *self) { PyObject *name = PyObject_GetAttrString((PyObject *) self->ob_type, "__name__"); PyObject *str = self->ob_type->tp_str((PyObject *) self); #if PY_VERSION_HEX < 0x02040000 PyObject *args = Py_BuildValue("(OO)", name, str); #else PyObject *args = PyTuple_Pack(2, name, str); #endif PyObject *format = PyString_FromString("<%s: %s>"); PyObject *repr = PyString_Format(format, args); Py_DECREF(name); Py_DECREF(str); Py_DECREF(args); Py_DECREF(format); return repr; } static int t_JObject_hash(t_JObject *self) { return env->hash(self->object.this$); } static PyObject *t_JObject__getJObject(t_JObject *self, void *data) { return PyCObject_FromVoidPtr((void *) self->object.this$, NULL); } #endif /* PYTHON */ JCC-3.6/jcc2/sources/JCCEnv.h0000644000076500000000000002575613063017435015732 0ustar vajdawheel00000000000000/* * Copyright (c) 2007-2008 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JCCEnv_H #define _JCCEnv_H #include #if defined(_MSC_VER) || defined(__WIN32) #define _DLL_IMPORT __declspec(dllimport) #define _DLL_EXPORT __declspec(dllexport) #include #undef MAX_PRIORITY #undef MIN_PRIORITY #else #include #define _DLL_IMPORT #define _DLL_EXPORT #endif #ifdef __SUNPRO_CC #undef DEFAULT_TYPE #endif #ifdef TRUE #undef TRUE #endif #ifdef FALSE #undef FALSE #endif #include #ifdef PYTHON #include #endif #undef EOF class JCCEnv; #if defined(_MSC_VER) || defined(__WIN32) #ifdef _jcc_shared _DLL_IMPORT extern JCCEnv *env; _DLL_IMPORT extern DWORD VM_ENV; #else _DLL_EXPORT extern JCCEnv *env; _DLL_EXPORT extern DWORD VM_ENV; #endif #else extern JCCEnv *env; #endif #define _EXC_PYTHON ((int) 0) #define _EXC_JAVA ((int) 1) typedef jclass (*getclassfn)(bool); class countedRef { public: jobject global; int count; }; class _DLL_EXPORT JCCEnv { protected: jclass _sys, _obj, _thr; jclass _boo, _byt, _cha, _dou, _flo, _int, _lon, _sho; jmethodID *_mids; enum { mid_sys_identityHashCode, mid_sys_setProperty, mid_sys_getProperty, mid_obj_toString, mid_obj_hashCode, mid_obj_getClass, mid_iterator, mid_iterator_next, mid_enumeration_nextElement, mid_Boolean_booleanValue, mid_Byte_byteValue, mid_Character_charValue, mid_Double_doubleValue, mid_Float_floatValue, mid_Integer_intValue, mid_Long_longValue, mid_Short_shortValue, mid_Boolean_init, mid_Byte_init, mid_Character_init, mid_Double_init, mid_Float_init, mid_Integer_init, mid_Long_init, mid_Short_init, max_mid }; public: JavaVM *vm; std::multimap refs; int handlers; explicit JCCEnv(JavaVM *vm, JNIEnv *env); #if defined(_MSC_VER) || defined(__WIN32) inline JNIEnv *get_vm_env() const { return (JNIEnv *) TlsGetValue(VM_ENV); } #else static pthread_key_t VM_ENV; inline JNIEnv *get_vm_env() const { return (JNIEnv *) pthread_getspecific(VM_ENV); } #endif void set_vm(JavaVM *vm, JNIEnv *vm_env); void set_vm_env(JNIEnv *vm_env); int attachCurrentThread(char *name, int asDaemon); jint getJNIVersion() const; jstring getJavaVersion() const; jclass findClass(const char *className) const; jboolean isInstanceOf(jobject obj, getclassfn initializeClass) const; void registerNatives(jclass cls, JNINativeMethod *methods, int n) const; jobject iterator(jobject obj) const; jobject iteratorNext(jobject obj) const; jobject enumerationNext(jobject obj) const; jobject newGlobalRef(jobject obj, int id); jobject deleteGlobalRef(jobject obj, int id); jclass getClass(getclassfn initializeClass) const; jobject newObject(getclassfn initializeClass, jmethodID **mids, int m, ...); jobjectArray newObjectArray(jclass cls, int size); void setObjectArrayElement(jobjectArray a, int n, jobject obj) const; jobject getObjectArrayElement(jobjectArray a, int n) const; int getArrayLength(jarray a) const; void reportException() const; jobject callObjectMethod(jobject obj, jmethodID mid, ...) const; jboolean callBooleanMethod(jobject obj, jmethodID mid, ...) const; jbyte callByteMethod(jobject obj, jmethodID mid, ...) const; jchar callCharMethod(jobject obj, jmethodID mid, ...) const; jdouble callDoubleMethod(jobject obj, jmethodID mid, ...) const; jfloat callFloatMethod(jobject obj, jmethodID mid, ...) const; jint callIntMethod(jobject obj, jmethodID mid, ...) const; jlong callLongMethod(jobject obj, jmethodID mid, ...) const; jshort callShortMethod(jobject obj, jmethodID mid, ...) const; void callVoidMethod(jobject obj, jmethodID mid, ...) const; jobject callNonvirtualObjectMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jboolean callNonvirtualBooleanMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jbyte callNonvirtualByteMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jchar callNonvirtualCharMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jdouble callNonvirtualDoubleMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jfloat callNonvirtualFloatMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jint callNonvirtualIntMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jlong callNonvirtualLongMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jshort callNonvirtualShortMethod(jobject obj, jclass cls, jmethodID mid, ...) const; void callNonvirtualVoidMethod(jobject obj, jclass cls, jmethodID mid, ...) const; jobject callStaticObjectMethod(jclass cls, jmethodID mid, ...) const; jboolean callStaticBooleanMethod(jclass cls, jmethodID mid, ...) const; jbyte callStaticByteMethod(jclass cls, jmethodID mid, ...) const; jchar callStaticCharMethod(jclass cls, jmethodID mid, ...) const; jdouble callStaticDoubleMethod(jclass cls, jmethodID mid, ...) const; jfloat callStaticFloatMethod(jclass cls, jmethodID mid, ...) const; jint callStaticIntMethod(jclass cls, jmethodID mid, ...) const; jlong callStaticLongMethod(jclass cls, jmethodID mid, ...) const; jshort callStaticShortMethod(jclass cls, jmethodID mid, ...) const; void callStaticVoidMethod(jclass cls, jmethodID mid, ...) const; jboolean booleanValue(jobject obj) const; jbyte byteValue(jobject obj) const; jchar charValue(jobject obj) const; jdouble doubleValue(jobject obj) const; jfloat floatValue(jobject obj) const; jint intValue(jobject obj) const; jlong longValue(jobject obj) const; jshort shortValue(jobject obj) const; jobject boxBoolean(jboolean value) const; jobject boxByte(jbyte value) const; jobject boxChar(jchar value) const; jobject boxDouble(jdouble value) const; jobject boxFloat(jfloat value) const; jobject boxInteger(jint value) const; jobject boxLong(jlong value) const; jobject boxShort(jshort value) const; jmethodID getMethodID(jclass cls, const char *name, const char *signature) const; jfieldID getFieldID(jclass cls, const char *name, const char *signature) const; jmethodID getStaticMethodID(jclass cls, const char *name, const char *signature) const; jobject getStaticObjectField(jclass cls, const char *name, const char *signature) const; jboolean getStaticBooleanField(jclass cls, const char *name) const; jbyte getStaticByteField(jclass cls, const char *name) const; jchar getStaticCharField(jclass cls, const char *name) const; jdouble getStaticDoubleField(jclass cls, const char *name) const; jfloat getStaticFloatField(jclass cls, const char *name) const; jint getStaticIntField(jclass cls, const char *name) const; jlong getStaticLongField(jclass cls, const char *name) const; jshort getStaticShortField(jclass cls, const char *name) const; jobject getObjectField(jobject obj, jfieldID id) const; jboolean getBooleanField(jobject obj, jfieldID id) const; jbyte getByteField(jobject obj, jfieldID id) const; jchar getCharField(jobject obj, jfieldID id) const; jdouble getDoubleField(jobject obj, jfieldID id) const; jfloat getFloatField(jobject obj, jfieldID id) const; jint getIntField(jobject obj, jfieldID id) const; jlong getLongField(jobject obj, jfieldID id) const; jshort getShortField(jobject obj, jfieldID id) const; void setObjectField(jobject obj, jfieldID id, jobject value) const; void setBooleanField(jobject obj, jfieldID id, jboolean value) const; void setByteField(jobject obj, jfieldID id, jbyte value) const; void setCharField(jobject obj, jfieldID id, jchar value) const; void setDoubleField(jobject obj, jfieldID id, jdouble value) const; void setFloatField(jobject obj, jfieldID id, jfloat value) const; void setIntField(jobject obj, jfieldID id, jint value) const; void setLongField(jobject obj, jfieldID id, jlong value) const; void setShortField(jobject obj, jfieldID id, jshort value) const; int id(jobject obj) const { return obj ? get_vm_env()->CallStaticIntMethod(_sys, _mids[mid_sys_identityHashCode], obj) : 0; } int hash(jobject obj) const { return obj ? get_vm_env()->CallIntMethod(obj, _mids[mid_obj_hashCode]) : 0; } void setClassPath(const char *classPath); char *getClassPath(); jstring fromUTF(const char *bytes) const; char *toUTF(jstring str) const; char *toString(jobject obj) const; char *getClassName(jobject obj) const; #ifdef PYTHON jclass getPythonExceptionClass() const; bool restorePythonException(jthrowable throwable) const; jstring fromPyString(PyObject *object) const; PyObject *fromJString(jstring js, int delete_local_ref) const; void finalizeObject(JNIEnv *jenv, PyObject *obj); #endif inline int isSame(jobject o1, jobject o2) const { return o1 == o2 || get_vm_env()->IsSameObject(o1, o2); } }; #ifdef PYTHON class PythonGIL { private: PyGILState_STATE state; public: PythonGIL() { state = PyGILState_Ensure(); } PythonGIL(JNIEnv *vm_env) { state = PyGILState_Ensure(); env->set_vm_env(vm_env); } ~PythonGIL() { PyGILState_Release(state); } }; class PythonThreadState { private: PyThreadState *state; int handler; public: PythonThreadState(int handler=0) { state = PyEval_SaveThread(); this->handler = handler; env->handlers += handler; } ~PythonThreadState() { PyEval_RestoreThread(state); env->handlers -= handler; } }; #endif #endif /* _JCCEnv_H */ JCC-3.6/jcc2/sources/macros.h0000644000076500000000000002540013063017435016130 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _macros_H #define _macros_H #define OBJ_CALL(action) \ { \ try { \ PythonThreadState state(1); \ action; \ } catch (int e) { \ switch (e) { \ case _EXC_PYTHON: \ return NULL; \ case _EXC_JAVA: \ return PyErr_SetJavaError(); \ default: \ throw; \ } \ } \ } #define INT_CALL(action) \ { \ try { \ PythonThreadState state(1); \ action; \ } catch (int e) { \ switch (e) { \ case _EXC_PYTHON: \ return -1; \ case _EXC_JAVA: \ PyErr_SetJavaError(); \ return -1; \ default: \ throw; \ } \ } \ } #define DECLARE_METHOD(type, name, flags) \ { #name, (PyCFunction) type##_##name, flags, "" } #define DECLARE_GET_FIELD(type, name) \ { #name, (getter) type##_get__##name, NULL, "", NULL } #define DECLARE_SET_FIELD(type, name) \ { #name, NULL, (setter) type##_set__##name, "", NULL } #define DECLARE_GETSET_FIELD(type, name) \ { #name, (getter) type##_get__##name, (setter) type##_set__##name, "", NULL } #define PY_TYPE(name) name##$$Type #define DECLARE_TYPE(name, t_name, base, javaClass, \ init, iter, iternext, getset, mapping, sequence) \ PyTypeObject PY_TYPE(name) = { \ PyObject_HEAD_INIT(NULL) \ /* ob_size */ 0, \ /* tp_name */ #name, \ /* tp_basicsize */ sizeof(t_name), \ /* tp_itemsize */ 0, \ /* tp_dealloc */ 0, \ /* tp_print */ 0, \ /* tp_getattr */ 0, \ /* tp_setattr */ 0, \ /* tp_compare */ 0, \ /* tp_repr */ 0, \ /* tp_as_number */ 0, \ /* tp_as_sequence */ sequence, \ /* tp_as_mapping */ mapping, \ /* tp_hash */ 0, \ /* tp_call */ 0, \ /* tp_str */ 0, \ /* tp_getattro */ 0, \ /* tp_setattro */ 0, \ /* tp_as_buffer */ 0, \ /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, \ /* tp_doc */ #t_name" objects", \ /* tp_traverse */ 0, \ /* tp_clear */ 0, \ /* tp_richcompare */ 0, \ /* tp_weaklistoffset */ 0, \ /* tp_iter */ (getiterfunc) iter, \ /* tp_iternext */ (iternextfunc) iternext, \ /* tp_methods */ t_name##__methods_, \ /* tp_members */ 0, \ /* tp_getset */ getset, \ /* tp_base */ &PY_TYPE(base), \ /* tp_dict */ 0, \ /* tp_descr_get */ 0, \ /* tp_descr_set */ 0, \ /* tp_dictoffset */ 0, \ /* tp_init */ (initproc)init, \ /* tp_alloc */ 0, \ /* tp_new */ 0, \ }; \ PyObject *t_name::wrap_Object(const javaClass& object) \ { \ if (!!object) \ { \ t_name *self = \ (t_name *) PY_TYPE(name).tp_alloc(&PY_TYPE(name), 0); \ if (self) \ self->object = object; \ return (PyObject *) self; \ } \ Py_RETURN_NONE; \ } \ PyObject *t_name::wrap_jobject(const jobject& object) \ { \ if (!!object) \ { \ if (!env->isInstanceOf(object, javaClass::initializeClass)) \ { \ PyErr_SetObject(PyExc_TypeError, \ (PyObject *) &PY_TYPE(name)); \ return NULL; \ } \ t_name *self = (t_name *) \ PY_TYPE(name).tp_alloc(&PY_TYPE(name), 0); \ if (self) \ self->object = javaClass(object); \ return (PyObject *) self; \ } \ Py_RETURN_NONE; \ } \ #define INSTALL_TYPE(name, module) \ if (PyType_Ready(&PY_TYPE(name)) == 0) \ { \ Py_INCREF(&PY_TYPE(name)); \ PyModule_AddObject(module, #name, (PyObject *) &PY_TYPE(name)); \ } #define Py_RETURN_BOOL(b) \ { \ if (b) \ Py_RETURN_TRUE; \ else \ Py_RETURN_FALSE; \ } #define Py_RETURN_SELF \ { \ Py_INCREF(self); \ return (PyObject *) self; \ } #if PY_VERSION_HEX < 0x02040000 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None #define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True #define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False #define Py_CLEAR(op) \ do { \ if (op) { \ PyObject *tmp = (PyObject *)(op); \ (op) = NULL; \ Py_DECREF(tmp); \ } \ } while (0) #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit((PyObject *)(op), arg); \ if (vret) \ return vret; \ } \ } while (0) #endif /* Python 2.3.5 */ #endif /* _macros_H */ JCC-3.6/jcc2/sources/JArray.h0000644000076500000000000013627713063017435016053 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JArray_H #define _JArray_H #ifdef PYTHON #include #include "macros.h" #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #endif extern jobjectArray fromPySequence(jclass cls, PyObject *sequence); extern jobjectArray fromPySequence(jclass cls, PyObject **args, int length); extern PyObject *PyErr_SetJavaError(); extern PyTypeObject *PY_TYPE(JArrayObject); extern PyTypeObject *PY_TYPE(JArrayString); extern PyTypeObject *PY_TYPE(JArrayBool); extern PyTypeObject *PY_TYPE(JArrayByte); extern PyTypeObject *PY_TYPE(JArrayChar); extern PyTypeObject *PY_TYPE(JArrayDouble); extern PyTypeObject *PY_TYPE(JArrayFloat); extern PyTypeObject *PY_TYPE(JArrayInt); extern PyTypeObject *PY_TYPE(JArrayLong); extern PyTypeObject *PY_TYPE(JArrayShort); #else typedef int Py_ssize_t; #endif /* PYTHON */ #include "JCCEnv.h" #include "java/lang/Object.h" template class JArray : public java::lang::Object { public: Py_ssize_t length; explicit JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(fromPySequence(env->getClass(T::initializeClass), sequence)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(jclass cls, PyObject *sequence) : java::lang::Object(fromPySequence(cls, sequence)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(jclass cls, PyObject **args, int length) : java::lang::Object(fromPySequence(cls, args, length)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } PyObject *toSequence(PyObject *(*wrapfn)(const T&)) { if (this$ == NULL) Py_RETURN_NONE; PyObject *list = PyList_New(length); for (Py_ssize_t i = 0; i < length; i++) PyList_SET_ITEM(list, i, (*wrapfn)((*this)[i])); return list; } PyObject *get(Py_ssize_t n, PyObject *(*wrapfn)(const T&)) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return (*wrapfn)((*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } #endif T operator[](Py_ssize_t n) { return T(env->getObjectArrayElement((jobjectArray) this$, n)); } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; JArray(jclass cls, Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewObjectArray(n, cls, NULL)) { length = env->getArrayLength((jobjectArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } #ifdef PYTHON JArray(jclass cls, PyObject *sequence) : java::lang::Object(fromPySequence(cls, sequence)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(jclass cls, PyObject **args, int length) : java::lang::Object(fromPySequence(cls, args, length)) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } PyObject *toSequence(PyObject *(*wrapfn)(const jobject&)) { return toSequence(0, length, wrapfn); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi, PyObject *(*wrapfn)(const jobject&)) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); if (!wrapfn) wrapfn = java::lang::t_Object::wrap_jobject; for (Py_ssize_t i = lo; i < hi; i++) { jobject jobj = env->getObjectArrayElement((jobjectArray) this$, i); PyObject *obj = (*wrapfn)(jobj); PyList_SET_ITEM(list, i - lo, obj); } return list; } PyObject *get(Py_ssize_t n, PyObject *(*wrapfn)(const jobject&)) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!wrapfn) wrapfn = java::lang::t_Object::wrap_jobject; jobject jobj = env->getObjectArrayElement((jobjectArray) this$, n); return (*wrapfn)(jobj); } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jobject jobj; if (PyString_Check(obj) || PyUnicode_Check(obj)) jobj = env->fromPyString(obj); else if (!PyObject_TypeCheck(obj, &PY_TYPE(JObject))) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } else jobj = ((t_JObject *) obj)->object.this$; try { env->setObjectArrayElement((jobjectArray) this$, n, jobj); } catch (int e) { switch (e) { case _EXC_JAVA: PyErr_SetJavaError(); return -1; default: throw; } } return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap(PyObject *(*wrapfn)(const jobject&)) const; #endif jobject operator[](Py_ssize_t n) { return (jobject) env->getObjectArrayElement((jobjectArray) this$, n); } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jobjectArray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewObjectArray(n, env->findClass("java/lang/String"), NULL)) { length = env->getArrayLength((jobjectArray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewObjectArray(PySequence_Length(sequence), env->findClass("java/lang/String"), NULL)) { length = env->getArrayLength((jobjectArray) this$); for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (obj == NULL) break; jstring str = env->fromPyString(obj); Py_DECREF(obj); if (PyErr_Occurred()) break; env->setObjectArrayElement((jobjectArray) this$, i, str); env->get_vm_env()->DeleteLocalRef(str); } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); for (Py_ssize_t i = lo; i < hi; i++) { jstring str = (jstring) env->getObjectArrayElement((jobjectArray) this$, i); PyObject *obj = env->fromJString(str, 1); PyList_SET_ITEM(list, i - lo, obj); } return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jstring str = (jstring) env->getObjectArrayElement((jobjectArray) this$, n); PyObject *obj = env->fromJString(str, 1); return obj; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jstring str = env->fromPyString(obj); if (PyErr_Occurred()) return -1; env->setObjectArrayElement((jobjectArray) this$, n, str); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jstring operator[](Py_ssize_t n) { return (jstring) env->getObjectArrayElement((jobjectArray) this$, n); } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jbooleanArray array; jboolean *elts; public: arrayElements(jbooleanArray array) { this->array = array; elts = env->get_vm_env()->GetBooleanArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseBooleanArrayElements(array, elts, 0); } operator jboolean *() { return elts; } }; arrayElements elements() { return arrayElements((jbooleanArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewBooleanArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewBooleanArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jboolean *buf = (jboolean *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (obj == Py_True || obj == Py_False) { buf[i] = (jboolean) (obj == Py_True); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewBooleanArray(length)) { arrayElements elts = elements(); jboolean *buf = (jboolean *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (obj == Py_True || obj == Py_False) buf[i] = (jboolean) (obj == Py_True); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jboolean *buf = (jboolean *) elts; for (Py_ssize_t i = lo; i < hi; i++) { jboolean value = buf[i]; PyObject *obj = value ? Py_True : Py_False; Py_INCREF(obj); PyList_SET_ITEM(list, i - lo, obj); } return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) Py_RETURN_BOOL(elements()[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { elements()[n] = (jboolean) PyObject_IsTrue(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jboolean operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jboolean *elts = (jboolean *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jboolean value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jbyteArray array; jbyte *elts; public: arrayElements(jbyteArray array) { this->array = array; elts = env->get_vm_env()->GetByteArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseByteArrayElements(array, elts, 0); } operator jbyte *() { return elts; } }; arrayElements elements() { return arrayElements((jbyteArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewByteArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewByteArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; if (PyString_Check(sequence)) memcpy(buf, PyString_AS_STRING(sequence), length); else for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyString_Check(obj) && (PyString_GET_SIZE(obj) == 1)) { buf[i] = (jbyte) PyString_AS_STRING(obj)[0]; Py_DECREF(obj); } else if (PyInt_CheckExact(obj)) { buf[i] = (jbyte) PyInt_AS_LONG(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewByteArray(length)) { arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyString_Check(obj) && (PyString_GET_SIZE(obj) == 1)) buf[i] = (jbyte) PyString_AS_STRING(obj)[0]; else if (PyInt_CheckExact(obj)) buf[i] = (jbyte) PyInt_AS_LONG(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } char getType() { return 'Z'; } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; PyObject *tuple = PyTuple_New(hi - lo); for (Py_ssize_t i = 0; i < hi - lo; i++) PyTuple_SET_ITEM(tuple, i, PyInt_FromLong(buf[lo + i])); return tuple; } PyObject *to_string_() { if (this$ == NULL) Py_RETURN_NONE; arrayElements elts = elements(); jbyte *buf = (jbyte *) elts; return PyString_FromStringAndSize((char *) buf, length); } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jbyte b = (*this)[n]; return PyInt_FromLong(b); } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyInt_CheckExact(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jbyte) PyInt_AS_LONG(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jbyte operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jbyte *elts = (jbyte *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jbyte value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jcharArray array; jchar *elts; public: arrayElements(jcharArray array) { this->array = array; elts = env->get_vm_env()->GetCharArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseCharArrayElements(array, elts, 0); } operator jchar *() { return elts; } }; arrayElements elements() { return arrayElements((jcharArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewCharArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewCharArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jchar *buf = (jchar *) elts; if (PyUnicode_Check(sequence)) { if (sizeof(Py_UNICODE) == sizeof(jchar)) memcpy(buf, PyUnicode_AS_UNICODE(sequence), length * sizeof(jchar)); else { Py_UNICODE *pchars = PyUnicode_AS_UNICODE(sequence); for (Py_ssize_t i = 0; i < length; i++) buf[i] = (jchar) pchars[i]; } } else for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyUnicode_Check(obj) && (PyUnicode_GET_SIZE(obj) == 1)) { buf[i] = (jchar) PyUnicode_AS_UNICODE(obj)[0]; Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewCharArray(length)) { arrayElements elts = elements(); jchar *buf = (jchar *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyUnicode_Check(obj) && (PyUnicode_GET_SIZE(obj) == 1)) buf[i] = (jchar) PyUnicode_AS_UNICODE(obj)[0]; else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; arrayElements elts = elements(); jchar *buf = (jchar *) elts; if (sizeof(Py_UNICODE) == sizeof(jchar)) return PyUnicode_FromUnicode((const Py_UNICODE *) buf + lo, hi - lo); else { PyObject *string = PyUnicode_FromUnicode(NULL, hi - lo); Py_UNICODE *pchars = PyUnicode_AS_UNICODE(string); for (Py_ssize_t i = lo; i < hi; i++) pchars[i - lo] = (Py_UNICODE) buf[i]; return string; } } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { jchar c = (*this)[n]; if (sizeof(Py_UNICODE) == sizeof(jchar)) return PyUnicode_FromUnicode((const Py_UNICODE *) &c, 1); else { PyObject *string = PyUnicode_FromUnicode(NULL, 1); Py_UNICODE *pchars = PyUnicode_AS_UNICODE(string); pchars[0] = (Py_UNICODE) c; return string; } } } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyUnicode_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } if (PyUnicode_GET_SIZE(obj) != 1) { PyErr_SetObject(PyExc_ValueError, obj); return -1; } elements()[n] = (jchar) PyUnicode_AS_UNICODE(obj)[0]; return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jchar operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jchar *elts = (jchar *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jchar value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jdoubleArray array; jdouble *elts; public: arrayElements(jdoubleArray array) { this->array = array; elts = env->get_vm_env()->GetDoubleArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseDoubleArrayElements(array, elts, 0); } operator jdouble *() { return elts; } }; arrayElements elements() { return arrayElements((jdoubleArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewDoubleArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewDoubleArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jdouble *buf = (jdouble *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyFloat_Check(obj)) { buf[i] = (jdouble) PyFloat_AS_DOUBLE(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewDoubleArray(length)) { arrayElements elts = elements(); jdouble *buf = (jdouble *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyFloat_Check(obj)) buf[i] = (jdouble) PyFloat_AS_DOUBLE(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jdouble *buf = (jdouble *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyFloat_FromDouble((double) buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyFloat_FromDouble((double) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyFloat_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jdouble) PyFloat_AS_DOUBLE(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jdouble operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jdouble *elts = (jdouble *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jdouble value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jfloatArray array; jfloat *elts; public: arrayElements(jfloatArray array) { this->array = array; elts = env->get_vm_env()->GetFloatArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseFloatArrayElements(array, elts, 0); } operator jfloat *() { return elts; } }; arrayElements elements() { return arrayElements((jfloatArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewFloatArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewFloatArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jfloat *buf = (jfloat *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyFloat_Check(obj)) { buf[i] = (jfloat) PyFloat_AS_DOUBLE(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewFloatArray(length)) { arrayElements elts = elements(); jfloat *buf = (jfloat *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyFloat_Check(obj)) buf[i] = (jfloat) PyFloat_AS_DOUBLE(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jfloat *buf = (jfloat *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyFloat_FromDouble((double) buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyFloat_FromDouble((double) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyFloat_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jfloat) PyFloat_AS_DOUBLE(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jfloat operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jfloat *elts = (jfloat *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jfloat value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jintArray array; jint *elts; public: arrayElements(jintArray array) { this->array = array; elts = env->get_vm_env()->GetIntArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseIntArrayElements(array, elts, 0); } operator jint *() { return elts; } }; arrayElements elements() { return arrayElements((jintArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewIntArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewIntArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jint *buf = (jint *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyInt_Check(obj)) { buf[i] = (jint) PyInt_AS_LONG(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewIntArray(length)) { arrayElements elts = elements(); jint *buf = (jint *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyInt_Check(obj)) buf[i] = (jint) PyInt_AS_LONG(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jint *buf = (jint *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyInt_FromLong(buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyInt_FromLong((*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyInt_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jint) PyInt_AS_LONG(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jint operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jint *elts = (jint *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jint value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jlongArray array; jlong *elts; public: arrayElements(jlongArray array) { this->array = array; elts = env->get_vm_env()->GetLongArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseLongArrayElements(array, elts, 0); } operator jlong *() { return elts; } }; arrayElements elements() { return arrayElements((jlongArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewLongArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewLongArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jlong *buf = (jlong *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyLong_Check(obj)) { buf[i] = (jlong) PyLong_AsLongLong(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewLongArray(length)) { arrayElements elts = elements(); jlong *buf = (jlong *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyLong_Check(obj)) buf[i] = (jlong) PyLong_AsLongLong(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jlong *buf = (jlong *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyLong_FromLongLong((long long) buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyLong_FromLongLong((long long) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyLong_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jlong) PyLong_AsLongLong(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jlong operator[](long n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jlong *elts = (jlong *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jlong value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; template<> class JArray : public java::lang::Object { public: Py_ssize_t length; class arrayElements { private: jboolean isCopy; jshortArray array; jshort *elts; public: arrayElements(jshortArray array) { this->array = array; elts = env->get_vm_env()->GetShortArrayElements(array, &isCopy); } virtual ~arrayElements() { env->get_vm_env()->ReleaseShortArrayElements(array, elts, 0); } operator jshort *() { return elts; } }; arrayElements elements() { return arrayElements((jshortArray) this$); } JArray(jobject obj) : java::lang::Object(obj) { length = this$ ? env->getArrayLength((jarray) this$) : 0; } JArray(const JArray& obj) : java::lang::Object(obj) { length = obj.length; } JArray(Py_ssize_t n) : java::lang::Object(env->get_vm_env()->NewShortArray(n)) { length = env->getArrayLength((jarray) this$); } #ifdef PYTHON JArray(PyObject *sequence) : java::lang::Object(env->get_vm_env()->NewShortArray(PySequence_Length(sequence))) { length = env->getArrayLength((jarray) this$); arrayElements elts = elements(); jshort *buf = (jshort *) elts; for (Py_ssize_t i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (PyInt_Check(obj)) { buf[i] = (jshort) PyInt_AS_LONG(obj); Py_DECREF(obj); } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); break; } } } JArray(PyObject **args, int length) : java::lang::Object(env->get_vm_env()->NewShortArray(length)) { arrayElements elts = elements(); jshort *buf = (jshort *) elts; for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; if (PyInt_Check(obj)) buf[i] = (jshort) PyInt_AS_LONG(obj); else { PyErr_SetObject(PyExc_TypeError, obj); break; } } } PyObject *toSequence() { return toSequence(0, length); } PyObject *toSequence(Py_ssize_t lo, Py_ssize_t hi) { if (this$ == NULL) Py_RETURN_NONE; if (lo < 0) lo = length + lo; if (lo < 0) lo = 0; else if (lo > length) lo = length; if (hi < 0) hi = length + hi; if (hi < 0) hi = 0; else if (hi > length) hi = length; if (lo > hi) lo = hi; PyObject *list = PyList_New(hi - lo); arrayElements elts = elements(); jshort *buf = (jshort *) elts; for (Py_ssize_t i = lo; i < hi; i++) PyList_SET_ITEM(list, i - lo, PyInt_FromLong(buf[i])); return list; } PyObject *get(Py_ssize_t n) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) return PyInt_FromLong((long) (*this)[n]); } PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } int set(Py_ssize_t n, PyObject *obj) { if (this$ != NULL) { if (n < 0) n = length + n; if (n >= 0 && n < length) { if (!PyInt_Check(obj)) { PyErr_SetObject(PyExc_TypeError, obj); return -1; } elements()[n] = (jshort) PyInt_AS_LONG(obj); return 0; } } PyErr_SetString(PyExc_IndexError, "index out of range"); return -1; } PyObject *wrap() const; #endif jshort operator[](Py_ssize_t n) { JNIEnv *vm_env = env->get_vm_env(); jboolean isCopy = 0; jshort *elts = (jshort *) vm_env->GetPrimitiveArrayCritical((jarray) this$, &isCopy); jshort value = elts[n]; vm_env->ReleasePrimitiveArrayCritical((jarray) this$, elts, 0); return value; } }; #ifdef PYTHON template class t_JArray { public: PyObject_HEAD JArray array; }; template class t_JArrayWrapper { public: static PyObject *wrap_Object(const JArray &array) { if (!!array) return array.wrap(U::wrap_jobject); Py_RETURN_NONE; } static PyObject *wrap_jobject(const jobject &array) { if (!!array) return JArray(array).wrap(U::wrap_jobject); Py_RETURN_NONE; } }; template class t_JArrayWrapper { public: static PyObject *wrap_Object(const JArray &array) { if (!!array) return array.wrap(); Py_RETURN_NONE; } static PyObject *wrap_jobject(const jobject &array) { if (!!array) return JArray(array).wrap(); Py_RETURN_NONE; } }; #endif #endif /* _JArray_H */ JCC-3.6/jcc2/sources/functions.h0000644000076500000000000002231213063017435016653 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _functions_h #define _functions_h #include "java/util/Iterator.h" #include "java/util/Enumeration.h" #include "java/lang/String.h" #include "java/lang/Object.h" #include "macros.h" #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; typedef inquiry lenfunc; typedef intargfunc ssizeargfunc; typedef intintargfunc ssizessizeargfunc; typedef intobjargproc ssizeobjargproc; typedef intintobjargproc ssizessizeobjargproc; #endif typedef PyTypeObject **(*getparametersfn)(void *); typedef int (*boxfn)(PyTypeObject *, PyObject *, java::lang::Object *); PyObject *PyErr_SetArgsError(char *name, PyObject *args); PyObject *PyErr_SetArgsError(PyObject *self, char *name, PyObject *args); PyObject *PyErr_SetArgsError(PyTypeObject *type, char *name, PyObject *args); PyObject *PyErr_SetJavaError(); extern PyObject *PyExc_JavaError; extern PyObject *PyExc_InvalidArgsError; void throwPythonError(void); void throwTypeError(const char *name, PyObject *object); #if defined(_MSC_VER) || defined(__SUNPRO_CC) #define parseArgs __parseArgs #define parseArg __parseArg int __parseArgs(PyObject *args, char *types, ...); int __parseArg(PyObject *arg, char *types, ...); int _parseArgs(PyObject **args, unsigned int count, char *types, va_list list, va_list check); #else #define parseArgs(args, types, rest...) \ _parseArgs(((PyTupleObject *)(args))->ob_item, \ ((PyTupleObject *)(args))->ob_size, types, ##rest) #define parseArg(arg, types, rest...) \ _parseArgs(&(arg), 1, types, ##rest) int _parseArgs(PyObject **args, unsigned int count, char *types, ...); #endif int abstract_init(PyObject *self, PyObject *args, PyObject *kwds); PyObject *wrapType(PyTypeObject *type, const jobject& obj); PyObject *unboxBoolean(const jobject& obj); PyObject *unboxByte(const jobject& obj); PyObject *unboxCharacter(const jobject& obj); PyObject *unboxDouble(const jobject& obj); PyObject *unboxFloat(const jobject& obj); PyObject *unboxInteger(const jobject& obj); PyObject *unboxLong(const jobject& obj); PyObject *unboxShort(const jobject& obj); PyObject *unboxString(const jobject& obj); int boxBoolean(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxByte(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxCharacter(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxCharSequence(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxDouble(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxFloat(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxInteger(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxLong(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxNumber(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxShort(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxString(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); int boxObject(PyTypeObject *type, PyObject *arg, java::lang::Object *obj); PyObject *j2p(const java::lang::String& js); java::lang::String p2j(PyObject *object); PyObject *make_descriptor(PyTypeObject *value); PyObject *make_descriptor(getclassfn initializeClass); PyObject *make_descriptor(getclassfn initializeClass, int generics); PyObject *make_descriptor(PyObject *value); PyObject *make_descriptor(PyObject *(*wrapfn)(const jobject &)); PyObject *make_descriptor(boxfn fn); PyObject *make_descriptor(jboolean value); PyObject *make_descriptor(jbyte value); PyObject *make_descriptor(jchar value); PyObject *make_descriptor(jdouble value); PyObject *make_descriptor(jfloat value); PyObject *make_descriptor(jint value); PyObject *make_descriptor(jlong value); PyObject *make_descriptor(jshort value); jobjectArray make_array(jclass cls, PyObject *sequence); PyObject *callSuper(PyTypeObject *type, const char *name, PyObject *args, int cardinality); PyObject *callSuper(PyTypeObject *type, PyObject *self, const char *name, PyObject *args, int cardinality); template PyObject *get_iterator(T *self) { jobject iterator; OBJ_CALL(iterator = env->iterator(self->object.this$)); return java::util::t_Iterator::wrap_jobject(iterator); } #ifdef _java_generics template PyObject *get_generic_iterator(T *self) { PyTypeObject *param = self->parameters[0]; jobject iterator; OBJ_CALL(iterator = env->iterator(self->object.this$)); return java::util::t_Iterator::wrap_jobject(iterator, param); } #endif template PyObject *get_iterator_next(T *self) { jboolean hasNext; OBJ_CALL(hasNext = self->object.hasNext()); if (!hasNext) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->iteratorNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); return U::wrap_jobject(next); } #ifdef _java_generics template PyObject *get_generic_iterator_next(T *self) { jboolean hasNext; OBJ_CALL(hasNext = self->object.hasNext()); if (!hasNext) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->iteratorNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); PyTypeObject *param = self->parameters[0]; if (param != NULL) return wrapType(param, next); return U::wrap_jobject(next); } #endif template PyObject *get_enumeration_next(T *self) { jboolean hasMoreElements; OBJ_CALL(hasMoreElements = self->object.hasMoreElements()); if (!hasMoreElements) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->enumerationNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); return U::wrap_jobject(next); } #ifdef _java_generics template PyObject *get_generic_enumeration_next(T *self) { jboolean hasMoreElements; OBJ_CALL(hasMoreElements = self->object.hasMoreElements()); if (!hasMoreElements) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jobject next; OBJ_CALL(next = env->enumerationNext(self->object.this$)); jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next, cls)) return env->fromJString((jstring) next, 1); PyTypeObject *param = self->parameters[0]; if (param != NULL) return wrapType(param, next); return U::wrap_jobject(next); } #endif template PyObject *get_next(T *self) { V next((jobject) NULL); OBJ_CALL(next = self->object.next()); if (!next) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next.this$, cls)) return env->fromJString((jstring) next.this$, 0); return U::wrap_Object(next); } #ifdef _java_generics template PyObject *get_generic_next(T *self) { V next((jobject) NULL); OBJ_CALL(next = self->object.next()); if (!next) { PyErr_SetNone(PyExc_StopIteration); return NULL; } jclass cls = env->getClass(java::lang::String::initializeClass); if (env->get_vm_env()->IsInstanceOf(next.this$, cls)) return env->fromJString((jstring) next.this$, 0); PyTypeObject *param = self->parameters[0]; if (param != NULL) return wrapType(param, next.this$); return U::wrap_Object(next); } #endif PyObject *get_extension_iterator(PyObject *self); PyObject *get_extension_next(PyObject *self); PyObject *get_extension_nextElement(PyObject *self); jobjectArray fromPySequence(jclass cls, PyObject *sequence); jobjectArray fromPySequence(jclass cls, PyObject **args, int length); PyObject *castCheck(PyObject *obj, getclassfn initializeClass, int reportError); void installType(PyTypeObject *type, PyObject *module, char *name, int isExtension); #ifdef _java_generics PyObject *typeParameters(PyTypeObject *types[], size_t size); #endif extern PyTypeObject PY_TYPE(FinalizerClass); extern PyTypeObject PY_TYPE(FinalizerProxy); typedef struct { PyObject_HEAD PyObject *object; } t_fp; #endif /* _functions_h */ JCC-3.6/jcc2/sources/functions.cpp0000644000076500000000000017605213502045202017210 0ustar vajdawheel00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #ifdef _MSC_VER #include #else #include #endif #include "java/lang/Object.h" #include "java/lang/Class.h" #include "java/lang/String.h" #include "java/lang/Throwable.h" #include "java/lang/Boolean.h" #include "java/lang/Byte.h" #include "java/lang/Character.h" #include "java/lang/Double.h" #include "java/lang/Float.h" #include "java/lang/Integer.h" #include "java/lang/Long.h" #include "java/lang/Short.h" #include "java/util/Iterator.h" #include "JArray.h" #include "functions.h" #include "macros.h" using namespace java::lang; using namespace java::util; PyObject *PyExc_JavaError = PyExc_ValueError; PyObject *PyExc_InvalidArgsError = PyExc_ValueError; PyObject *_set_exception_types(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "OO", &PyExc_JavaError, &PyExc_InvalidArgsError)) return NULL; Py_RETURN_NONE; } PyObject *_set_function_self(PyObject *self, PyObject *args) { PyObject *object, *module; if (!PyArg_ParseTuple(args, "OO", &object, &module)) return NULL; if (!PyCFunction_Check(object)) { PyErr_SetObject(PyExc_TypeError, object); return NULL; } PyCFunctionObject *cfn = (PyCFunctionObject *) object; Py_INCREF(module); Py_XDECREF(cfn->m_self); cfn->m_self = module; Py_RETURN_NONE; } PyObject *findClass(PyObject *self, PyObject *args) { char *className; if (!PyArg_ParseTuple(args, "s", &className)) return NULL; try { jclass cls = env->findClass(className); if (cls) return t_Class::wrap_Object(Class(cls)); } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: return PyErr_SetJavaError(); default: throw; } } Py_RETURN_NONE; } static const char interface_bytes[] = { '\xca', '\xfe', '\xba', '\xbe', // magic number: 0xcafebabe '\x00', '\x00', '\x00', '\x32', // version 50.0 '\x00', '\x07', // constant pool max index: 6 '\x07', '\x00', '\x04', // 1: class name at 4 '\x07', '\x00', '\x05', // 2: class name at 5 '\x07', '\x00', '\x06', // 3: class name at 6 '\x01', '\x00', '\x00', // 4: empty string '\x01', '\x00', '\x10', // 5: 16-byte string: java/lang/Object 'j', 'a', 'v', 'a', '/', 'l', 'a', 'n', 'g', '/', 'O', 'b', 'j', 'e', 'c', 't', '\x01', '\x00', '\x00', // 6: empty string '\x06', '\x01', // public abstract interface '\x00', '\x01', // this class at 1 '\x00', '\x02', // superclass at 2 '\x00', '\x01', // 1 interface '\x00', '\x03', // interface at 3 '\x00', '\x00', // 0 fields '\x00', '\x00', // 0 methods '\x00', '\x00' // 0 attributes }; /* make an empty interface that extends an interface */ PyObject *makeInterface(PyObject *self, PyObject *args) { char *name, *extName; int name_len, extName_len; if (!PyArg_ParseTuple(args, "s#s#", &name, &name_len, &extName, &extName_len)) return NULL; JNIEnv *vm_env = env->get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); const int bytes_len = sizeof(interface_bytes); const int len = bytes_len + name_len + extName_len; char *buf = (char *) malloc(len); if (buf == NULL) return PyErr_NoMemory(); int name_pos = 22; int extName_pos = 44; jclass cls; memcpy(buf, interface_bytes, name_pos); memcpy(buf + name_pos + name_len, interface_bytes + name_pos, extName_pos - name_pos); memcpy(buf + extName_pos + name_len + extName_len, interface_bytes + extName_pos, bytes_len - extName_pos); extName_pos += name_len; *((unsigned short *) (buf + name_pos - 2)) = htons(name_len); memcpy(buf + name_pos, name, name_len); *((unsigned short *) (buf + extName_pos - 2)) = htons(extName_len); memcpy(buf + extName_pos, extName, extName_len); cls = vm_env->DefineClass(name, classLoader, (const jbyte *) buf, len); free(buf); if (cls) return t_Class::wrap_Object(Class(cls)); return PyErr_SetJavaError(); } static const char class_bytes[] = { '\xca', '\xfe', '\xba', '\xbe', // magic number: 0xcafebabe '\x00', '\x00', '\x00', '\x32', // version 50.0 '\x00', '\x0c', // constant pool max index: 11 '\x0a', '\x00', '\x03', '\x00', '\x08', // 1: method for class 3 at 8 '\x07', '\x00', '\x09', // 2: class name at 9 '\x07', '\x00', '\x0a', // 3: class name at 10 '\x07', '\x00', '\x0b', // 4: class name at 11 '\x01', '\x00', '\x06', // 5: 6-byte string: '<', 'i', 'n', 'i', 't', '>', '\x01', '\x00', '\x03', '(', ')', 'V', // 6: 3-byte string: ()V '\x01', '\x00', '\x04', // 7: 4-byte string: Code 'C', 'o', 'd', 'e', '\x0c', '\x00', '\x05', '\x00', '\x06', // 8: name at 5, signature at 6 '\x01', '\x00', '\x00', // 9: empty string '\x01', '\x00', '\x00', // 10: empty string '\x01', '\x00', '\x00', // 11: empty string '\x00', '\x21', // super public '\x00', '\x02', // this class at 2 '\x00', '\x03', // superclass at 3 '\x00', '\x01', // 1 interface '\x00', '\x04', // interface at 4 '\x00', '\x00', // 0 fields '\x00', '\x01', // 1 method '\x00', '\x01', '\x00', '\x05', // public, name at 5 '\x00', '\x06', '\x00', '\x01', // signature at 6, 1 attribute '\x00', '\x07', // attribute name at 7: Code '\x00', '\x00', '\x00', '\x11', // 17 bytes past 6 attribute bytes '\x00', '\x01', // max stack: 1 '\x00', '\x01', // max locals: 1 '\x00', '\x00', '\x00', '\x05', // code length: 5 '\x2a', '\xb7', '\x00', '\x01', '\xb1', // actual code bytes '\x00', '\x00', // 0 method exceptions '\x00', '\x00', // 0 method attributes '\x00', '\x00', // 0 attributes }; /* make an empty class that extends a class and implements an interface */ PyObject *makeClass(PyObject *self, PyObject *args) { char *name, *extName, *implName; int name_len, extName_len, implName_len; if (!PyArg_ParseTuple(args, "s#s#s#", &name, &name_len, &extName, &extName_len, &implName, &implName_len)) return NULL; JNIEnv *vm_env = env->get_vm_env(); jclass _ucl = (jclass) vm_env->FindClass("java/net/URLClassLoader"); jmethodID mid = vm_env->GetStaticMethodID(_ucl, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); jobject classLoader = vm_env->CallStaticObjectMethod(_ucl, mid); const int bytes_len = sizeof(class_bytes); const int len = bytes_len + name_len + extName_len + implName_len; char *buf = (char *) malloc(len); if (buf == NULL) return PyErr_NoMemory(); int name_pos = 54; int extName_pos = 57; int implName_pos = 60; jclass cls; memcpy(buf, class_bytes, name_pos); memcpy(buf + name_pos + name_len, class_bytes + name_pos, extName_pos - name_pos); memcpy(buf + extName_pos + name_len + extName_len, class_bytes + extName_pos, bytes_len - extName_pos); memcpy(buf + implName_pos + name_len + extName_len + implName_len, class_bytes + implName_pos, bytes_len - implName_pos); extName_pos += name_len; implName_pos += name_len + extName_len; *((unsigned short *) (buf + name_pos - 2)) = htons(name_len); memcpy(buf + name_pos, name, name_len); *((unsigned short *) (buf + extName_pos - 2)) = htons(extName_len); memcpy(buf + extName_pos, extName, extName_len); *((unsigned short *) (buf + implName_pos - 2)) = htons(implName_len); memcpy(buf + implName_pos, implName, implName_len); cls = vm_env->DefineClass(name, classLoader, (const jbyte *) buf, len); free(buf); if (cls) return t_Class::wrap_Object(Class(cls)); return PyErr_SetJavaError(); } static boxfn get_boxfn(PyTypeObject *type) { static PyObject *boxfn_ = PyString_FromString("boxfn_"); PyObject *cobj = PyObject_GetAttr((PyObject *) type, boxfn_); boxfn fn; if (cobj == NULL) return NULL; fn = (boxfn) PyCObject_AsVoidPtr(cobj); Py_DECREF(cobj); return fn; } static int is_instance_of(PyObject *arg, PyTypeObject *type) { static PyObject *class_ = PyString_FromString("class_"); PyObject *clsObj = PyObject_GetAttr((PyObject *) type, class_); int result; if (clsObj == NULL) return -1; result = env->get_vm_env()-> IsInstanceOf(((t_Object *) arg)->object.this$, (jclass) ((t_Object *) clsObj)->object.this$); Py_DECREF(clsObj); return result; } #if defined(_MSC_VER) || defined(__SUNPRO_CC) int __parseArgs(PyObject *args, char *types, ...) { int count = ((PyTupleObject *)(args))->ob_size; va_list list, check; va_start(list, types); va_start(check, types); return _parseArgs(((PyTupleObject *)(args))->ob_item, count, types, list, check); } int __parseArg(PyObject *arg, char *types, ...) { va_list list, check; va_start(list, types); va_start(check, types); return _parseArgs(&arg, 1, types, list, check); } int _parseArgs(PyObject **args, unsigned int count, char *types, va_list list, va_list check) { unsigned int typeCount = strlen(types); if (count > typeCount) return -1; #else int _parseArgs(PyObject **args, unsigned int count, char *types, ...) { unsigned int typeCount = strlen(types); va_list list, check; va_start(list, types); va_start(check, types); #endif if (!env->vm) { PyErr_SetString(PyExc_RuntimeError, "initVM() must be called first"); return -1; } JNIEnv *vm_env = env->get_vm_env(); if (!vm_env) { PyErr_SetString(PyExc_RuntimeError, "attachCurrentThread() must be called first"); return -1; } bool last = false; /* true if last expected parameter */ bool varargs = false; /* true if in varargs mode */ bool empty = false; /* true if in varargs mode and no params passed */ int array = 0; /* > 0 if expecting an array, its nesting level */ unsigned int pos = 0; for (unsigned int a = 0; a < count; a++, pos++) { PyObject *arg = args[a]; char tc = types[pos]; last = last || types[pos + 1] == '\0'; if (array > 1 && tc != '[') tc = 'o'; switch (tc) { case '[': { if (++array > 1 && !PyObject_TypeCheck(arg, PY_TYPE(JArrayObject))) return -1; a -= 1; break; } case 'j': /* Java object, with class$ */ case 'k': /* Java object, with initializeClass */ case 'K': /* Java object, with initializeClass and params */ { jclass cls = NULL; switch (tc) { case 'j': cls = (jclass) va_arg(list, Class *)->this$; break; case 'k': case 'K': try { getclassfn initializeClass = va_arg(list, getclassfn); cls = env->getClass(initializeClass); } catch (int e) { switch (e) { case _EXC_PYTHON: return -1; case _EXC_JAVA: PyErr_SetJavaError(); return -1; default: throw; } } break; } if (arg == Py_None) break; /* ensure that class Class is initialized (which may not be the * case because of earlier recursion avoidance (JObject(cls)). */ if (!Class::class$) env->getClass(Class::initializeClass); if (array) { if (PyObject_TypeCheck(arg, PY_TYPE(JArrayObject))) break; if (PySequence_Check(arg) && !PyString_Check(arg) && !PyUnicode_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = 0; if (obj == Py_None) ok = 1; else if (PyObject_TypeCheck(obj, &PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) obj)->object.this$, cls)) ok = 1; else if (PyObject_TypeCheck(obj, &PY_TYPE(FinalizerProxy))) { PyObject *o = ((t_fp *) obj)->object; if (PyObject_TypeCheck(o, &PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) o)->object.this$, cls)) ok = 1; } Py_DECREF(obj); if (ok) break; } else break; } if (last) { int ok = 0; if (arg == Py_None) ok = 1; else if (PyObject_TypeCheck(arg, &PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) arg)->object.this$, cls)) ok = 1; else if (PyObject_TypeCheck(arg, &PY_TYPE(FinalizerProxy))) { PyObject *o = ((t_fp *) arg)->object; if (PyObject_TypeCheck(o, &PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) o)->object.this$, cls)) ok = 1; } if (ok) { varargs = true; break; } } } else if (PyObject_TypeCheck(arg, &PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) arg)->object.this$, cls)) break; else if (PyObject_TypeCheck(arg, &PY_TYPE(FinalizerProxy))) { arg = ((t_fp *) arg)->object; if (PyObject_TypeCheck(arg, &PY_TYPE(Object)) && vm_env->IsInstanceOf(((t_Object *) arg)->object.this$, cls)) break; } return -1; } case 'Z': /* boolean, strict */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayBool))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = obj == Py_True || obj == Py_False; Py_DECREF(obj); if (ok) break; } else break; } if (last && (arg == Py_True || arg == Py_False)) { varargs = true; break; } } else if (arg == Py_True || arg == Py_False) break; return -1; } case 'B': /* byte */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayByte))) break; if (last) { if (PyString_Check(arg) && (PyString_Size(arg) == 1)) { varargs = true; break; } } } else if (PyString_Check(arg) && (PyString_Size(arg) == 1)) break; return -1; } case 'C': /* char */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayChar))) break; if (last) { if (PyUnicode_Check(arg) && (PyUnicode_GET_SIZE(arg) == 1)) { varargs = true; break; } } } else if (PyUnicode_Check(arg) && PyUnicode_GET_SIZE(arg) == 1) break; return -1; } case 'I': /* int */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayInt))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyInt_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyInt_CheckExact(arg)) { varargs = true; break; } } else if (PyInt_CheckExact(arg)) break; return -1; } case 'S': /* short */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayShort))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyInt_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyInt_CheckExact(arg)) { varargs = true; break; } } else if (PyInt_CheckExact(arg)) break; return -1; } case 'D': /* double */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayDouble))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyFloat_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyFloat_CheckExact(arg)) { varargs = true; break; } } else if (PyFloat_CheckExact(arg)) break; return -1; } case 'F': /* float */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayFloat))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyFloat_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyFloat_CheckExact(arg)) { varargs = true; break; } } else if (PyFloat_CheckExact(arg)) break; return -1; } case 'J': /* long long */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayLong))) break; if (PySequence_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = PyLong_CheckExact(obj); Py_DECREF(obj); if (ok) break; } else break; } if (last && PyLong_CheckExact(arg)) { varargs = true; break; } } else if (PyLong_CheckExact(arg)) break; return -1; } case 's': /* string */ { if (array) { if (arg == Py_None) break; if (PyObject_TypeCheck(arg, PY_TYPE(JArrayString))) break; if (PySequence_Check(arg) && !PyString_Check(arg) && !PyUnicode_Check(arg)) { if (PySequence_Length(arg) > 0) { PyObject *obj = PySequence_GetItem(arg, 0); int ok = (obj == Py_None || PyString_Check(obj) || PyUnicode_Check(obj)); Py_DECREF(obj); if (ok) break; } else break; } if (last && (arg == Py_None || PyString_Check(arg) || PyUnicode_Check(arg))) { varargs = true; break; } } else if (arg == Py_None || PyString_Check(arg) || PyUnicode_Check(arg)) break; return -1; } case 'o': /* java.lang.Object */ break; case 'O': /* java.lang.Object with type param */ { PyTypeObject *type = va_arg(list, PyTypeObject *); if (type != NULL) { boxfn fn = get_boxfn(type); if (fn == NULL || fn(type, arg, NULL) < 0) return -1; } break; } case 'T': /* tuple of python types with wrapfn_ */ { static PyObject *wrapfn_ = PyString_FromString("wrapfn_"); int len = va_arg(list, int); if (PyTuple_Check(arg)) { if (PyTuple_GET_SIZE(arg) != len) return -1; for (int i = 0; i < len; i++) { PyObject *type = PyTuple_GET_ITEM(arg, i); if (!(type == Py_None || (PyType_Check(type) && PyObject_HasAttr(type, wrapfn_)))) return -1; } break; } return -1; } default: return -1; } if (tc != '[') array = 0; if (varargs) { pos = typeCount; break; } } if (array) return -1; if (pos == typeCount - 2 && types[pos] == '[' && types[pos + 1] != '[') { varargs = true; empty = true; pos = typeCount; } if (pos != typeCount) return -1; pos = 0; last = false; for (unsigned int a = 0; a <= count; a++, pos++) { char tc = types[pos]; PyObject *arg; if (a == count) { if (empty) /* empty varargs */ arg = NULL; else break; } else arg = args[a]; last = last || types[pos + 1] == '\0'; if (array > 1 && tc != '[') tc = 'o'; switch (tc) { case '[': { array += 1; a -= 1; break; } case 'j': /* Java object except String and Object */ case 'k': /* Java object, with initializeClass */ case 'K': /* Java object, with initializeClass and params */ { jclass cls = NULL; switch (tc) { case 'j': cls = (jclass) va_arg(check, Class *)->this$; break; case 'k': case 'K': getclassfn initializeClass = va_arg(check, getclassfn); cls = env->getClass(initializeClass); break; } if (array) { JArray *array = va_arg(list, JArray *); #ifdef _java_generics if (tc == 'K') { PyTypeObject ***tp = va_arg(list, PyTypeObject ***); va_arg(list, getparametersfn); *tp = NULL; } #endif if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = fromPySequence(cls, args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayObject))) *array = ((t_JArray *) arg)->array; else *array = JArray(cls, arg); if (PyErr_Occurred()) return -1; } else { Object *obj = va_arg(list, Object *); if (PyObject_TypeCheck(arg, &PY_TYPE(FinalizerProxy))) arg = ((t_fp *) arg)->object; #ifdef _java_generics if (tc == 'K') { PyTypeObject ***tp = va_arg(list, PyTypeObject ***); PyTypeObject **(*parameters_)(void *) = va_arg(list, getparametersfn); if (arg == Py_None) *tp = NULL; else *tp = (*parameters_)(arg); } #endif *obj = arg == Py_None ? Object(NULL) : ((t_Object *) arg)->object; } break; } case 'Z': /* boolean, strict */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayBool))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jboolean *b = va_arg(list, jboolean *); *b = arg == Py_True; } break; } case 'B': /* byte */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayByte))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else if (PyString_Check(arg)) { jbyte *a = va_arg(list, jbyte *); *a = (jbyte) PyString_AS_STRING(arg)[0]; } else { jbyte *a = va_arg(list, jbyte *); *a = (jbyte) PyInt_AsLong(arg); } break; } case 'C': /* char */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayChar))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jchar *c = va_arg(list, jchar *); *c = (jchar) PyUnicode_AS_UNICODE(arg)[0]; } break; } case 'I': /* int */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayInt))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jint *n = va_arg(list, jint *); *n = (jint) PyInt_AsLong(arg); } break; } case 'S': /* short */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayShort))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jshort *n = va_arg(list, jshort *); *n = (jshort) PyInt_AsLong(arg); } break; } case 'D': /* double */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayDouble))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jdouble *d = va_arg(list, jdouble *); *d = (jdouble) PyFloat_AsDouble(arg); } break; } case 'F': /* float */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayFloat))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jfloat *d = va_arg(list, jfloat *); *d = (jfloat) (float) PyFloat_AsDouble(arg); } break; } case 'J': /* long long */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray(args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayLong))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { jlong *l = va_arg(list, jlong *); *l = (jlong) PyLong_AsLongLong(arg); } break; } case 's': /* string */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = fromPySequence( env->getClass(String::initializeClass), args + a, count - a); else if (PyObject_TypeCheck(arg, PY_TYPE(JArrayString))) *array = ((t_JArray *) arg)->array; else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { String *str = va_arg(list, String *); if (arg == Py_None) *str = String(NULL); else { *str = p2j(arg); if (PyErr_Occurred()) return -1; } } break; } case 'o': /* java.lang.Object */ case 'O': /* java.lang.Object with type param */ { if (array) { JArray *array = va_arg(list, JArray *); if (arg == Py_None) *array = JArray((jobject) NULL); else if (last && varargs) *array = JArray( env->getClass(Object::initializeClass), args + a, count - a); else *array = JArray(arg); if (PyErr_Occurred()) return -1; } else { Object *obj = va_arg(list, Object *); if (tc == 'O') { PyTypeObject *type = va_arg(check, PyTypeObject *); if (type != NULL) { boxfn fn = get_boxfn(type); if (fn == NULL || fn(type, arg, obj) < 0) return -1; break; } } if (boxObject(NULL, arg, obj) < 0) return -1; } break; } case 'T': /* tuple of python types with wrapfn_ */ { int len = va_arg(check, int); PyTypeObject **types = va_arg(list, PyTypeObject **); for (int i = 0; i < len; i++) { PyObject *type = PyTuple_GET_ITEM(arg, i); if (type == Py_None) types[i] = NULL; else types[i] = (PyTypeObject *) type; } break; } default: return -1; } if (tc != '[') array = 0; if (last && varargs) { pos = typeCount; break; } } if (pos == typeCount) return 0; return -1; } String p2j(PyObject *object) { return String(env->fromPyString(object)); } PyObject *j2p(const String& js) { return env->fromJString((jstring) js.this$, 0); } PyObject *PyErr_SetArgsError(char *name, PyObject *args) { if (!PyErr_Occurred()) { PyObject *err = Py_BuildValue("(sO)", name, args); PyErr_SetObject(PyExc_InvalidArgsError, err); Py_DECREF(err); } return NULL; } PyObject *PyErr_SetArgsError(PyObject *self, char *name, PyObject *args) { if (!PyErr_Occurred()) { PyObject *type = (PyObject *) self->ob_type; PyObject *err = Py_BuildValue("(OsO)", type, name, args); PyErr_SetObject(PyExc_InvalidArgsError, err); Py_DECREF(err); } return NULL; } PyObject *PyErr_SetArgsError(PyTypeObject *type, char *name, PyObject *args) { if (!PyErr_Occurred()) { PyObject *err = Py_BuildValue("(OsO)", type, name, args); PyErr_SetObject(PyExc_InvalidArgsError, err); Py_DECREF(err); } return NULL; } PyObject *PyErr_SetJavaError() { JNIEnv *vm_env = env->get_vm_env(); jthrowable throwable = vm_env->ExceptionOccurred(); vm_env->ExceptionClear(); if (env->restorePythonException(throwable)) return NULL; PyObject *err = t_Throwable::wrap_Object(Throwable(throwable)); PyErr_SetObject(PyExc_JavaError, err); Py_DECREF(err); return NULL; } void throwPythonError(void) { PyObject *exc = PyErr_Occurred(); if (exc && PyErr_GivenExceptionMatches(exc, PyExc_JavaError)) { PyObject *value, *traceback; PyErr_Fetch(&exc, &value, &traceback); if (value) { PyObject *je = PyObject_CallMethod(value, "getJavaException", ""); if (!je) PyErr_Restore(exc, value, traceback); else { Py_DECREF(exc); Py_DECREF(value); Py_XDECREF(traceback); exc = je; if (exc && PyObject_TypeCheck(exc, &PY_TYPE(Throwable))) { jobject jobj = ((t_Throwable *) exc)->object.this$; env->get_vm_env()->Throw((jthrowable) jobj); Py_DECREF(exc); return; } } } else { Py_DECREF(exc); Py_XDECREF(traceback); } } else if (exc && PyErr_GivenExceptionMatches(exc, PyExc_StopIteration)) { PyErr_Clear(); return; } if (exc) { PyObject *name = PyObject_GetAttrString(exc, "__name__"); env->get_vm_env()->ThrowNew(env->getPythonExceptionClass(), PyString_AS_STRING(name)); Py_DECREF(name); } else env->get_vm_env()->ThrowNew(env->getPythonExceptionClass(), "python error"); } void throwTypeError(const char *name, PyObject *object) { PyObject *tuple = Py_BuildValue("(ssO)", "while calling", name, object); PyErr_SetObject(PyExc_TypeError, tuple); Py_DECREF(tuple); env->get_vm_env()->ThrowNew(env->getPythonExceptionClass(), "type error"); } int abstract_init(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *err = Py_BuildValue("(sO)", "instantiating java class", self->ob_type); PyErr_SetObject(PyExc_NotImplementedError, err); Py_DECREF(err); return -1; } PyObject *callSuper(PyTypeObject *type, const char *name, PyObject *args, int cardinality) { PyObject *super = (PyObject *) type->tp_base; PyObject *method = PyObject_GetAttrString(super, (char *) name); // python 2.4 cast PyObject *value; if (!method) return NULL; if (cardinality > 1) value = PyObject_Call(method, args, NULL); else { #if PY_VERSION_HEX < 0x02040000 PyObject *tuple = Py_BuildValue("(O)", args); #else PyObject *tuple = PyTuple_Pack(1, args); #endif value = PyObject_Call(method, tuple, NULL); Py_DECREF(tuple); } Py_DECREF(method); return value; } PyObject *callSuper(PyTypeObject *type, PyObject *self, const char *name, PyObject *args, int cardinality) { #if PY_VERSION_HEX < 0x02040000 PyObject *tuple = Py_BuildValue("(OO)", type, self); #else PyObject *tuple = PyTuple_Pack(2, type, self); #endif PyObject *super = PyObject_Call((PyObject *) &PySuper_Type, tuple, NULL); PyObject *method, *value; Py_DECREF(tuple); if (!super) return NULL; method = PyObject_GetAttrString(super, (char *) name); // python 2.4 cast Py_DECREF(super); if (!method) return NULL; if (cardinality > 1) value = PyObject_Call(method, args, NULL); else { #if PY_VERSION_HEX < 0x02040000 tuple = Py_BuildValue("(O)", args); #else tuple = PyTuple_Pack(1, args); #endif value = PyObject_Call(method, tuple, NULL); Py_DECREF(tuple); } Py_DECREF(method); return value; } PyObject *castCheck(PyObject *obj, getclassfn initializeClass, int reportError) { if (PyObject_TypeCheck(obj, &PY_TYPE(FinalizerProxy))) obj = ((t_fp *) obj)->object; if (!PyObject_TypeCheck(obj, &PY_TYPE(Object))) { if (reportError) PyErr_SetObject(PyExc_TypeError, obj); return NULL; } jobject jobj = ((t_Object *) obj)->object.this$; if (jobj && !env->isInstanceOf(jobj, initializeClass)) { if (reportError) PyErr_SetObject(PyExc_TypeError, obj); return NULL; } return obj; } PyObject *get_extension_iterator(PyObject *self) { return PyObject_CallMethod(self, "iterator", ""); } PyObject *get_extension_next(PyObject *self) { return PyObject_CallMethod(self, "next", ""); } PyObject *get_extension_nextElement(PyObject *self) { return PyObject_CallMethod(self, "nextElement", ""); } static bool setArrayObj(jobjectArray array, int index, PyObject *obj) { bool deleteLocal = false; jobject jobj; if (obj == Py_None) jobj = NULL; else if (PyString_Check(obj) || PyUnicode_Check(obj)) { jobj = env->fromPyString(obj); deleteLocal = true; } else if (PyObject_TypeCheck(obj, &PY_TYPE(JObject))) jobj = ((t_JObject *) obj)->object.this$; else if (PyObject_TypeCheck(obj, &PY_TYPE(FinalizerProxy))) jobj = ((t_JObject *) ((t_fp *) obj)->object)->object.this$; else if (obj == Py_True || obj == Py_False) { jobj = env->boxBoolean(obj == Py_True); deleteLocal = true; } else if (PyFloat_Check(obj)) { jobj = env->boxDouble(PyFloat_AS_DOUBLE(obj)); deleteLocal = true; } else if (PyInt_Check(obj)) { jobj = env->boxInteger(PyInt_AS_LONG(obj)); deleteLocal = true; } else if (PyLong_Check(obj)) { jobj = env->boxLong(PyLong_AsLongLong(obj)); deleteLocal = true; } else { PyErr_SetObject(PyExc_TypeError, obj); Py_DECREF(obj); return false; } try { env->setObjectArrayElement(array, index, jobj); if (deleteLocal) env->get_vm_env()->DeleteLocalRef(jobj); Py_DECREF(obj); } catch (int e) { Py_DECREF(obj); switch (e) { case _EXC_JAVA: PyErr_SetJavaError(); return false; default: throw; } } return true; } jobjectArray fromPySequence(jclass cls, PyObject *sequence) { if (sequence == Py_None) return NULL; if (!PySequence_Check(sequence)) { PyErr_SetObject(PyExc_TypeError, sequence); return NULL; } int length = PySequence_Length(sequence); jobjectArray array; try { array = env->newObjectArray(cls, length); } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: PyErr_SetJavaError(); return NULL; default: throw; } } for (int i = 0; i < length; i++) { PyObject *obj = PySequence_GetItem(sequence, i); if (!obj) break; if (!setArrayObj(array, i, obj)) return NULL; } return array; } jobjectArray fromPySequence(jclass cls, PyObject **args, int length) { jobjectArray array; try { array = env->newObjectArray(cls, length); } catch (int e) { switch (e) { case _EXC_PYTHON: return NULL; case _EXC_JAVA: PyErr_SetJavaError(); return NULL; default: throw; } } for (int i = 0; i < length; i++) { PyObject *obj = args[i]; if (!obj) break; Py_INCREF(obj); if (!setArrayObj(array, i, obj)) return NULL; } return array; } void installType(PyTypeObject *type, PyObject *module, char *name, int isExtension) { if (PyType_Ready(type) == 0) { Py_INCREF(type); if (isExtension) { type->ob_type = &PY_TYPE(FinalizerClass); Py_INCREF(&PY_TYPE(FinalizerClass)); } PyModule_AddObject(module, name, (PyObject *) type); } } PyObject *wrapType(PyTypeObject *type, const jobject& obj) { static PyObject *wrapfn_ = PyString_FromString("wrapfn_"); PyObject *cobj = PyObject_GetAttr((PyObject *) type, wrapfn_); PyObject *(*wrapfn)(const jobject&); if (cobj == NULL) return NULL; wrapfn = (PyObject *(*)(const jobject &)) PyCObject_AsVoidPtr(cobj); Py_DECREF(cobj); return wrapfn(obj); } PyObject *unboxBoolean(const jobject& obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Boolean::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Boolean)); return NULL; } if (env->booleanValue(obj)) Py_RETURN_TRUE; Py_RETURN_FALSE; } Py_RETURN_NONE; } PyObject *unboxByte(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Byte::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Byte)); return NULL; } return PyInt_FromLong((long) env->byteValue(obj)); } Py_RETURN_NONE; } PyObject *unboxCharacter(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Character::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Character)); return NULL; } jchar c = env->charValue(obj); return PyUnicode_FromUnicode((Py_UNICODE *) &c, 1); } Py_RETURN_NONE; } PyObject *unboxDouble(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Double::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Double)); return NULL; } return PyFloat_FromDouble((double) env->doubleValue(obj)); } Py_RETURN_NONE; } PyObject *unboxFloat(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Float::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Float)); return NULL; } return PyFloat_FromDouble((double) env->floatValue(obj)); } Py_RETURN_NONE; } PyObject *unboxInteger(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Integer::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Integer)); return NULL; } return PyInt_FromLong((long) env->intValue(obj)); } Py_RETURN_NONE; } PyObject *unboxLong(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Long::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Long)); return NULL; } return PyLong_FromLongLong((PY_LONG_LONG) env->longValue(obj)); } Py_RETURN_NONE; } PyObject *unboxShort(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::Short::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(Short)); return NULL; } return PyInt_FromLong((long) env->shortValue(obj)); } Py_RETURN_NONE; } PyObject *unboxString(const jobject &obj) { if (obj != NULL) { if (!env->isInstanceOf(obj, java::lang::String::initializeClass)) { PyErr_SetObject(PyExc_TypeError, (PyObject *) &java::lang::PY_TYPE(String)); return NULL; } return env->fromJString((jstring) obj, 0); } Py_RETURN_NONE; } static int boxJObject(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { if (arg == Py_None) { if (obj != NULL) *obj = Object(NULL); } else if (PyObject_TypeCheck(arg, &PY_TYPE(Object))) { if (type != NULL && !is_instance_of(arg, type)) return -1; if (obj != NULL) *obj = ((t_Object *) arg)->object; } else if (PyObject_TypeCheck(arg, &PY_TYPE(FinalizerProxy))) { arg = ((t_fp *) arg)->object; if (PyObject_TypeCheck(arg, &PY_TYPE(Object))) { if (type != NULL && !is_instance_of(arg, type)) return -1; if (obj != NULL) *obj = ((t_Object *) arg)->object; } else return -1; } else return 1; return 0; } int boxBoolean(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (arg == Py_True) { if (obj != NULL) *obj = *Boolean::TRUE; } else if (arg == Py_False) { if (obj != NULL) *obj = *Boolean::FALSE; } else return -1; return 0; } int boxByte(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { int n = PyInt_AS_LONG(arg); jbyte b = (jbyte) n; if (b == n) { if (obj != NULL) *obj = Byte(b); } else return -1; } else if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); jbyte b = (jbyte) ln; if (b == ln) { if (obj != NULL) *obj = Byte(b); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); jbyte b = (jbyte) d; if (b == d) { if (obj != NULL) *obj = Byte(b); } else return -1; } else return -1; return 0; } int boxCharacter(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyString_Check(arg)) { char *c; Py_ssize_t len; if (PyString_AsStringAndSize(arg, &c, &len) < 0 || len != 1) return -1; if (obj != NULL) *obj = Character((jchar) c[0]); } else if (PyUnicode_Check(arg)) { Py_ssize_t len = PyUnicode_GetSize(arg); if (len != 1) return -1; if (obj != NULL) *obj = Character((jchar) PyUnicode_AsUnicode(arg)[0]); } else return -1; return 0; } int boxCharSequence(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyString_Check(arg) || PyUnicode_Check(arg)) { if (obj != NULL) { *obj = p2j(arg); if (PyErr_Occurred()) return -1; } } else return -1; return 0; } int boxDouble(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { if (obj != NULL) *obj = Double((jdouble) PyInt_AS_LONG(arg)); } else if (PyLong_Check(arg)) { if (obj != NULL) *obj = Double((jdouble) PyLong_AsLongLong(arg)); } else if (PyFloat_Check(arg)) { if (obj != NULL) *obj = Double(PyFloat_AS_DOUBLE(arg)); } else return -1; return 0; } int boxFloat(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { if (obj != NULL) *obj = Float((jfloat) PyInt_AS_LONG(arg)); } else if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); float f = (float) ln; if ((PY_LONG_LONG) f == ln) { if (obj != NULL) *obj = Float(f); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); float f = (float) d; if ((double) f == d) { if (obj != NULL) *obj = Float(f); } else return -1; } else return -1; return 0; } int boxInteger(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { if (obj != NULL) *obj = Integer((jint) PyInt_AS_LONG(arg)); } else if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); int n = (int) ln; if (n == ln) { if (obj != NULL) *obj = Integer(n); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); int n = (int) d; if ((double) n == d) { if (obj != NULL) *obj = Integer(n); } else return -1; } else return -1; return 0; } int boxLong(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { if (obj != NULL) *obj = Long((jlong) PyInt_AS_LONG(arg)); } else if (PyLong_Check(arg)) { if (obj != NULL) *obj = Long((jlong) PyLong_AsLongLong(arg)); } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); PY_LONG_LONG n = (PY_LONG_LONG) d; if ((double) n == d) { if (obj != NULL) *obj = Long((jlong) n); } else return -1; } else return -1; return 0; } int boxNumber(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { if (obj != NULL) *obj = Integer((jint) PyInt_AS_LONG(arg)); } else if (PyLong_Check(arg)) { if (obj != NULL) *obj = Long((jlong) PyLong_AsLongLong(arg)); } else if (PyFloat_Check(arg)) { if (obj != NULL) *obj = Double((jdouble) PyFloat_AS_DOUBLE(arg)); } else return -1; return 0; } int boxShort(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyInt_Check(arg)) { int n = (int) PyInt_AS_LONG(arg); short sn = (short) n; if (sn == n) { if (obj != NULL) *obj = Short((jshort) sn); } else return -1; } else if (PyLong_Check(arg)) { PY_LONG_LONG ln = PyLong_AsLongLong(arg); short sn = (short) ln; if (sn == ln) { if (obj != NULL) *obj = Short((jshort) sn); } else return -1; } else if (PyFloat_Check(arg)) { double d = PyFloat_AS_DOUBLE(arg); short sn = (short) (int) d; if ((double) sn == d) { if (obj != NULL) *obj = Short((jshort) sn); } else return -1; } else return -1; return 0; } int boxString(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (PyString_Check(arg) || PyUnicode_Check(arg)) { if (obj != NULL) { *obj = p2j(arg); if (PyErr_Occurred()) return -1; } } else return -1; return 0; } int boxObject(PyTypeObject *type, PyObject *arg, java::lang::Object *obj) { int result = boxJObject(type, arg, obj); if (result <= 0) return result; if (obj != NULL) { if (PyString_Check(arg) || PyUnicode_Check(arg)) { *obj = p2j(arg); if (PyErr_Occurred()) return -1; } else if (arg == Py_True) *obj = *Boolean::TRUE; else if (arg == Py_False) *obj = *Boolean::FALSE; else if (PyInt_Check(arg)) { long ln = PyInt_AS_LONG(arg); int n = (int) ln; if (ln != (long) n) *obj = Long((jlong) ln); else *obj = Integer((jint) n); } else if (PyLong_Check(arg)) *obj = Long((jlong) PyLong_AsLongLong(arg)); else if (PyFloat_Check(arg)) *obj = Double((jdouble) PyFloat_AS_DOUBLE(arg)); else return -1; } else if (!(PyString_Check(arg) || PyUnicode_Check(arg) || arg == Py_True || arg == Py_False || PyInt_Check(arg) || PyLong_Check(arg) || PyFloat_Check(arg))) return -1; return 0; } #ifdef _java_generics PyObject *typeParameters(PyTypeObject *types[], size_t size) { size_t count = size / sizeof(PyTypeObject *); PyObject *tuple = PyTuple_New(count); for (size_t i = 0; i < count; i++) { PyObject *type = (PyObject *) types[i]; if (type == NULL) type = Py_None; PyTuple_SET_ITEM(tuple, i, type); Py_INCREF(type); } return tuple; } #endif JCC-3.6/jcc2/windows.py0000644000076500000000000000477213063017435015065 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, _winreg class WindowsRegistry(object): def __init__(self): self.handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) def get(self, key, name): handle = None try: handle = _winreg.OpenKey(self.handle, key) return _winreg.QueryValueEx(handle, name)[0] finally: if handle is not None: handle.Close() def close(self): self.handle.Close() def get_jvm_dll_directory(client_or_server="client"): jre_key = r"SOFTWARE\JavaSoft\Java Runtime Environment" jdk_key = r"SOFTWARE\JavaSoft\Java Development Kit" current_key = r"%s\%s" registry = None try: registry = WindowsRegistry() try: # try JRE version = registry.get(jre_key, "CurrentVersion") path = registry.get(current_key %(jre_key, version), "JavaHome") if not os.path.exists(path): path = None except: path = None if not path: try: # try JDK version = registry.get(jdk_key, "CurrentVersion") path = registry.get(current_key %(jdk_key, version), "JavaHome") if os.path.exists(path): path = os.path.abspath(os.path.join(path, "jre")) else: path = None except: path = None finally: if registry is not None: registry.close() if path: path = os.path.abspath(os.path.join(path, "bin", client_or_server)) if os.path.exists(os.path.join(path, "jvm.dll")): return path return None def add_jvm_dll_directory_to_path(): path = os.environ['Path'].split(os.pathsep) dll_path = get_jvm_dll_directory() if dll_path is not None: path.append(dll_path) os.environ['Path'] = os.pathsep.join(path) return True raise ValueError, "jvm.dll could not be found" JCC-3.6/jcc2/__main__.py0000644000076500000000000001253513063025027015103 0ustar vajdawheel00000000000000 import sys from jcc import cpp if len(sys.argv) == 1 or '--help' in sys.argv: help = ''' JCC - C++/Python Java Native Interface Code Generator Usage: python -m jcc [options] [actions] Input options: --jar JARFILE - make JCC wrap all public classes found in JARFILE, add it to the module's CLASSPATH and include it in the distribution --include JARFILE - include JARFILE in the distribution and add it to the module's CLASSPATH --import MODULE - link against the wrappers to classes shared with MODULE instead of generating duplicate and incompatible wrappers --exclude CLASS - explicitly don't wrap CLASS --package PACKAGE - add PACKAGE to the list of packages from which dependencies are automatically wrapped --classpath [PATH|JAR] - add [PATH|JAR] to CLASSPATH while generating wrappers --libpath [PATH] - add [PATH] to java.library.path while generating wrappers --module MODULE - include Python MODULE in the distribution --reserved SYMBOL - mark SYMBOL as a reserved word that will be mangled in the generated C++ code to avoid clashes with C/C++ reserved words or header file definitions --vmarg - add extra Java VM initialization parameter --maxheap - set the maximum Java heap size, as passing -Xmx* using --vmarg doesn't do anything --resources - include resource directory in distribution as package data Python wrapper generation options: --python NAME - generate wrappers for use from Python in a module called NAME --version VERSION - the generated module's version number --shared - generate a module that links against a shared library version of the JCC runtime so that multiple JCC-wrapped modules can be used within the same Python runtime --sequence CLASS METHODSIGNATURE - generate a pythonic sequence protocol wrapper for CLASS --mapping CLASS METHODSIGNATURE1 METHODSIGNATURE2 - generate a pythonic map protocol wrapper for CLASS --rename CLASS1=NAME1,CLASS2=NAME2,... - rename one or more Python wrapper classes to avoid name clashes due to the flattening of the Java package namespaces as mapped into Python --use_full_names - map the full Java package structure into Python modules, as an alternative to selectively renaming or excluding classes due to name conflicts --no-generics - disable support for Java generics If you're planning to use pythonic wrappers you should read the relevant documentation first: http://lucene.apache.org/pylucene/jcc/documentation/readme.html#python Output options: --debug - generate a module using the C++ compiler's debug options --output OUTPUTDIR - the wrapper will be generated in OUTPUTDIR, 'build' by default --files N - split the generated wrapper file into at least N files to workaround C++ compiler file size limitations --arch - Mac OS X only: filter the -arch parameters Python was configured with to build leaner binaries, faster --find-jvm-dll - Windows only: extract the directory containing jvm.dll from the registry and append it to the Path at runtime Actions: --build - generate the wrapper and compile it --compile - recompile the (previously generated) module --install - install the wrapper in the local site-packages --egg-info - ask distutils setup() to generate egg info, and don't compile the module (for pip install) Distribution actions: --use-distutils - use distutils even when setuptools is available --bdist - generate a binary distutils-based distribution or a setuptools-based .egg --wininst - create an installer application for Microsoft Windows Other distutils/setuptools options (there are passed right through): --compiler COMPILER - use COMPILER instead of the platform default --root ROOTDIR --install-dir INSTALLDIR --prefix PREFIX --home HOMEDIR --extra-setup-arg - pass an extra argument on setup.py command line (pip install uses --egg-base and --record params) ''' print help sys.exit(0) cpp.jcc(sys.argv) JCC-3.6/CHANGES0000644000076500000000000003424413502050600013155 0ustar vajdawheel00000000000000Version 3.5 -> 3.6 ------------------ - fixed bug PYLUCENE-47 (with help from Petrus Hyvönen) - fixed bug PYLUCENE-48 - removed overlap between int and byte types when parsing args (PYLUCENE-50) Version 3.4 -> 3.5 ------------------ - fixed bug PYLUCENE-46 Version 3.3 -> 3.4 ------------------ - added NAN to the list of reserved words Version 3.2 -> 3.3 ------------------ - fixed bug PYLUCENE-43 - fixed bug PYLUCENE-41 Version 3.1 -> 3.2 ------------------ - added missing 'const' breaking build with Python 3.7 (Aric Coady) - fixed bug with not skipping META-INF/ entries in .jar files Version 3.0 -> 3.1 ------------------ - fixed bug PYLUCENE-36 (Paulo Villegas) - reworked type construction to use PyType_FromSpecWithBases (Python 3) - added 'm' suffix to linux -lpython statement for shared jcc lib - fixed bug with using split instead of rpartition on path (Petrus Hyvönen) - fixed bug PYLUCENE-38 (Aric Coady) - fixed bug PYLUCENE-39 Version 2.23 -> 3.0 ------------------- - added support for Python 3 (3.3+) (with Rüdiger Meier and Thomas Koch) - python3: fixed bugs with surrogate pairs (now supported for the first time) Version 2.22 -> 2.23 -------------------- - extended ability to explicitely requesting wrappers to fields Version 2.21 -> 2.22 -------------------- - monkeypatched customize_compiler to fix darwin linker error due to -Wl,-x - added check that MACOSX_DEPLOYMENT_TARGET is set to at least 10.5 - replaced MACOSX_DEPLOYMENT_TARGET check -mmacosx-version-min=10.5 - shared mode now requires a modern setuptools (version >= 8) Version 2.20 -> 2.21 -------------------- - improved through-layer Python error handling (with Lee Skillen) Version 2.19 -> 2.20 -------------------- - added support for java varargs by reconstructing array from last parameters Version 2.18 -> 2.19 -------------------- - fixed bug with missing class parameters when fixed by declaration - improved runtime support for fixed class generic parameters - improved runtime support for fixed class array generic parameters Version 2.17 -> 2.18 -------------------- - fixed bug PYLUCENE-26 (Martin Anon) - added support for building with setuptools >= 1.1.6 Version 2.16 -> 2.17 -------------------- - added support for detecting and running with Oracle JDK 7 on Mac OS X - added skipping of synthetic methods Version 2.15 -> 2.16 -------------------- - improved parseArgs() to let nested arrays pass through - added 'min', 'max' and 'PREFIX' to reserved words list to placate Visual C++ Version 2.14 -> 2.15 -------------------- - improved JCC build on Linux by monkey patching setuptools (Caleb Burns) - fixed bug with wrapping arrays coming out of generic iterators - added support for wrapping non-public methods by listing them as class:method - fixed bug with wrapping wrong clone() method in python extensions classes Version 2.13 -> 2.14 -------------------- - fixed class initialization race bug PYLUCENE-17 (with Patrick J. McNerthney) - added support for initVM's vmargs to be a [list, of, args], PYLUCENE-19 - added support for using full Java class names in Python via --use_full_names - fixed bug PYLUCENE-20 (Roman Chyla) Version 2.12 -> 2.13 -------------------- - fixed bug with name collision between method and static field of same name - added --maxheap, --egg-info and --extra-setup-arg parameters (Chris Wilson) - added check for duplicate class names in generated Python module - updated setuptools patch logic to accomodate new 0.6.15 and up fork - fixed issues with with arrays as generics parameters (openjdk 7) - added support for auto-boxing primitive types when converting to object array - fixed bug with setting a string into an object array - fixed bug with decref'ing too early when converting a sequence to an array Version 2.11 -> 2.12 -------------------- - fixed slice operation bug on JArray (int vs Py_ssize_t on 64-bit systems) - fixed bug in argument parsing not detecting soon enough incorrect num args - fixed bug in JArray(type) function decref'ing type_name too soon Version 2.10 -> 2.11 -------------------- - improved recovery from toString() failure, displaying class name instead - non public classes listed on command line now wrapped (Lukasz Jancewicz) - fixed bug with generating wrappers for unimplemented interface methods - fixed bug with generating propMethods for void getters - fixed bug with missing code for returning arrays from iterators Version 2.9 -> 2.10 ------------------- - added javadoc for org.apache.jcc.PythonVM class (Bill Janssen) - fixed bug with Constructor.getGenericParameterTypes() losing first parameter Version 2.8 -> 2.9 ------------------ - fixed bug with excluding inner classes only (Christian Heimes) - fixed bug with Python gc in non-attached JVM thread (Christian Heimes) Version 2.7 -> 2.8 ------------------ - fixed bug with --module using relative paths (Roman Chyla) - made fully qualified C++ class names absolute - fixed bug with parameterized types not requiring classes found in parameters - fixed bug with missing space between >> of nested generics Version 2.6 -> 2.7 ------------------ - added 'IGNORE' to reserved word list - improved --exclude logic to also exclude inner classes of excluded classes - moved --find-jvm-dll logic to __init__.py to accomodate Python 2.7 - fixed bug with faulty Java version logic causing crashes with Java 1.5 - added logic for finding JavaVM.framework headers on Mac OS X (Bill Janssen) Version 2.5 -> 2.6 ------------------ - added freebsd7 settings to setup.py (Sujan Shakya) - added support for unix-specific --home distutils install parameter - added support for extracting JAVAHOME from Windows registry (Bill Janssen) - updated MANIFEST.in as sdist started creating incomplete source archives - improved support for building on Windows with mingw32 (Bill Janssen) - added support for --find-jvm-dll parameter (Bill Janssen) - fixed bug with not inheriting type parameters to inner parameterized classes - added support for of_() method to set instance type parameters - fixed bug with not heeding type parameter for --sequence get method - parameterized return values are now unboxed - improved auto-boxing of primitive type parameters - added support for auto-boxing CharSequence from python str and unicode - added support for auto-boxing Number from python int, long and float - added 'asm' to list of reserved words - added JCC_VERSION string to modules using JCC - added support for --resources - fixed bug with array Release calls using isCopy instead of 0 mode - added support for --import - added read-only env.classpath property - config.py now written only during build or when missing (Christian Heimes) - fixed bug with not enforcing Iterable for iterator method detection Version 2.4 -> 2.5 ------------------ - added env.jni_version for the JNI version as returned by JNI's GetVersion() - added env.java_version for java.lang.System.getProperty('java.version') - default value to initVM's classpath parameter now is importing module's - added support for Java generics - added 'string_' property to JArray('byte') instances to extract byte string - fixed bug with passing list of extension objects - reworked iterator and enumeration 'next' templates to shortcut C++ wrappers - fixed bug in code comparing setuptools versions when >= 0.6c10 - verified build against setuptools from distribute 0.6.6 - renamed patch.43 to differentiate setuptools versions Version 2.3 -> 2.4 ------------------ - added 'typeof' to reserved word list - added Java stacktrace to __str__() of JavaError, fixing half of PYLUCENE-1 - fixed local string ref leaks in JArray.get/toSequence (Aric Coady) - added --libpath parameter to specify -Djava.library.path - classes listed with --exclude are no longer loaded (except for dependencies) - added --vmarg to add Java VM initialization parameters (Christian Kofler) - added support for passing a directory to --module - byte values are now returned as signed numbers as opposed to one-char strs - added --arch command line flag to filter Mac OS X python config settings - cast_() and instance_() methods now generated on extension classes as well - fixed bug with reporting Python error that occurred in an extension class Version 2.2 -> 2.3 ------------------ - fixed Solaris compilation issue with using va_arg() with function pointers - added --reserved command line arg to extend list of words to mangle - fixed bug with initJCC not being run when Python VM embedded in JVM - added --wininst to enable use of bdist_wininst with distutils (Jonas Maurus) - added --help to describe command line options (Jonas Maurus) - added support for --rename to workaround python flattened namespace clashes - fixed bug with Enumeration/Iterator template function instantiation - removed -framework Python from darwin link flags in setup.py Version 2.1 -> 2.2 ------------------ - JCC now a subproject of the Apache PyLucene project - fixed bug where thread's JNIEnv was not set before calling findClass() - unhandled java exception now is printed out via ExceptionDescribe() - added cast to placate Solaris compiler error in JArray.cpp - JArray Python wrappers should return None when passed a null array - added JDK variable to setup.py to better parameterize build configuration - added support for proxying mapping and sequence protocols on FinalizerProxy - changed Type suffix to $$Type to avoid clashes with like-named Java classes - added 'bool' and 'operator' to list of reserved words - added support for packages and classes named with C++ reserved words - static methods shadowed by non-static methods of same name now '_' suffixed - added 'java.lang' to --package by default - added isCurrentThreadAttached() method to VMEnv - added MANIFEST.in to exclude generated jcc/config.py (Christian Heimes) - passing strings for byte[] or char[] is no longer supported, use JArray - failure to call initVM() now reported with error instead of crash - failure to find class now reported with error instead of crash - failure to call attachCurrentThread() now reported with error, not crash Version 2.0 -> 2.1 ------------------ - fixed bug with not checking missing module name when attempting build - increased jcc's java stack to 512k - added support for iPod/iPhone, with shared mode - added missing cast to jweak in call to DeleteWeakGlobalRef() - fixed local string ref leak in JArray (Aaron Lav) - fixed local ref leak if ref for object already exists in table (Aaron Lav) - fixed bug with error reporting from class methods (Aaron Lav) - fixed bug with reporting python errors with RuntimeException when not shared - removed bogus storage class from template specializations (Joseph Barillari) Version 1.9 -> 2.0 ------------------ - fixed bug with failed findClass() import - fixed bug http://bugzilla.osafoundation.org/show_bug.cgi?id=12127 - added -ljvm to linux2 and sunos5 LFLAGS - added support for using JCC in reverse (starting from Java VM) (shared only) - using PythonException for reporting Python errors (shared only) - inserted Apache 2.0 license copyright notices - fixed bug with declaring array parameters in extension methods - added support for --module to add individual python files to resulting egg - JCC in reverse functional on Mac OS X and Linux - fixed JCC in reverse threading issues - JCC in reverse usable with Tomcat - got python stacktrace into PythonException's message - added 'self' property to get wrapped python object from extension wrapper - added headless AWT workaround to JCC's own initVM() call - added DEBUG_CFLAGS to setup.py to improve debug build support - fixed uninitialized Class class bug (parseArgs) - added errorName field to PythonException - added support for excluding stack trace from PythonException - arrays are now wrapped by JArray() objects instead of expanded into lists - return by value in arrays now supported - added support for nested arrays via JArray().cast_() - included patch to setuptools to support shared mode on Linux Version 1.8 -> 1.9 ------------------ - fixed code generation for clone() broken by finalization proxy work - added 'union' to the list of reserved words - fixed castCheck() to work with finalization proxies - --compile no longer installs by default - fixed bug in __init__.cpp #include statements for package-less classes - fixed line ending bug on Windows - fixed multiple JCC-built extensions in same process problem - removed env argument from initVM() as it's redundant with the libjcc.dylib - reimplemented env->setClassPath() in terms of system URLClassLoader hack - added support for --include option - added 'NULL' to list of reserved words - added support for building shared libjcc library on Mac OS X and Linux - fixed bug with generating wrappers for abstract Enumeration implementations - added support for --install-dir and --use-distutils options - copy jcc runtime sources into extension source tree before compiling - added detection of invalid command line args - fixed double-free bug when passing in vmargs - added defines to enable building with MinGW (Bill Janssen) - added support for --bdist - added support for --compiler - fixed crasher on Windows with virtual JObject.weaken$() - fixed bug not checking return value from initVM() - fixed bug with findClass() not catching C++ exception when class not found - added missing code in parseArgs() to handle double[], float[] and long[] Version 1.7 -> 1.8 ------------------ - fixed bug using the wrong field modifiers for setter (Bill Janssen) - added missing calls for generating wrappers for ancestors of Exception - added missing call for generating wrappers for String - added note about --classpath to README Version 1.6 -> 1.7 ------------------ - fixed memory leak when calling inherited methods via callSuper() - added support for building on Solaris with Sun Studio C++ (Solaris 11) - fixed leak of local refs of jstring when converting to an array of String - automated finalization of extensions via proxy for breaking ref cycle - added Py_CLEAR and Py_VISIT macros for Python 2.3.5 compilation Earlier versions (changes included in PyLucene versions < 2.3) -------------------------------------------------------------- - see http://svn.osafoundation.org/pylucene/trunk/jcc/CHANGES JCC-3.6/java/0000755000076500000000000000000013536235634013117 5ustar vajdawheel00000000000000JCC-3.6/java/org/0000755000076500000000000000000013536235634013706 5ustar vajdawheel00000000000000JCC-3.6/java/org/apache/0000755000076500000000000000000013536235634015127 5ustar vajdawheel00000000000000JCC-3.6/java/org/apache/jcc/0000755000076500000000000000000013536235634015666 5ustar vajdawheel00000000000000JCC-3.6/java/org/apache/jcc/PythonVM.java0000644000076500000000000000717011603675254020261 0ustar vajdawheel00000000000000/* ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.apache.jcc; public class PythonVM { static protected PythonVM vm; static { System.loadLibrary("jcc"); } /** * Start the embedded Python interpreter. The specified * program name and args are set into the Python variable sys.argv. * This returns an instance of the Python VM; it may be called * multiple times, and will return the same VM instance each time. * * @param programName the name of the Python program, typically * /usr/bin/python. This is informational; the program is not * actually executed. * @param args additional arguments to be put into sys.argv. * @return a singleton instance of PythonVM */ static public PythonVM start(String programName, String[] args) { if (vm == null) { vm = new PythonVM(); vm.init(programName, args); } return vm; } /** * Start the embedded Python interpreter. The specified * program name is set into the Python variable sys.argv[0]. * This returns an instance of the Python VM; it may be called * multiple times, and will return the same VM instance each time. * * @param programName the name of the Python program, typically * /usr/bin/python. This is informational; the program is not * actually executed. * @return a singleton instance of PythonVM */ static public PythonVM start(String programName) { return start(programName, null); } /** * Obtain the PythonVM instance, or null if the Python VM * has not yet been started. * * @return a singleton instance of PythonVM, or null */ static public PythonVM get() { return vm; } protected PythonVM() { } protected native void init(String programName, String[] args); /** * Instantiate the specified Python class, and return the instance. * * @param moduleName the Python module the class is defined in * @param className the Python class to instantiate. * @return a handle on the Python instance. */ public native Object instantiate(String moduleName, String className) throws PythonException; /** * Bump the Python thread state counter. Every thread should * do this before calling into Python, to prevent the Python * thread state from being inadvertently collected (and causing loss * of thread-local variables) * * @return the Python thread state counter. A return value less * than zero signals an error. */ public native int acquireThreadState(); /** * Release the Python thread state counter. Every thread that has * called acquireThreadState() should call this before * terminating. * * @return the Python thread state counter. A return value less * than zero signals an error. */ public native int releaseThreadState(); } JCC-3.6/java/org/apache/jcc/PythonException.java0000644000076500000000000000316612357276474021706 0ustar vajdawheel00000000000000/* ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.apache.jcc; public class PythonException extends RuntimeException { public boolean withTrace = true; protected long py_error_state = 0L; public PythonException(String message) { super(message); saveErrorState(); } public void finalize() throws Throwable { pythonDecRef(); } public String getMessage(boolean trace) { if (py_error_state == 0L) return super.getMessage(); String message = getErrorMessage(); if (trace) return message + "\n" + getErrorTraceback(); return message; } public String getMessage() { return getMessage(withTrace); } public native void pythonDecRef(); public native String getErrorName(); public native String getErrorMessage(); public native String getErrorTraceback(); protected native void saveErrorState(); } JCC-3.6/MANIFEST.in0000644000076500000000000000060713063077466013741 0ustar vajdawheel00000000000000exclude jcc2/config.py exclude jcc3/config.py include jcc2/patches/patch.* include jcc3/patches/patch.* recursive-include jcc2 *.h recursive-include jcc3 *.h recursive-include _jcc2 *.h recursive-include _jcc3 *.h recursive-include java *.java recursive-include helpers2 *.py recursive-include helpers3 *.py include CHANGES include DESCRIPTION include INSTALL include LICENSE include NOTICE JCC-3.6/README0000644000076500000000000000035311205636403013045 0ustar vajdawheel00000000000000 If you obtained JCC with a PyLucene source archive, please see doc/jcc/documentation/readme.html If you obtained JCC from http://www.python.org/pypi, please see http://lucene.apache.org/pylucene/jcc/documentation/readme.html JCC-3.6/NOTICE0000644000076500000000000000020511131542523013062 0ustar vajdawheel00000000000000 Apache PyLucene (JCC) Copyright 2009 The Apache Software Foundation Copyright (c) 2007-2008 Open Source Applications Foundation JCC-3.6/setup.py0000644000076500000000000004110413502046546013703 0ustar vajdawheel00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, sys, platform, subprocess jcc_ver = '3.6' machine = platform.machine() using_python2 = sys.version_info < (3,) if not using_python2 and sys.version_info < (3, 3): raise RuntimeError(''' Python 3 is supported from version 3.3, you are running version %s.%s''' %(sys.version_info.major, sys.version_info.minor)) if machine.startswith("iPod") or machine.startswith("iPhone"): platform = 'ipod' elif sys.platform == "win32" and "--compiler=mingw32" in sys.argv: platform = 'mingw32' elif sys.platform.startswith('linux'): platform = 'linux' else: platform = sys.platform # Add or edit the entry corresponding to your system in the JDK, INCLUDES, # CFLAGS, DEBUG_CFLAGS, LFLAGS and JAVAC dictionaries below. # These entries are used to build JCC _and_ by JCC to drive compiling and # linking via distutils or setuptools the extensions it generated code for. # # The key for your system is determined by the platform variable defined # above. # # Instead of editing the entries below, you may also override these # dictionaries with JCC_JDK, JCC_INCLUDES, JCC_CFLAGS, JCC_DEBUG_CFLAGS, # JCC_LFLAGS and JCC_JAVAC environment variables using os.pathsep as value # separator. if platform in ("win32", "mingw32"): try: JAVAFRAMEWORKS = None if using_python2: from helpers2.windows import JAVAHOME else: from helpers3.windows import JAVAHOME except ImportError: JAVAHOME = None elif platform in ("darwin",): try: if using_python2: from helpers2.darwin import JAVAHOME, JAVAFRAMEWORKS else: from helpers3.darwin import JAVAHOME, JAVAFRAMEWORKS except ImportError: JAVAHOME = None JAVAFRAMEWORKS = None else: JAVAHOME = None JAVAFRAMEWORKS = None JDK = { 'darwin': JAVAHOME or JAVAFRAMEWORKS, 'ipod': '/usr/include/gcc', 'linux': '/usr/lib/jvm/java-8-oracle', 'sunos5': '/usr/jdk/instances/jdk1.6.0', 'win32': JAVAHOME, 'mingw32': JAVAHOME, 'freebsd7': '/usr/local/diablo-jdk1.6.0' } if 'JCC_JDK' in os.environ: JDK[platform] = os.environ['JCC_JDK'] if not JDK[platform]: raise RuntimeError(''' Can't determine where the Java JDK has been installed on this machine. Please set the environment variable JCC_JDK to that location before running setup.py. ''') elif not os.path.isdir(JDK[platform]): raise RuntimeError(''' Java JDK directory '%s' does not exist. Please set the environment variable JCC_JDK to the correct location before running setup.py. ''' %(JDK[platform])) INCLUDES = { 'darwin/frameworks': ['%(darwin)s/Headers' %(JDK)], 'darwin/home': ['%(darwin)s/include' %(JDK), '%(darwin)s/include/darwin' %(JDK)], 'ipod': ['%(ipod)s/darwin/default' %(JDK)], 'linux': ['%(linux)s/include' %(JDK), '%(linux)s/include/linux' %(JDK)], 'sunos5': ['%(sunos5)s/include' %(JDK), '%(sunos5)s/include/solaris' %(JDK)], 'win32': ['%(win32)s/include' %(JDK), '%(win32)s/include/win32' %(JDK)], 'mingw32': ['%(mingw32)s/include' %(JDK), '%(mingw32)s/include/win32' %(JDK)], 'freebsd7': ['%(freebsd7)s/include' %(JDK), '%(freebsd7)s/include/freebsd' %(JDK)], } CFLAGS = { 'darwin': ['-fno-strict-aliasing', '-Wno-write-strings', '-mmacosx-version-min=10.9', '-std=c++11', '-stdlib=libc++'], 'ipod': ['-Wno-write-strings'], 'linux': ['-fno-strict-aliasing', '-Wno-write-strings'], 'sunos5': ['-features=iddollar', '-erroff=badargtypel2w,wbadinitl,wvarhidemem'], 'win32': ["/EHsc", "/D_CRT_SECURE_NO_WARNINGS"], # MSVC 9 (2008) 'mingw32': ['-fno-strict-aliasing', '-Wno-write-strings'], 'freebsd7': ['-fno-strict-aliasing', '-Wno-write-strings'], } # added to CFLAGS when JCC is invoked with --debug DEBUG_CFLAGS = { 'darwin': ['-O0', '-g', '-DDEBUG'], 'ipod': ['-O0', '-g', '-DDEBUG'], 'linux': ['-O0', '-g', '-DDEBUG'], 'sunos5': ['-DDEBUG'], 'win32': ['/Od', '/DDEBUG'], 'mingw32': ['-O0', '-g', '-DDEBUG'], 'freebsd7': ['-O0', '-g', '-DDEBUG'], } LFLAGS = { 'darwin/frameworks': ['-framework', 'JavaVM', '-mmacosx-version-min=10.9'], 'darwin/home': ['-L%(darwin)s/jre/lib' %(JDK), '-ljava', '-L%(darwin)s/jre/lib/server' %(JDK), '-ljvm', '-Wl,-rpath', '-Wl,%(darwin)s/jre/lib' %(JDK), '-Wl,-rpath', '-Wl,%(darwin)s/jre/lib/server' %(JDK), '-mmacosx-version-min=10.9'], 'ipod': ['-ljvm', '-lpython%s.%s' %(sys.version_info[0:2]), '-L/usr/lib/gcc/arm-apple-darwin9/4.0.1'], 'linux/i386': ['-L%(linux)s/jre/lib/i386' %(JDK), '-ljava', '-L%(linux)s/jre/lib/i386/client' %(JDK), '-ljvm', '-Wl,-rpath=%(linux)s/jre/lib/i386:%(linux)s/jre/lib/i386/client' %(JDK)], 'linux/i686': ['-L%(linux)s/jre/lib/i386' %(JDK), '-ljava', '-L%(linux)s/jre/lib/i386/client' %(JDK), '-ljvm', '-Wl,-rpath=%(linux)s/jre/lib/i386:%(linux)s/jre/lib/i386/client' %(JDK)], 'linux/x86_64': ['-L%(linux)s/jre/lib/amd64' %(JDK), '-ljava', '-L%(linux)s/jre/lib/amd64/server' %(JDK), '-ljvm', '-Wl,-rpath=%(linux)s/jre/lib/amd64:%(linux)s/jre/lib/amd64/server' %(JDK)], 'sunos5': ['-L%(sunos5)s/jre/lib/i386' %(JDK), '-ljava', '-L%(sunos5)s/jre/lib/i386/client' %(JDK), '-ljvm', '-R%(sunos5)s/jre/lib/i386:%(sunos5)s/jre/lib/i386/client' %(JDK)], 'win32': ['/DLL', '/LIBPATH:%(win32)s/lib' %(JDK), 'Ws2_32.lib', 'jvm.lib'], 'mingw32': ['-L%(mingw32)s/lib' %(JDK), '-ljvm'], 'freebsd7': ['-L%(freebsd7)s/jre/lib/i386' %(JDK), '-ljava', '-lverify', '-L%(freebsd7)s/jre/lib/i386/client' %(JDK), '-ljvm', '-Wl,-rpath=%(freebsd7)s/jre/lib/i386:%(freebsd7)s/jre/lib/i386/client' %(JDK)], } IMPLIB_LFLAGS = { 'win32': ["/IMPLIB:%s"], 'mingw32': ["-Wl,--out-implib,%s"] } if platform == 'linux': LFLAGS['linux'] = LFLAGS['linux/%s' %(machine)] elif platform == 'darwin': if JAVAHOME is not None: INCLUDES['darwin'] = INCLUDES['darwin/home'] LFLAGS['darwin'] = LFLAGS['darwin/home'] elif JAVAFRAMEWORKS is not None: INCLUDES['darwin'] = INCLUDES['darwin/frameworks'] LFLAGS['darwin'] = LFLAGS['darwin/frameworks'] JAVAC = { 'darwin': ['javac', '-source', '1.5', '-target', '1.5'], 'ipod': ['jikes', '-cp', '/usr/share/classpath/glibj.zip'], 'linux': ['javac'], 'sunos5': ['javac'], 'win32': ['%(win32)s/bin/javac.exe' %(JDK)], 'mingw32': ['%(mingw32)s/bin/javac.exe' %(JDK)], 'freebsd7': ['javac'], } JAVADOC = { 'darwin': ['javadoc'], 'ipod': [], 'linux': ['javadoc'], 'sunos5': ['javadoc'], 'win32': ['%(win32)s/bin/javadoc.exe' %(JDK)], 'mingw32': ['%(mingw32)s/bin/javadoc.exe' %(JDK)], 'freebsd7': ['javadoc'], } try: if 'USE_DISTUTILS' in os.environ: raise ImportError from setuptools import setup, Extension from pkg_resources import require with_setuptools = require('setuptools')[0].parsed_version try: from pkg_resources import SetuptoolsVersion with_modern_setuptools = True except ImportError: try: from pkg_resources.extern.packaging.version import Version with_modern_setuptools = True except ImportError: with_modern_setuptools = False enable_shared = False if with_modern_setuptools and 'NO_SHARED' not in os.environ: if platform in ('ipod', 'win32'): enable_shared = True elif platform == 'darwin': enable_shared = True elif platform == 'linux': if using_python2: from helpers2.linux import patch_setuptools else: from helpers3.linux import patch_setuptools enable_shared = patch_setuptools(with_setuptools) elif platform == 'mingw32': enable_shared = True # need to monkeypatch the CygwinCCompiler class to generate # jcc.lib in the correct place if using_python2: from helpers2.mingw32 import JCCMinGW32CCompiler else: from helpers3.mingw32 import JCCMinGW32CCompiler import distutils.cygwinccompiler distutils.cygwinccompiler.Mingw32CCompiler = JCCMinGW32CCompiler if enable_shared: from setuptools.extension import Library except ImportError: if sys.version_info < (2, 4): raise ImportError('setuptools is required when using Python 2.3') else: from distutils.core import setup, Extension with_setuptools = None enable_shared = False def main(debug): if using_python2: py_version_suffix = '2' else: py_version_suffix = '3' _jcc_argsep = os.environ.get('JCC_ARGSEP', os.pathsep) if 'JCC_INCLUDES' in os.environ: _includes = os.environ['JCC_INCLUDES'].split(_jcc_argsep) else: _includes = INCLUDES[platform] if 'JCC_CFLAGS' in os.environ: _cflags = os.environ['JCC_CFLAGS'].split(_jcc_argsep) else: _cflags = CFLAGS[platform] if 'JCC_DEBUG_CFLAGS' in os.environ: _debug_cflags = os.environ['JCC_DEBUG_CFLAGS'].split(_jcc_argsep) else: _debug_cflags = DEBUG_CFLAGS[platform] if 'JCC_LFLAGS' in os.environ: _lflags = os.environ['JCC_LFLAGS'].split(_jcc_argsep) else: _lflags = LFLAGS[platform] if 'JCC_IMPLIB_LFLAGS' in os.environ: _implib_lflags = os.environ['JCC_IMPLIB_LFLAGS'].split(_jcc_argsep) else: _implib_lflags = IMPLIB_LFLAGS.get(platform, []) if 'JCC_JAVAC' in os.environ: _javac = os.environ['JCC_JAVAC'].split(_jcc_argsep) else: _javac = JAVAC[platform] if 'JCC_JAVADOC' in os.environ: _javadoc = os.environ['JCC_JAVADOC'].split(_jcc_argsep) else: _javadoc = JAVADOC[platform] if using_python2: from helpers2.build import jcc_build_py else: from helpers3.build import jcc_build_py jcc_build_py.config_file = \ os.path.join(os.path.dirname(os.path.abspath(__file__)), 'jcc%s' %(py_version_suffix), 'config.py') jcc_build_py.config_text = \ '\n'.join(['', 'INCLUDES=%s' %(_includes), 'CFLAGS=%s' %(_cflags), 'DEBUG_CFLAGS=%s' %(_debug_cflags), 'LFLAGS=%s' %(_lflags), 'IMPLIB_LFLAGS=%s' %(_implib_lflags), 'SHARED=%s' %(enable_shared), 'VERSION="%s"' %(jcc_ver), '']) extensions = [] boot = '_jcc%s' %(py_version_suffix) cflags = ['-DPYTHON'] + _cflags if debug: cflags += _debug_cflags includes = _includes + [boot, 'jcc%s/sources' %(py_version_suffix)] lflags = _lflags if not debug: if platform == 'win32': pass elif platform == 'sunos5': lflags += ['-Wl,-s'] else: lflags += ['-Wl,-S'] sources = ['jcc%s/sources/jcc.cpp' %(py_version_suffix), 'jcc%s/sources/JCCEnv.cpp' %(py_version_suffix), 'jcc%s/sources/JObject.cpp' %(py_version_suffix), 'jcc%s/sources/JArray.cpp' %(py_version_suffix), 'jcc%s/sources/functions.cpp' %(py_version_suffix), 'jcc%s/sources/types.cpp' %(py_version_suffix)] for path, dirs, names in os.walk(boot): for name in names: if name.endswith('.cpp'): sources.append(os.path.join(path, name)) package_data = ['sources/*.cpp', 'sources/*.h', 'patches/patch.*'] if with_setuptools and enable_shared: from subprocess import Popen, PIPE kwds = { "extra_compile_args": cflags, "include_dirs": includes, "define_macros": [('_jcc_lib', None), ('JCC_VER', '"%s"' %(jcc_ver))], "sources": sources[0:2] } if platform in ('darwin', 'ipod'): kwds["extra_link_args"] = \ lflags + ['-install_name', '@rpath/libjcc%s.dylib' %(py_version_suffix), '-current_version', jcc_ver, '-compatibility_version', jcc_ver] elif platform == 'linux': kwds["extra_link_args"] = \ lflags + ['-lpython%s.%s%s' %( sys.version_info[0:2] + ('' if using_python2 else 'm',))] kwds["force_shared"] = True # requires jcc/patches/patch.43 elif platform in IMPLIB_LFLAGS: jcclib = 'jcc%s%s.lib' %(py_version_suffix, debug and '_d' or '') implib_flags = ' '.join(IMPLIB_LFLAGS[platform]) kwds["extra_link_args"] = \ lflags + [implib_flags %(os.path.join('jcc%s' %(py_version_suffix), jcclib))] package_data.append(jcclib) else: kwds["extra_link_args"] = lflags extensions.append(Library('jcc%s' %(py_version_suffix), **kwds)) args = _javac[:] args.extend(('-d', 'jcc%s/classes' %(py_version_suffix))) args.append('java/org/apache/jcc/PythonVM.java') args.append('java/org/apache/jcc/PythonException.java') if not os.path.exists('jcc%s/classes' %(py_version_suffix)): os.makedirs('jcc%s/classes' %(py_version_suffix)) try: process = Popen(args, stderr=PIPE) except: raise sys.exc_info()[0]("%s: %s" %(sys.exc_info()[1], args)) process.wait() if process.returncode != 0: raise OSError(process.stderr.read()) package_data.append('classes/org/apache/jcc/PythonVM.class') package_data.append('classes/org/apache/jcc/PythonException.class') args = _javadoc[:] args.extend(('-d', 'javadoc', '-sourcepath', 'java', 'org.apache.jcc')) try: process = Popen(args, stderr=PIPE) except: raise sys.exc_info()[0]("%s: %s" %(sys.exc_info()[1], args)) process.wait() if process.returncode != 0: raise OSError(process.stderr.read()) extensions.append(Extension('jcc._jcc%s' %(py_version_suffix), extra_compile_args=cflags, extra_link_args=lflags, include_dirs=includes, define_macros=[('_java_generics', None), ('JCC_VER', '"%s"' %(jcc_ver))], sources=sources)) args = { 'name': 'JCC', 'version': jcc_ver, 'description': 'a C++ code generator for calling Java from C++/Python', 'long_description': open('DESCRIPTION').read(), 'author': 'Andi Vajda', 'author_email': 'vajda@apache.org', 'classifiers': ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: C++', 'Programming Language :: Java', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Libraries :: Java Libraries'], 'packages': ['jcc'], 'package_dir': {'jcc': 'jcc%s' %(py_version_suffix)}, 'package_data': {'jcc': package_data}, 'ext_modules': extensions, "cmdclass": {"build_py": jcc_build_py}, } if with_setuptools: args['zip_safe'] = False setup(**args) if __name__ == "__main__": main('--debug' in sys.argv) JCC-3.6/DESCRIPTION0000644000076500000000000000321513063332670013676 0ustar vajdawheel00000000000000 For changes since earlier releases, see: http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc/CHANGES JCC is a C++ code generator for producing the code necessary to call into Java classes from CPython via Java's Native Invocation Interface (JNI). JCC generates C++ wrapper classes that hide all the gory details of JNI access as well Java memory and object reference management. JCC generates CPython types that make these C++ classes accessible from a Python interpreter. JCC attempts to make these Python types pythonic by detecting iterators and property accessors. Iterators and mappings may also be declared to JCC. JCC has been built on Python 2.3 to 2.7, on Python 3.6, and has been used with various Java Runtime Environments such as Sun Java 1.5 and 1.6, Apple's Java 1.5 and 1.6 on Mac OS X, open source Java OpenJDK 1.7 builds as well as Oracle Java 1.7 and 1.8. JCC is supported on Mac OS X, Linux, Solaris and Windows. JCC is written in C++ and Python. It uses Java's reflection API to do its job and needs a Java Runtime Environment to be present to operate. JCC is built with distutils or setuptools:: python setup.py build sudo python setup.py install Setuptools is required to build JCC on Python 2.3. JCC's setup.py file needs to be edited before building JCC to specify the location of the Java Runtime Environment's header files and libraries. The svn sources for JCC are available at: http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc/ For more information about JCC see: http://lucene.apache.org/pylucene/jcc/index.html JCC comes with an Apache 2.0 copyright license: http://www.apache.org/licenses/LICENSE-2.0 JCC-3.6/setup.cfg0000644000076500000000000000007313536235634014017 0ustar vajdawheel00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0