This commit was manufactured by cvs2svn to create tag 'release101'.
[python/dscho.git] / Python / pythonrun.c
blob707959f44ce176069bfe5e086e40fe50be9537e9
1 /***********************************************************
2 Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
3 Amsterdam, The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI not be used in advertising or publicity pertaining to
13 distribution of the software without specific, written prior permission.
15 STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
16 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17 FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
18 FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21 OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 ******************************************************************/
25 /* Python interpreter top-level routines, including init/exit */
27 #include "allobjects.h"
29 #include "grammar.h"
30 #include "node.h"
31 #include "parsetok.h"
32 #include "graminit.h"
33 #include "errcode.h"
34 #include "sysmodule.h"
35 #include "compile.h"
36 #include "eval.h"
37 #include "ceval.h"
38 #include "pythonrun.h"
39 #include "import.h"
41 #ifdef HAVE_SIGNAL_H
42 #include <signal.h>
43 #endif
45 extern char *getpythonpath();
47 extern grammar gram; /* From graminit.c */
49 /* Forward */
50 static object *run_err_node PROTO((node *n, char *filename,
51 object *globals, object *locals));
52 static object *run_node PROTO((node *n, char *filename,
53 object *globals, object *locals));
54 static void err_input PROTO((perrdetail *));
55 static void initsigs PROTO((void));
57 int debugging; /* Needed by parser.c */
58 int verbose; /* Needed by import.c */
60 /* Initialize all */
62 void
63 initall()
65 static int inited;
67 if (inited)
68 return;
69 inited = 1;
71 initimport();
73 /* Modules '__builtin__' and 'sys' are initialized here,
74 they are needed by random bits of the interpreter.
75 All other modules are optional and are initialized
76 when they are first imported. */
78 initbuiltin(); /* Also initializes builtin exceptions */
79 initsys();
81 setpythonpath(getpythonpath());
83 initsigs(); /* Signal handling stuff, including initintr() */
86 /* Parse input from a file and execute it */
88 int
89 run(fp, filename)
90 FILE *fp;
91 char *filename;
93 if (filename == NULL)
94 filename = "???";
95 if (isatty((int)fileno(fp)))
96 return run_tty_loop(fp, filename);
97 else
98 return run_script(fp, filename);
102 run_tty_loop(fp, filename)
103 FILE *fp;
104 char *filename;
106 object *v;
107 int ret;
108 v = sysget("ps1");
109 if (v == NULL) {
110 sysset("ps1", v = newstringobject(">>> "));
111 XDECREF(v);
113 v = sysget("ps2");
114 if (v == NULL) {
115 sysset("ps2", v = newstringobject("... "));
116 XDECREF(v);
118 for (;;) {
119 ret = run_tty_1(fp, filename);
120 #ifdef REF_DEBUG
121 fprintf(stderr, "[%ld refs]\n", ref_total);
122 #endif
123 if (ret == E_EOF)
124 return 0;
126 if (ret == E_NOMEM)
127 return -1;
133 run_tty_1(fp, filename)
134 FILE *fp;
135 char *filename;
137 object *m, *d, *v, *w;
138 node *n;
139 perrdetail err;
140 char *ps1, *ps2;
141 int ret;
142 v = sysget("ps1");
143 w = sysget("ps2");
144 if (v != NULL && is_stringobject(v)) {
145 INCREF(v);
146 ps1 = getstringvalue(v);
148 else {
149 v = NULL;
150 ps1 = "";
152 if (w != NULL && is_stringobject(w)) {
153 INCREF(w);
154 ps2 = getstringvalue(w);
156 else {
157 w = NULL;
158 ps2 = "";
160 BGN_SAVE
161 n = parsefile(fp, filename, &gram, single_input, ps1, ps2, &err);
162 END_SAVE
163 XDECREF(v);
164 XDECREF(w);
165 if (n == NULL) {
166 if (err.error == E_EOF) {
167 if (err.text)
168 free(err.text);
169 return E_EOF;
171 err_input(&err);
172 print_error();
173 return ret;
175 m = add_module("__main__");
176 if (m == NULL)
177 return -1;
178 d = getmoduledict(m);
179 v = run_node(n, filename, d, d);
180 flushline();
181 if (v == NULL) {
182 print_error();
183 return -1;
185 DECREF(v);
186 return 0;
190 run_script(fp, filename)
191 FILE *fp;
192 char *filename;
194 object *m, *d, *v;
195 m = add_module("__main__");
196 if (m == NULL)
197 return -1;
198 d = getmoduledict(m);
199 v = run_file(fp, filename, file_input, d, d);
200 flushline();
201 if (v == NULL) {
202 print_error();
203 return -1;
205 DECREF(v);
206 return 0;
210 run_command(command)
211 char *command;
213 object *m, *d, *v;
214 m = add_module("__main__");
215 if (m == NULL)
216 return -1;
217 d = getmoduledict(m);
218 v = run_string(command, file_input, d, d);
219 flushline();
220 if (v == NULL) {
221 print_error();
222 return -1;
224 DECREF(v);
225 return 0;
228 void
229 print_error()
231 object *exception, *v, *f;
232 err_get(&exception, &v);
233 if (exception == NULL) {
234 fprintf(stderr, "print_error called but no exception\n");
235 abort();
237 if (exception == SystemExit) {
238 if (v == NULL || v == None)
239 goaway(0);
240 if (is_intobject(v))
241 goaway((int)getintvalue(v));
242 else {
243 /* OK to use real stderr here */
244 printobject(v, stderr, PRINT_RAW);
245 fprintf(stderr, "\n");
246 goaway(1);
249 sysset("last_type", exception);
250 sysset("last_value", v);
251 f = sysget("stderr");
252 if (f == NULL)
253 fprintf(stderr, "lost sys.stderr\n");
254 else {
255 printtraceback(f);
256 if (exception == SyntaxError) {
257 object *message;
258 char *filename, *text;
259 int lineno, offset;
260 if (!getargs(v, "(O(ziiz))", &message,
261 &filename, &lineno, &offset, &text))
262 err_clear();
263 else {
264 char buf[10];
265 writestring(" File \"", f);
266 if (filename == NULL)
267 writestring("<string>", f);
268 else
269 writestring(filename, f);
270 writestring("\", line ", f);
271 sprintf(buf, "%d", lineno);
272 writestring(buf, f);
273 writestring("\n", f);
274 if (text != NULL) {
275 while (*text == ' ' || *text == '\t') {
276 text++;
277 offset--;
279 writestring(" ", f);
280 writestring(text, f);
281 if (*text == '\0' ||
282 text[strlen(text)-1] != '\n')
283 writestring("\n", f);
284 writestring(" ", f);
285 offset--;
286 while (offset > 0) {
287 writestring(" ", f);
288 offset--;
290 writestring("^\n", f);
292 v = message;
295 if (writeobject(exception, f, PRINT_RAW) != 0)
296 err_clear();
297 if (v != NULL && v != None) {
298 writestring(": ", f);
299 if (writeobject(v, f, PRINT_RAW) != 0)
300 err_clear();
302 writestring("\n", f);
304 XDECREF(exception);
305 XDECREF(v);
308 object *
309 run_string(str, start, globals, locals)
310 char *str;
311 int start;
312 object *globals, *locals;
314 return run_err_node(parse_string(str, start),
315 "<string>", globals, locals);
318 object *
319 run_file(fp, filename, start, globals, locals)
320 FILE *fp;
321 char *filename;
322 int start;
323 object *globals, *locals;
325 return run_err_node(parse_file(fp, filename, start),
326 filename, globals, locals);
329 static object *
330 run_err_node(n, filename, globals, locals)
331 node *n;
332 char *filename;
333 object *globals, *locals;
335 if (n == NULL)
336 return NULL;
337 return run_node(n, filename, globals, locals);
340 static object *
341 run_node(n, filename, globals, locals)
342 node *n;
343 char *filename;
344 object *globals, *locals;
346 codeobject *co;
347 object *v;
348 co = compile(n, filename);
349 freetree(n);
350 if (co == NULL)
351 return NULL;
352 v = eval_code(co, globals, locals, (object *)NULL, (object *)NULL);
353 DECREF(co);
354 return v;
357 object *
358 compile_string(str, filename, start)
359 char *str;
360 char *filename;
361 int start;
363 node *n;
364 int err;
365 codeobject *co;
366 n = parse_string(str, start);
367 if (n == NULL)
368 return NULL;
369 co = compile(n, filename);
370 freetree(n);
371 return (object *)co;
374 /* Simplified interface to parsefile -- return node or set exception */
376 node *
377 parse_file(fp, filename, start)
378 FILE *fp;
379 char *filename;
380 int start;
382 node *n;
383 perrdetail err;
384 BGN_SAVE
385 n = parsefile(fp, filename, &gram, start,
386 (char *)0, (char *)0, &err);
387 END_SAVE
388 if (n == NULL)
389 err_input(&err);
390 return n;
393 /* Simplified interface to parsestring -- return node or set exception */
395 node *
396 parse_string(str, start)
397 char *str;
398 int start;
400 node *n;
401 perrdetail err;
402 n = parsestring(str, &gram, start, &err);
403 if (n == NULL)
404 err_input(&err);
405 return n;
408 /* Set the error appropriate to the given input error code (see errcode.h) */
410 static void
411 err_input(err)
412 perrdetail *err;
414 object *v, *w;
415 char *msg = NULL;
416 v = mkvalue("(ziiz)", err->filename,
417 err->lineno, err->offset, err->text);
418 if (err->text != NULL) {
419 free(err->text);
420 err->text = NULL;
422 switch (err->error) {
423 case E_SYNTAX:
424 msg = "invalid syntax";
425 break;
426 case E_TOKEN:
427 msg = "invalid token";
429 break;
430 case E_INTR:
431 err_set(KeyboardInterrupt);
432 return;
433 case E_NOMEM:
434 err_nomem();
435 return;
436 case E_EOF:
437 msg = "unexpected EOF while parsing";
438 break;
439 default:
440 fprintf(stderr, "error=%d\n", err->error);
441 msg = "unknown parsing error";
442 break;
444 w = mkvalue("(sO)", msg, v);
445 XDECREF(v);
446 err_setval(SyntaxError, w);
447 XDECREF(w);
450 /* Print fatal error message and abort */
452 void
453 fatal(msg)
454 char *msg;
456 fprintf(stderr, "Fatal error: %s\n", msg);
457 abort();
460 /* Clean up and exit */
462 #ifdef WITH_THREAD
463 int threads_started = 0; /* Set by threadmodule.c and maybe others */
464 #endif
466 void
467 cleanup()
469 object *exitfunc = sysget("exitfunc");
471 if (exitfunc) {
472 object *arg;
473 object *res;
474 sysset("exitfunc", (object *)NULL);
475 arg = newtupleobject(0);
476 if (arg == NULL)
477 res = NULL;
478 else {
479 res = call_object(exitfunc, arg);
480 DECREF(arg);
482 if (res == NULL) {
483 fprintf(stderr, "Error in sys.exitfunc:\n");
484 print_error();
488 flushline();
491 #ifdef COUNT_ALLOCS
492 extern void dump_counts PROTO((void));
493 #endif
495 void
496 goaway(sts)
497 int sts;
499 cleanup();
501 #ifdef COUNT_ALLOCS
502 dump_counts();
503 #endif
505 #ifdef WITH_THREAD
507 /* Other threads may still be active, so skip most of the
508 cleanup actions usually done (these are mostly for
509 debugging anyway). */
511 (void) save_thread();
512 if (threads_started)
513 _exit_prog(sts);
514 else
515 exit_prog(sts);
517 #else /* WITH_THREAD */
519 doneimport();
521 err_clear();
523 #ifdef REF_DEBUG
524 fprintf(stderr, "[%ld refs]\n", ref_total);
525 #endif
527 #ifdef TRACE_REFS
528 if (askyesno("Print left references?")) {
529 printrefs(stderr);
531 #endif /* TRACE_REFS */
533 exit(sts);
534 #endif /* WITH_THREAD */
535 /*NOTREACHED*/
538 #ifdef HAVE_SIGNAL_H
539 static RETSIGTYPE
540 sighandler(sig)
541 int sig;
543 signal(sig, SIG_DFL); /* Don't catch recursive signals */
544 cleanup(); /* Do essential clean-up */
545 #ifdef HAVE_GETPID
546 kill(getpid(), sig); /* Pretend the signal killed us */
547 #else
548 exit(1);
549 #endif
550 /*NOTREACHED*/
552 #endif
554 static void
555 initsigs()
557 initintr();
558 #ifdef HAVE_SIGNAL_H
559 #ifdef SIGHUP
560 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
561 signal(SIGHUP, sighandler);
562 #endif
563 #ifdef SIGTERM
564 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
565 signal(SIGTERM, sighandler);
566 #endif
567 #endif /* HAVE_SIGNAL_H */
570 #ifdef TRACE_REFS
571 /* Ask a yes/no question */
574 askyesno(prompt)
575 char *prompt;
577 char buf[256];
579 printf("%s [ny] ", prompt);
580 if (fgets(buf, sizeof buf, stdin) == NULL)
581 return 0;
582 return buf[0] == 'y' || buf[0] == 'Y';
584 #endif
586 #ifdef applec /* MPW (also usable for Think C 3.0) */
588 /* Check for file descriptor connected to interactive device.
589 Pretend that stdin is always interactive, other files never. */
592 isatty(fd)
593 int fd;
595 return fd == fileno(stdin);
598 #endif