Debian Codegraph @

pTk/mTk/tclGeneric/tclMain.c

raw symbols SCIP
1 /*
2 * tclMain.c --
3 *
4 * Main program for Tcl shells and other Tcl-based applications.
5 *
6 * Copyright (c) 1988-1994 The Regents of the University of California.
7 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
8 * Copyright (c) 2000 Ajuba Solutions.
9 *
10 * See the file "license.terms" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 *
13 * RCS: @(#) $Id: tclMain.c,v 1.20 2002/05/29 22:59:33 dgp Exp $
14 */
15
16 #include "tcl.h"
17 #include "tclInt.h"
18
19 # undef TCL_STORAGE_CLASS
20 # define TCL_STORAGE_CLASS DLLEXPORT
21
22 /*
23 * Declarations for various library procedures and variables (don't want
24 * to include tclPort.h here, because people might copy this file out of
25 * the Tcl source directory to make their own modified versions).
26 */
27
28 #if !defined(MAC_TCL)
29 extern int isatty _ANSI_ARGS_((int fd));
30 #else
31 #include <unistd.h>
32 #endif
33
34 static Tcl_Obj *tclStartupScriptPath = NULL;
35
36 static Tcl_MainLoopProc *mainLoopProc = NULL;
37
38 /*
39 * Structure definition for information used to keep the state of
40 * an interactive command processor that reads lines from standard
41 * input and writes prompts and results to standard output.
42 */
43
44 typedef enum {
45 PROMPT_NONE, /* Print no prompt */
46 PROMPT_START, /* Print prompt for command start */
47 PROMPT_CONTINUE /* Print prompt for command continuation */
48 } PromptType;
49
50 typedef struct InteractiveState {
51 Tcl_Channel input; /* The standard input channel from which
52 * lines are read. */
53 int tty; /* Non-zero means standard input is a
54 * terminal-like device. Zero means it's
55 * a file. */
56 Tcl_Obj *commandPtr; /* Used to assemble lines of input into
57 * Tcl commands. */
58 PromptType prompt; /* Next prompt to print */
59 Tcl_Interp *interp; /* Interpreter that evaluates interactive
60 * commands. */
61 } InteractiveState;
62
63 /*
64 * Forward declarations for procedures defined later in this file.
65 */
66
67 static void Prompt _ANSI_ARGS_((Tcl_Interp *interp,
68 PromptType *promptPtr));
69 static void StdinProc _ANSI_ARGS_((ClientData clientData,
70 int mask));
71
72
73 /*
74 *----------------------------------------------------------------------
75 *
76 * TclSetStartupScriptPath --
77 *
78 * Primes the startup script VFS path, used to override the
79 * command line processing.
80 *
81 * Results:
82 * None.
83 *
84 * Side effects:
85 * This procedure initializes the VFS path of the Tcl script to
86 * run at startup.
87 *
88 *----------------------------------------------------------------------
89 */
90 void TclSetStartupScriptPath(pathPtr)
91 Tcl_Obj *pathPtr;
92 {
93 if (tclStartupScriptPath != NULL) {
94 Tcl_DecrRefCount(tclStartupScriptPath);
95 }
96 tclStartupScriptPath = pathPtr;
97 if (tclStartupScriptPath != NULL) {
98 Tcl_IncrRefCount(tclStartupScriptPath);
99 }
100 }
101
102
103 /*
104 *----------------------------------------------------------------------
105 *
106 * TclGetStartupScriptPath --
107 *
108 * Gets the startup script VFS path, used to override the
109 * command line processing.
110 *
111 * Results:
112 * The startup script VFS path, NULL if none has been set.
113 *
114 * Side effects:
115 * None.
116 *
117 *----------------------------------------------------------------------
118 */
119 Tcl_Obj *TclGetStartupScriptPath()
120 {
121 return tclStartupScriptPath;
122 }
123
124
125 /*
126 *----------------------------------------------------------------------
127 *
128 * TclSetStartupScriptFileName --
129 *
130 * Primes the startup script file name, used to override the
131 * command line processing.
132 *
133 * Results:
134 * None.
135 *
136 * Side effects:
137 * This procedure initializes the file name of the Tcl script to
138 * run at startup.
139 *
140 *----------------------------------------------------------------------
141 */
142 void TclSetStartupScriptFileName(fileName)
143 CONST char *fileName;
144 {
145 Tcl_Obj *pathPtr = Tcl_NewStringObj(fileName,-1);
146 TclSetStartupScriptPath(pathPtr);
147 }
148
149
150 /*
151 *----------------------------------------------------------------------
152 *
153 * TclGetStartupScriptFileName --
154 *
155 * Gets the startup script file name, used to override the
156 * command line processing.
157 *
158 * Results:
159 * The startup script file name, NULL if none has been set.
160 *
161 * Side effects:
162 * None.
163 *
164 *----------------------------------------------------------------------
165 */
166 CONST char *TclGetStartupScriptFileName()
167 {
168 Tcl_Obj *pathPtr = TclGetStartupScriptPath();
169
170 if (pathPtr == NULL) {
171 return NULL;
172 }
173 return Tcl_GetString(pathPtr);
174 }
175
176
177
178 /*
179 *----------------------------------------------------------------------
180 *
181 * Tcl_Main --
182 *
183 * Main program for tclsh and most other Tcl-based applications.
184 *
185 * Results:
186 * None. This procedure never returns (it exits the process when
187 * it's done).
188 *
189 * Side effects:
190 * This procedure initializes the Tcl world and then starts
191 * interpreting commands; almost anything could happen, depending
192 * on the script being interpreted.
193 *
194 *----------------------------------------------------------------------
195 */
196
197 void
198 Tcl_Main(argc, argv, appInitProc)
199 int argc; /* Number of arguments. */
200 char **argv; /* Array of argument strings. */
201 Tcl_AppInitProc *appInitProc;
202 /* Application-specific initialization
203 * procedure to call after most
204 * initialization but before starting to
205 * execute commands. */
206 {
207 Tcl_Obj *resultPtr;
208 Tcl_Obj *commandPtr = NULL;
209 char buffer[TCL_INTEGER_SPACE + 5], *args;
210 PromptType prompt = PROMPT_START;
211 int code, length, tty;
212 int exitCode = 0;
213 Tcl_Channel inChannel, outChannel, errChannel;
214 Tcl_Interp *interp;
215 Tcl_DString argString;
216
217 Tcl_FindExecutable(argv[0]);
218
219 interp = Tcl_CreateInterp();
220 Tcl_InitMemory(interp);
221
222 /*
223 * Make command-line arguments available in the Tcl variables "argc"
224 * and "argv". If the first argument doesn't start with a "-" then
225 * strip it off and use it as the name of a script file to process.
226 */
227
228 if (TclGetStartupScriptPath() == NULL) {
229 if ((argc > 1) && (argv[1][0] != '-')) {
230 TclSetStartupScriptFileName(argv[1]);
231 argc--;
232 argv++;
233 }
234 }
235
236 /*
237 * The CONST casting is safe, and better we do it here than force
238 * all callers of Tcl_Main to do it. (Those callers are likely
239 * in a main() that can't easily change its signature.)
240 */
241
242 args = Tcl_Merge(argc-1, (CONST char **)argv+1);
243 Tcl_ExternalToUtfDString(NULL, args, -1, &argString);
244 Tcl_SetVar(interp, "argv", Tcl_DStringValue(&argString), TCL_GLOBAL_ONLY);
245 Tcl_DStringFree(&argString);
246 ckfree(args);
247
248 if (TclGetStartupScriptPath() == NULL) {
249 Tcl_ExternalToUtfDString(NULL, argv[0], -1, &argString);
250 } else {
251 TclSetStartupScriptFileName(Tcl_ExternalToUtfDString(NULL,
252 TclGetStartupScriptFileName(), -1, &argString));
253 }
254
255 TclFormatInt(buffer, (long) argc-1);
256 Tcl_SetVar(interp, "argc", buffer, TCL_GLOBAL_ONLY);
257 Tcl_SetVar(interp, "argv0", Tcl_DStringValue(&argString), TCL_GLOBAL_ONLY);
258
259 /*
260 * Set the "tcl_interactive" variable.
261 */
262
263 tty = isatty(0);
264 Tcl_SetVar(interp, "tcl_interactive",
265 ((TclGetStartupScriptPath() == NULL) && tty) ? "1" : "0",
266 TCL_GLOBAL_ONLY);
267
268 /*
269 * Invoke application-specific initialization.
270 */
271
272 Tcl_Preserve((ClientData) interp);
273 if ((*appInitProc)(interp) != TCL_OK) {
274 errChannel = Tcl_GetStdChannel(TCL_STDERR);
275 if (errChannel) {
276 Tcl_WriteChars(errChannel,
277 "application-specific initialization failed: ", -1);
278 Tcl_WriteObj(errChannel, Tcl_GetObjResult(interp));
279 Tcl_WriteChars(errChannel, "\n", 1);
280 }
281 }
282 if (Tcl_InterpDeleted(interp)) {
283 goto done;
284 }
285
286 /*
287 * If a script file was specified then just source that file
288 * and quit.
289 */
290
291 if (TclGetStartupScriptPath() != NULL) {
292 code = Tcl_FSEvalFile(interp, TclGetStartupScriptPath());
293 if (code != TCL_OK) {
294 errChannel = Tcl_GetStdChannel(TCL_STDERR);
295 if (errChannel) {
296
297 /*
298 * The following statement guarantees that the errorInfo
299 * variable is set properly.
300 */
301
302 Tcl_AddErrorInfo(interp, "");
303 Tcl_WriteObj(errChannel, Tcl_GetVar2Ex(interp, "errorInfo",
304 NULL, TCL_GLOBAL_ONLY));
305 Tcl_WriteChars(errChannel, "\n", 1);
306 }
307 exitCode = 1;
308 }
309 goto done;
310 }
311 Tcl_DStringFree(&argString);
312
313 /*
314 * We're running interactively. Source a user-specific startup
315 * file if the application specified one and if the file exists.
316 */
317
318 Tcl_SourceRCFile(interp);
319
320 /*
321 * Process commands from stdin until there's an end-of-file. Note
322 * that we need to fetch the standard channels again after every
323 * eval, since they may have been changed.
324 */
325
326 commandPtr = Tcl_NewObj();
327 Tcl_IncrRefCount(commandPtr);
328
329 /*
330 * Get a new value for tty if anyone writes to ::tcl_interactive
331 */
332 Tcl_LinkVar(interp, "tcl_interactive", (char *) &tty, TCL_LINK_BOOLEAN);
333 inChannel = Tcl_GetStdChannel(TCL_STDIN);
334 outChannel = Tcl_GetStdChannel(TCL_STDOUT);
335 while ((inChannel != (Tcl_Channel) NULL) && !Tcl_InterpDeleted(interp)) {
336 if (tty) {
337 Prompt(interp, &prompt);
338 if (Tcl_InterpDeleted(interp)) {
339 break;
340 }
341 inChannel = Tcl_GetStdChannel(TCL_STDIN);
342 if (inChannel == (Tcl_Channel) NULL) {
343 break;
344 }
345 }
346 if (Tcl_IsShared(commandPtr)) {
347 Tcl_DecrRefCount(commandPtr);
348 commandPtr = Tcl_DuplicateObj(commandPtr);
349 Tcl_IncrRefCount(commandPtr);
350 }
351 length = Tcl_GetsObj(inChannel, commandPtr);
352 if (length < 0) {
353 if (Tcl_InputBlocked(inChannel)) {
354
355 /*
356 * This can only happen if stdin has been set to
357 * non-blocking. In that case cycle back and try
358 * again. This sets up a tight polling loop (since
359 * we have no event loop running). If this causes
360 * bad CPU hogging, we might try toggling the blocking
361 * on stdin instead.
362 */
363
364 continue;
365 }
366
367 /*
368 * Either EOF, or an error on stdin; we're done
369 */
370
371 break;
372 }
373
374 /*
375 * Add the newline removed by Tcl_GetsObj back to the string.
376 */
377
378 if (Tcl_IsShared(commandPtr)) {
379 Tcl_DecrRefCount(commandPtr);
380 commandPtr = Tcl_DuplicateObj(commandPtr);
381 Tcl_IncrRefCount(commandPtr);
382 }
383 Tcl_AppendToObj(commandPtr, "\n", 1);
384 if (!TclObjCommandComplete(commandPtr)) {
385 prompt = PROMPT_CONTINUE;
386 continue;
387 }
388
389 prompt = PROMPT_START;
390 code = Tcl_RecordAndEvalObj(interp, commandPtr, TCL_EVAL_GLOBAL);
391 inChannel = Tcl_GetStdChannel(TCL_STDIN);
392 outChannel = Tcl_GetStdChannel(TCL_STDOUT);
393 errChannel = Tcl_GetStdChannel(TCL_STDERR);
394 Tcl_DecrRefCount(commandPtr);
395 commandPtr = Tcl_NewObj();
396 Tcl_IncrRefCount(commandPtr);
397 if (code != TCL_OK) {
398 if (errChannel) {
399 Tcl_WriteObj(errChannel, Tcl_GetObjResult(interp));
400 Tcl_WriteChars(errChannel, "\n", 1);
401 }
402 } else if (tty) {
403 resultPtr = Tcl_GetObjResult(interp);
404 Tcl_IncrRefCount(resultPtr);
405 Tcl_GetStringFromObj(resultPtr, &length);
406 if ((length > 0) && outChannel) {
407 Tcl_WriteObj(outChannel, resultPtr);
408 Tcl_WriteChars(outChannel, "\n", 1);
409 }
410 Tcl_DecrRefCount(resultPtr);
411 }
412 if (mainLoopProc != NULL) {
413
414 /*
415 * If a main loop has been defined while running interactively,
416 * we want to start a fileevent based prompt by establishing a
417 * channel handler for stdin.
418 */
419
420 InteractiveState *isPtr = NULL;
421
422 if (inChannel) {
423 if (tty) {
424 Prompt(interp, &prompt);
425 }
426 isPtr = (InteractiveState *)
427 ckalloc((int) sizeof(InteractiveState));
428 isPtr->input = inChannel;
429 isPtr->tty = tty;
430 isPtr->commandPtr = commandPtr;
431 isPtr->prompt = prompt;
432 isPtr->interp = interp;
433
434 Tcl_UnlinkVar(interp, "tcl_interactive");
435 Tcl_LinkVar(interp, "tcl_interactive", (char *) &(isPtr->tty),
436 TCL_LINK_BOOLEAN);
437
438 Tcl_CreateChannelHandler(inChannel, TCL_READABLE, StdinProc,
439 (ClientData) isPtr);
440 }
441
442 (*mainLoopProc)();
443 mainLoopProc = NULL;
444
445 if (inChannel) {
446 tty = isPtr->tty;
447 Tcl_UnlinkVar(interp, "tcl_interactive");
448 Tcl_LinkVar(interp, "tcl_interactive", (char *) &tty,
449 TCL_LINK_BOOLEAN);
450 prompt = isPtr->prompt;
451 commandPtr = isPtr->commandPtr;
452 if (isPtr->input != (Tcl_Channel) NULL) {
453 Tcl_DeleteChannelHandler(isPtr->input, StdinProc,
454 (ClientData) isPtr);
455 }
456 ckfree((char *)isPtr);
457 }
458 inChannel = Tcl_GetStdChannel(TCL_STDIN);
459 outChannel = Tcl_GetStdChannel(TCL_STDOUT);
460 errChannel = Tcl_GetStdChannel(TCL_STDERR);
461 }
462 #ifdef TCL_MEM_DEBUG
463
464 /*
465 * This code here only for the (unsupported and deprecated)
466 * [checkmem] command.
467 */
468
469 if (tclMemDumpFileName != NULL) {
470 mainLoopProc = NULL;
471 Tcl_DeleteInterp(interp);
472 }
473 #endif
474 }
475
476 done:
477 if ((exitCode == 0) && (mainLoopProc != NULL)) {
478
479 /*
480 * If everything has gone OK so far, call the main loop proc,
481 * if it exists. Packages (like Tk) can set it to start processing
482 * events at this point.
483 */
484
485 (*mainLoopProc)();
486 mainLoopProc = NULL;
487 }
488 if (commandPtr != NULL) {
489 Tcl_DecrRefCount(commandPtr);
490 }
491
492 /*
493 * Rather than calling exit, invoke the "exit" command so that
494 * users can replace "exit" with some other command to do additional
495 * cleanup on exit. The Tcl_Eval call should never return.
496 */
497
498 if (!Tcl_InterpDeleted(interp)) {
499 sprintf(buffer, "exit %d", exitCode);
500 Tcl_Eval(interp, buffer);
501
502 /*
503 * If Tcl_Eval returns, trying to eval [exit], something
504 * unusual is happening. Maybe interp has been deleted;
505 * maybe [exit] was redefined. We still want to cleanup
506 * and exit.
507 */
508
509 if (!Tcl_InterpDeleted(interp)) {
510 Tcl_DeleteInterp(interp);
511 }
512 }
513 TclSetStartupScriptPath(NULL);
514
515 /*
516 * If we get here, the master interp has been deleted. Allow
517 * its destruction with the last matching Tcl_Release.
518 */
519
520 Tcl_Release((ClientData) interp);
521 Tcl_Exit(exitCode);
522 }
523
524 /*
525 *---------------------------------------------------------------
526 *
527 * Tcl_SetMainLoop --
528 *
529 * Sets an alternative main loop procedure.
530 *
531 * Results:
532 * Returns the previously defined main loop procedure.
533 *
534 * Side effects:
535 * This procedure will be called before Tcl exits, allowing for
536 * the creation of an event loop.
537 *
538 *---------------------------------------------------------------
539 */
540
541 void
542 Tcl_SetMainLoop(proc)
543 Tcl_MainLoopProc *proc;
544 {
545 mainLoopProc = proc;
546 }
547
548 /*
549 *----------------------------------------------------------------------
550 *
551 * StdinProc --
552 *
553 * This procedure is invoked by the event dispatcher whenever
554 * standard input becomes readable. It grabs the next line of
555 * input characters, adds them to a command being assembled, and
556 * executes the command if it's complete.
557 *
558 * Results:
559 * None.
560 *
561 * Side effects:
562 * Could be almost arbitrary, depending on the command that's
563 * typed.
564 *
565 *----------------------------------------------------------------------
566 */
567
568 /* ARGSUSED */
569 static void
570 StdinProc(clientData, mask)
571 ClientData clientData; /* The state of interactive cmd line */
572 int mask; /* Not used. */
573 {
574 InteractiveState *isPtr = (InteractiveState *) clientData;
575 Tcl_Channel chan = isPtr->input;
576 Tcl_Obj *commandPtr = isPtr->commandPtr;
577 Tcl_Interp *interp = isPtr->interp;
578 int code, length;
579
580 if (Tcl_IsShared(commandPtr)) {
581 Tcl_DecrRefCount(commandPtr);
582 commandPtr = Tcl_DuplicateObj(commandPtr);
583 Tcl_IncrRefCount(commandPtr);
584 }
585 length = Tcl_GetsObj(chan, commandPtr);
586 if (length < 0) {
587 if (Tcl_InputBlocked(chan)) {
588 return;
589 }
590 if (isPtr->tty) {
591 /*
592 * Would be better to find a way to exit the mainLoop?
593 * Or perhaps evaluate [exit]? Leaving as is for now due
594 * to compatibility concerns.
595 */
596 Tcl_Exit(0);
597 }
598 Tcl_DeleteChannelHandler(chan, StdinProc, (ClientData) isPtr);
599 return;
600 }
601
602 if (Tcl_IsShared(commandPtr)) {
603 Tcl_DecrRefCount(commandPtr);
604 commandPtr = Tcl_DuplicateObj(commandPtr);
605 Tcl_IncrRefCount(commandPtr);
606 }
607 Tcl_AppendToObj(commandPtr, "\n", 1);
608 if (!TclObjCommandComplete(commandPtr)) {
609 isPtr->prompt = PROMPT_CONTINUE;
610 goto prompt;
611 }
612 isPtr->prompt = PROMPT_START;
613
614 /*
615 * Disable the stdin channel handler while evaluating the command;
616 * otherwise if the command re-enters the event loop we might
617 * process commands from stdin before the current command is
618 * finished. Among other things, this will trash the text of the
619 * command being evaluated.
620 */
621
622 Tcl_CreateChannelHandler(chan, 0, StdinProc, (ClientData) isPtr);
623 code = Tcl_RecordAndEvalObj(interp, commandPtr, TCL_EVAL_GLOBAL);
624 isPtr->input = chan = Tcl_GetStdChannel(TCL_STDIN);
625 Tcl_DecrRefCount(commandPtr);
626 isPtr->commandPtr = commandPtr = Tcl_NewObj();
627 Tcl_IncrRefCount(commandPtr);
628 if (chan != (Tcl_Channel) NULL) {
629 Tcl_CreateChannelHandler(chan, TCL_READABLE, StdinProc,
630 (ClientData) isPtr);
631 }
632 if (code != TCL_OK) {
633 Tcl_Channel errChannel = Tcl_GetStdChannel(TCL_STDERR);
634 if (errChannel != (Tcl_Channel) NULL) {
635 Tcl_WriteObj(errChannel, Tcl_GetObjResult(interp));
636 Tcl_WriteChars(errChannel, "\n", 1);
637 }
638 } else if (isPtr->tty) {
639 Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
640 Tcl_Channel outChannel = Tcl_GetStdChannel(TCL_STDOUT);
641 Tcl_IncrRefCount(resultPtr);
642 Tcl_GetStringFromObj(resultPtr, &length);
643 if ((length >0) && (outChannel != (Tcl_Channel) NULL)) {
644 Tcl_WriteObj(outChannel, resultPtr);
645 Tcl_WriteChars(outChannel, "\n", 1);
646 }
647 Tcl_DecrRefCount(resultPtr);
648 }
649
650 /*
651 * If a tty stdin is still around, output a prompt.
652 */
653
654 prompt:
655 if (isPtr->tty && (isPtr->input != (Tcl_Channel) NULL)) {
656 Prompt(interp, &(isPtr->prompt));
657 isPtr->input = Tcl_GetStdChannel(TCL_STDIN);
658 }
659 }
660
661 /*
662 *----------------------------------------------------------------------
663 *
664 * Prompt --
665 *
666 * Issue a prompt on standard output, or invoke a script
667 * to issue the prompt.
668 *
669 * Results:
670 * None.
671 *
672 * Side effects:
673 * A prompt gets output, and a Tcl script may be evaluated
674 * in interp.
675 *
676 *----------------------------------------------------------------------
677 */
678
679 static void
680 Prompt(interp, promptPtr)
681 Tcl_Interp *interp; /* Interpreter to use for prompting. */
682 PromptType *promptPtr; /* Points to type of prompt to print.
683 * Filled with PROMPT_NONE after a
684 * prompt is printed. */
685 {
686 Tcl_Obj *promptCmdPtr;
687 int code;
688 Tcl_Channel outChannel, errChannel;
689
690 if (*promptPtr == PROMPT_NONE) {
691 return;
692 }
693
694 promptCmdPtr = Tcl_GetVar2Ex(interp,
695 ((*promptPtr == PROMPT_CONTINUE) ? "tcl_prompt2" : "tcl_prompt1"),
696 NULL, TCL_GLOBAL_ONLY);
697 if (Tcl_InterpDeleted(interp)) {
698 return;
699 }
700 if (promptCmdPtr == NULL) {
701 defaultPrompt:
702 outChannel = Tcl_GetStdChannel(TCL_STDOUT);
703 if ((*promptPtr == PROMPT_START)
704 && (outChannel != (Tcl_Channel) NULL)) {
705 Tcl_WriteChars(outChannel, "% ", 2);
706 }
707 } else {
708 code = Tcl_EvalObjEx(interp, promptCmdPtr, TCL_EVAL_GLOBAL);
709 if (code != TCL_OK) {
710 Tcl_AddErrorInfo(interp,
711 "\n (script that generates prompt)");
712 errChannel = Tcl_GetStdChannel(TCL_STDERR);
713 if (errChannel != (Tcl_Channel) NULL) {
714 Tcl_WriteObj(errChannel, Tcl_GetObjResult(interp));
715 Tcl_WriteChars(errChannel, "\n", 1);
716 }
717 goto defaultPrompt;
718 }
719 }
720 outChannel = Tcl_GetStdChannel(TCL_STDOUT);
721 if (outChannel != (Tcl_Channel) NULL) {
722 Tcl_Flush(outChannel);
723 }
724 *promptPtr = PROMPT_NONE;
725 }