Cython has moved to github.

cython

view bin/cython_freeze @ 2829:8bff3332e34f

Added tag 0.12.1 for changeset e90c522631ae
author Robert Bradshaw <robertwb@math.washington.edu>
date Tue Feb 02 02:10:32 2010 -0800 (2 years ago)
parents b4e76fec149f
children
line source
1 #!/usr/bin/env python
2 """
3 Create a C file for embedding one or more Cython source files.
4 Requires Cython 0.11.2 (or perhaps newer).
6 See Demos/freeze/README.txt for more details.
7 """
9 import optparse
11 usage= '%prog [-o outfile] [-p] module [module ...]'
12 description = 'Create a C file for embedding Cython modules.'
13 p = optparse.OptionParser(usage=usage, description=description)
14 p.add_option('-o', '--output', metavar='FILE',
15 help='write output to FILE instead of standard output')
16 p.add_option('-p', '--pymain', action='store_true', default=False,
17 help='do not automatically run the first module as __main__')
19 options, args = p.parse_args()
21 if len(args) < 1:
22 p.print_help()
23 p.exit(1)
25 if options.output:
26 import sys
27 old_stdout = sys.stdout
28 sys.stdout = open(options.output, 'w')
30 def format_modname(name):
31 if name.endswith('.pyx'):
32 name = name[:-4]
33 elif name.endswith('.py'):
34 name = name[:-3]
35 return name.replace('.','_')
37 modules = [format_modname(x) for x in args]
39 print """\
40 #include <Python.h>
41 #include <locale.h>
42 #include <stdio.h>
43 #include <stdlib.h>
45 #ifdef __FreeBSD__
46 #include <floatingpoint.h>
47 #endif
49 #if PY_MAJOR_VERSION < 3
50 # define MODINIT(name) init ## name
51 #else
52 # define MODINIT(name) PyInit_ ## name
53 #endif
54 """
56 for name in modules:
57 print "PyMODINIT_FUNC MODINIT(%s) (void);" % name
59 print """
60 static struct _inittab inittab[] = {"""
62 for name in modules:
63 print ' {"%(name)s", MODINIT(%(name)s)},' % {'name' : name}
65 print """ {NULL, NULL}
66 };
67 """,
69 if not options.pymain:
70 print "\nextern int __pyx_module_is_main_%s;" % modules[0]
72 print """
73 #if PY_MAJOR_VERSION < 3
74 int main(int argc, char** argv) {
75 #elif defined(WIN32) || defined(MS_WINDOWS)
76 int wmain(int argc, wchar_t **argv) {
77 #else
78 static int python_main(int argc, wchar_t **argv) {
79 #endif
80 """,
81 if not options.pymain:
82 print """\
83 PyObject *m = NULL;
84 int r = 0;
85 """,
86 print """\
87 /* 754 requires that FP exceptions run in "no stop" mode by default,
88 * and until C vendors implement C99's ways to control FP exceptions,
89 * Python requires non-stop mode. Alas, some platforms enable FP
90 * exceptions by default. Here we disable them.
91 */
92 #ifdef __FreeBSD__
93 fp_except_t m;
95 m = fpgetmask();
96 fpsetmask(m & ~FP_X_OFL);
97 #endif
98 if (PyImport_ExtendInittab(inittab)) {
99 fprintf(stderr, "No memory\\n");
100 exit(1);
101 }
102 """,
103 if options.pymain:
104 print """\
105 return Py_Main(argc, argv);
106 }
107 """
108 else:
109 print """\
110 Py_SetProgramName(argv[0]);
111 Py_Initialize();
112 PySys_SetArgv(argc, argv);
113 __pyx_module_is_main_%(main)s = 1;
114 m = PyImport_ImportModule(inittab[0].name);
115 if (!m) {
116 r = 1;
117 PyErr_Print(); /* This exits with the right code if SystemExit. */
118 #if PY_MAJOR_VERSION < 3
119 if (Py_FlushLine())
120 PyErr_Clear();
121 #endif
122 }
123 Py_XDECREF(m);
124 Py_Finalize();
125 return r;
126 }
127 """ % {'main' : modules[0]},
129 print r"""
130 #if PY_MAJOR_VERSION >= 3 && !defined(WIN32) && !defined(MS_WINDOWS)
131 static wchar_t*
132 char2wchar(char* arg)
133 {
134 wchar_t *res;
135 #ifdef HAVE_BROKEN_MBSTOWCS
136 /* Some platforms have a broken implementation of
137 * mbstowcs which does not count the characters that
138 * would result from conversion. Use an upper bound.
139 */
140 size_t argsize = strlen(arg);
141 #else
142 size_t argsize = mbstowcs(NULL, arg, 0);
143 #endif
144 size_t count;
145 unsigned char *in;
146 wchar_t *out;
147 #ifdef HAVE_MBRTOWC
148 mbstate_t mbs;
149 #endif
150 if (argsize != (size_t)-1) {
151 res = (wchar_t *)malloc((argsize+1)*sizeof(wchar_t));
152 if (!res)
153 goto oom;
154 count = mbstowcs(res, arg, argsize+1);
155 if (count != (size_t)-1) {
156 wchar_t *tmp;
157 /* Only use the result if it contains no
158 surrogate characters. */
159 for (tmp = res; *tmp != 0 &&
160 (*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
161 ;
162 if (*tmp == 0)
163 return res;
164 }
165 free(res);
166 }
167 /* Conversion failed. Fall back to escaping with surrogateescape. */
168 #ifdef HAVE_MBRTOWC
169 /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
171 /* Overallocate; as multi-byte characters are in the argument, the
172 actual output could use less memory. */
173 argsize = strlen(arg) + 1;
174 res = malloc(argsize*sizeof(wchar_t));
175 if (!res) goto oom;
176 in = (unsigned char*)arg;
177 out = res;
178 memset(&mbs, 0, sizeof mbs);
179 while (argsize) {
180 size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
181 if (converted == 0)
182 /* Reached end of string; null char stored. */
183 break;
184 if (converted == (size_t)-2) {
185 /* Incomplete character. This should never happen,
186 since we provide everything that we have -
187 unless there is a bug in the C library, or I
188 misunderstood how mbrtowc works. */
189 fprintf(stderr, "unexpected mbrtowc result -2\n");
190 return NULL;
191 }
192 if (converted == (size_t)-1) {
193 /* Conversion error. Escape as UTF-8b, and start over
194 in the initial shift state. */
195 *out++ = 0xdc00 + *in++;
196 argsize--;
197 memset(&mbs, 0, sizeof mbs);
198 continue;
199 }
200 if (*out >= 0xd800 && *out <= 0xdfff) {
201 /* Surrogate character. Escape the original
202 byte sequence with surrogateescape. */
203 argsize -= converted;
204 while (converted--)
205 *out++ = 0xdc00 + *in++;
206 continue;
207 }
208 /* successfully converted some bytes */
209 in += converted;
210 argsize -= converted;
211 out++;
212 }
213 #else
214 /* Cannot use C locale for escaping; manually escape as if charset
215 is ASCII (i.e. escape all bytes > 128. This will still roundtrip
216 correctly in the locale's charset, which must be an ASCII superset. */
217 res = malloc((strlen(arg)+1)*sizeof(wchar_t));
218 if (!res) goto oom;
219 in = (unsigned char*)arg;
220 out = res;
221 while(*in)
222 if(*in < 128)
223 *out++ = *in++;
224 else
225 *out++ = 0xdc00 + *in++;
226 *out = 0;
227 #endif
228 return res;
229 oom:
230 fprintf(stderr, "out of memory\n");
231 return NULL;
232 }
234 int
235 main(int argc, char **argv)
236 {
237 wchar_t **argv_copy = (wchar_t **)malloc(sizeof(wchar_t*)*argc);
238 /* We need a second copies, as Python might modify the first one. */
239 wchar_t **argv_copy2 = (wchar_t **)malloc(sizeof(wchar_t*)*argc);
240 int i, res;
241 char *oldloc;
242 if (!argv_copy || !argv_copy2) {
243 fprintf(stderr, "out of memory\n");
244 return 1;
245 }
246 oldloc = strdup(setlocale(LC_ALL, NULL));
247 setlocale(LC_ALL, "");
248 for (i = 0; i < argc; i++) {
249 argv_copy2[i] = argv_copy[i] = char2wchar(argv[i]);
250 if (!argv_copy[i])
251 return 1;
252 }
253 setlocale(LC_ALL, oldloc);
254 free(oldloc);
255 res = python_main(argc, argv_copy);
256 for (i = 0; i < argc; i++) {
257 free(argv_copy2[i]);
258 }
259 free(argv_copy);
260 free(argv_copy2);
261 return res;
262 }
263 #endif"""