Debian Codegraph @

generic/tclMain.c

raw
1 /*
2 * tclMain.c --
3 *
4 * Main program for Tcl shells and other Tcl-based applications.
5 * This file contains a generic main program for Tcl shells and other
6 * Tcl-based applications. It can be used as-is for many applications,
7 * just by supplying a different appInitProc function for each specific
8 * application. Or, it can be used as a template for creating new main
9 * programs for Tcl applications.
10 *
11 * Copyright (c) 1988-1994 The Regents of the University of California.
12 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
13 * Copyright (c) 2000 Ajuba Solutions.
14 *
15 * See the file "license.terms" for information on usage and redistribution of
16 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
17 */
18
19 /*
20 * On Windows, this file needs to be compiled twice, once with UNICODE and
21 * _UNICODE defined. This way both Tcl_Main and Tcl_MainExW can be
22 * implemented, sharing the same source code.
23 */
24
25 #include "tclInt.h"
26
27 /*
28 * The default prompt used when the user has not overridden it.
29 */
30
31 static const char DEFAULT_PRIMARY_PROMPT[] = "% ";
32
33 /*
34 * This file can be compiled on Windows in UNICODE mode, as well as on all
35 * other platforms using the native encoding. This is done by using the normal
36 * Windows functions like _tcscmp, but on platforms which don't have <tchar.h>
37 * we have to translate that to strcmp here.
38 */
39
40 #ifndef _WIN32
41 # define TCHAR char
42 # define TEXT(arg) arg
43 # define _tcscmp strcmp
44 #endif
45
46 static inline Tcl_Obj *
47 NewNativeObj(
48 TCHAR *string)
49 {
50 Tcl_DString ds;
51
52 #ifdef UNICODE
53 Tcl_WinTCharToUtf(string, -1, &ds);
54 #else
55 (void)Tcl_ExternalToUtfDString(NULL, (char *)string, -1, &ds);
56 #endif
57 return TclDStringToObj(&ds);
58 }
59
60 /*
61 * Declarations for various library functions and variables (don't want to
62 * include tclPort.h here, because people might copy this file out of the Tcl
63 * source directory to make their own modified versions).
64 */
65
66 #if defined _MSC_VER && _MSC_VER < 1900
67 /* isatty is always defined on MSVC 14.0, but not necessarily as CRTIMPORT. */
68 extern CRTIMPORT int isatty(int fd);
69 #endif
70
71 /*
72 * The thread-local variables for this file's functions.
73 */
74
75 typedef struct {
76 Tcl_Obj *path; /* The filename of the script for *_Main()
77 * routines to [source] as a startup script,
78 * or NULL for none set, meaning enter
79 * interactive mode. */
80 Tcl_Obj *encoding; /* The encoding of the startup script file. */
81 Tcl_MainLoopProc *mainLoopProc;
82 /* Any installed main loop handler. The main
83 * extension that installs these is Tk. */
84 } ThreadSpecificData;
85
86 /*
87 * Structure definition for information used to keep the state of an
88 * interactive command processor that reads lines from standard input and
89 * writes prompts and results to standard output.
90 */
91
92 typedef enum {
93 PROMPT_NONE, /* Print no prompt */
94 PROMPT_START, /* Print prompt for command start */
95 PROMPT_CONTINUE /* Print prompt for command continuation */
96 } PromptType;
97
98 typedef struct {
99 Tcl_Channel input; /* The standard input channel from which lines
100 * are read. */
101 int tty; /* Non-zero means standard input is a
102 * terminal-like device. Zero means it's a
103 * file. */
104 Tcl_Obj *commandPtr; /* Used to assemble lines of input into Tcl
105 * commands. */
106 PromptType prompt; /* Next prompt to print */
107 Tcl_Interp *interp; /* Interpreter that evaluates interactive
108 * commands. */
109 } InteractiveState;
110
111 /*
112 * Forward declarations for functions defined later in this file.
113 */
114
115 MODULE_SCOPE Tcl_MainLoopProc *TclGetMainLoop(void);
116 static void Prompt(Tcl_Interp *interp, InteractiveState *isPtr);
117 static void StdinProc(ClientData clientData, int mask);
118 static void FreeMainInterp(ClientData clientData);
119
120 #if !defined(_WIN32) || defined(UNICODE) && !defined(TCL_ASCII_MAIN)
121 static Tcl_ThreadDataKey dataKey;
122
123 /*
124 *----------------------------------------------------------------------
125 *
126 * Tcl_SetStartupScript --
127 *
128 * Sets the path and encoding of the startup script to be evaluated by
129 * Tcl_Main, used to override the command line processing.
130 *
131 * Results:
132 * None.
133 *
134 * Side effects:
135 *
136 *----------------------------------------------------------------------
137 */
138
139 void
140 Tcl_SetStartupScript(
141 Tcl_Obj *path, /* Filesystem path of startup script file */
142 const char *encoding) /* Encoding of the data in that file */
143 {
144 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
145 Tcl_Obj *newEncoding = NULL;
146
147 if (encoding != NULL) {
148 newEncoding = Tcl_NewStringObj(encoding, -1);
149 Tcl_IncrRefCount(newEncoding);
150 }
151
152 if (path != NULL) {
153 Tcl_IncrRefCount(path);
154 }
155 if (tsdPtr->path != NULL) {
156 Tcl_DecrRefCount(tsdPtr->path);
157 }
158 tsdPtr->path = path;
159
160 if (tsdPtr->encoding != NULL) {
161 Tcl_DecrRefCount(tsdPtr->encoding);
162 }
163 tsdPtr->encoding = newEncoding;
164 }
165
166 /*
167 *----------------------------------------------------------------------
168 *
169 * Tcl_GetStartupScript --
170 *
171 * Gets the path and encoding of the startup script to be evaluated by
172 * Tcl_Main.
173 *
174 * Results:
175 * The path of the startup script; NULL if none has been set.
176 *
177 * Side effects:
178 * If encodingPtr is not NULL, stores a (const char *) in it pointing to
179 * the encoding name registered for the startup script. Tcl retains
180 * ownership of the string, and may free it. Caller should make a copy
181 * for long-term use.
182 *
183 *----------------------------------------------------------------------
184 */
185
186 Tcl_Obj *
187 Tcl_GetStartupScript(
188 const char **encodingPtr) /* When not NULL, points to storage for the
189 * (const char *) that points to the
190 * registered encoding name for the startup
191 * script. */
192 {
193 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
194
195 if (encodingPtr != NULL) {
196 if (tsdPtr->encoding != NULL) {
197 *encodingPtr = Tcl_GetString(tsdPtr->encoding);
198 } else {
199 *encodingPtr = NULL;
200 }
201 }
202 return tsdPtr->path;
203 }
204
205 /*----------------------------------------------------------------------
206 *
207 * Tcl_SourceRCFile --
208 *
209 * This function is typically invoked by Tcl_Main of Tk_Main function to
210 * source an application specific rc file into the interpreter at startup
211 * time. If the filename cannot be translated (e.g. it referred to a bogus
212 * user or there was no HOME environment variable). Just do nothing.
213 *
214 * Results:
215 * None.
216 *
217 * Side effects:
218 * Depends on what's in the rc script.
219 *
220 *----------------------------------------------------------------------
221 */
222
223 void
224 Tcl_SourceRCFile(
225 Tcl_Interp *interp) /* Interpreter to source rc file into. */
226 {
227 Tcl_DString temp;
228 const char *fileName;
229 Tcl_Channel chan;
230
231 fileName = Tcl_GetVar2(interp, "tcl_rcFileName", NULL, TCL_GLOBAL_ONLY);
232 if (fileName != NULL) {
233 Tcl_Channel c;
234 const char *fullName;
235
236 Tcl_DStringInit(&temp);
237 fullName = Tcl_TranslateFileName(interp, fileName, &temp);
238 if (fullName != NULL) {
239 /*
240 * Test for the existence of the rc file before trying to read it.
241 */
242
243 c = Tcl_OpenFileChannel(NULL, fullName, "r", 0);
244 if (c != NULL) {
245 Tcl_Close(NULL, c);
246 if (Tcl_EvalFile(interp, fullName) != TCL_OK) {
247 chan = Tcl_GetStdChannel(TCL_STDERR);
248 if (chan) {
249 Tcl_WriteObj(chan, Tcl_GetObjResult(interp));
250 Tcl_WriteChars(chan, "\n", 1);
251 }
252 }
253 }
254 }
255 Tcl_DStringFree(&temp);
256 }
257 }
258 #endif /* !UNICODE */
259
260 /*----------------------------------------------------------------------
261 *
262 * Tcl_Main, Tcl_MainEx --
263 *
264 * Main program for tclsh and most other Tcl-based applications.
265 *
266 * Results:
267 * None. This function never returns (it exits the process when it's
268 * done).
269 *
270 * Side effects:
271 * This function initializes the Tcl world and then starts interpreting
272 * commands; almost anything could happen, depending on the script being
273 * interpreted.
274 *
275 *----------------------------------------------------------------------
276 */
277
278 void
279 Tcl_MainEx(
280 int argc, /* Number of arguments. */
281 TCHAR **argv, /* Array of argument strings. */
282 Tcl_AppInitProc *appInitProc,
283 /* Application-specific initialization
284 * function to call after most initialization
285 * but before starting to execute commands. */
286 Tcl_Interp *interp)
287 {
288 int i=0; /* argv[i] index */
289 Tcl_Obj *path, *resultPtr, *argvPtr, *appName;
290 const char *encodingName = NULL;
291 int code, exitCode = 0;
292 Tcl_MainLoopProc *mainLoopProc;
293 Tcl_Channel chan;
294 InteractiveState is;
295
296 TclpSetInitialEncodings();
297 if (argc > 0) {
298 --argc; /* consume argv[0] */
299 ++i;
300 }
301 TclpFindExecutable((const char *)argv[0]); /* nb: this could be NULL
302 * w/ (eg) an empty argv supplied to execve() */
303
304 Tcl_InitMemory(interp);
305
306 is.interp = interp;
307 is.prompt = PROMPT_START;
308 TclNewObj(is.commandPtr);
309
310 /*
311 * If the application has not already set a startup script, parse the
312 * first few command line arguments to determine the script path and
313 * encoding.
314 */
315
316 if (NULL == Tcl_GetStartupScript(NULL)) {
317 /*
318 * Check whether first 3 args (argv[1] - argv[3]) look like
319 * -encoding ENCODING FILENAME
320 * or like
321 * FILENAME
322 */
323
324 /* mind argc is being adjusted as we proceed */
325 if ((argc >= 3) && (0 == _tcscmp(TEXT("-encoding"), argv[1]))
326 && ('-' != argv[3][0])) {
327 Tcl_Obj *value = NewNativeObj(argv[2]);
328 Tcl_SetStartupScript(NewNativeObj(argv[3]),
329 Tcl_GetString(value));
330 Tcl_DecrRefCount(value);
331 argc -= 3;
332 i += 3;
333 } else if ((argc >= 1) && ('-' != argv[1][0])) {
334 Tcl_SetStartupScript(NewNativeObj(argv[1]), NULL);
335 argc--;
336 i++;
337 }
338 }
339
340 path = Tcl_GetStartupScript(&encodingName);
341 if (path != NULL) {
342 appName = path;
343 } else if (argv[0]) {
344 appName = NewNativeObj(argv[0]);
345 } else {
346 appName = Tcl_NewStringObj("tclsh", -1);
347 }
348 Tcl_SetVar2Ex(interp, "argv0", NULL, appName, TCL_GLOBAL_ONLY);
349
350 Tcl_SetVar2Ex(interp, "argc", NULL, Tcl_NewIntObj(argc), TCL_GLOBAL_ONLY);
351
352 argvPtr = Tcl_NewListObj(0, NULL);
353 while (argc--) {
354 Tcl_ListObjAppendElement(NULL, argvPtr, NewNativeObj(argv[i++]));
355 }
356 Tcl_SetVar2Ex(interp, "argv", NULL, argvPtr, TCL_GLOBAL_ONLY);
357
358 /*
359 * Set the "tcl_interactive" variable.
360 */
361
362 is.tty = isatty(0);
363 Tcl_SetVar2Ex(interp, "tcl_interactive", NULL,
364 Tcl_NewBooleanObj(!path && is.tty), TCL_GLOBAL_ONLY);
365
366 /*
367 * Invoke application-specific initialization.
368 */
369
370 Tcl_Preserve(interp);
371 if (appInitProc(interp) != TCL_OK) {
372 chan = Tcl_GetStdChannel(TCL_STDERR);
373 if (chan) {
374 Tcl_WriteChars(chan,
375 "application-specific initialization failed: ", -1);
376 Tcl_WriteObj(chan, Tcl_GetObjResult(interp));
377 Tcl_WriteChars(chan, "\n", 1);
378 }
379 }
380 if (Tcl_InterpDeleted(interp)) {
381 goto done;
382 }
383 if (Tcl_LimitExceeded(interp)) {
384 goto done;
385 }
386 if (TclFullFinalizationRequested()) {
387 /*
388 * Arrange for final deletion of the main interp
389 */
390
391 /* ARGH Munchhausen effect */
392 Tcl_CreateExitHandler(FreeMainInterp, interp);
393 }
394
395 /*
396 * Invoke the script specified on the command line, if any. Must fetch it
397 * again, as the appInitProc might have reset it.
398 */
399
400 path = Tcl_GetStartupScript(&encodingName);
401 if (path != NULL) {
402 Tcl_ResetResult(interp);
403 code = Tcl_FSEvalFileEx(interp, path, encodingName);
404 if (code != TCL_OK) {
405 chan = Tcl_GetStdChannel(TCL_STDERR);
406 if (chan) {
407 Tcl_Obj *options = Tcl_GetReturnOptions(interp, code);
408 Tcl_Obj *valuePtr = NULL;
409
410 TclDictGet(NULL, options, "-errorinfo", &valuePtr);
411 if (valuePtr) {
412 Tcl_WriteObj(chan, valuePtr);
413 }
414 Tcl_WriteChars(chan, "\n", 1);
415 Tcl_DecrRefCount(options);
416 }
417 exitCode = 1;
418 }
419 goto done;
420 }
421
422 /*
423 * We're running interactively. Source a user-specific startup file if the
424 * application specified one and if the file exists.
425 */
426
427 Tcl_SourceRCFile(interp);
428 if (Tcl_LimitExceeded(interp)) {
429 goto done;
430 }
431
432 /*
433 * Process commands from stdin until there's an end-of-file. Note that we
434 * need to fetch the standard channels again after every eval, since they
435 * may have been changed.
436 */
437
438 Tcl_IncrRefCount(is.commandPtr);
439
440 /*
441 * Get a new value for tty if anyone writes to ::tcl_interactive
442 */
443
444 Tcl_LinkVar(interp, "tcl_interactive", (char *)&is.tty, TCL_LINK_BOOLEAN);
445 is.input = Tcl_GetStdChannel(TCL_STDIN);
446 while ((is.input != NULL) && !Tcl_InterpDeleted(interp)) {
447 mainLoopProc = TclGetMainLoop();
448 if (mainLoopProc == NULL) {
449 int length;
450
451 if (is.tty) {
452 Prompt(interp, &is);
453 if (Tcl_InterpDeleted(interp)) {
454 break;
455 }
456 if (Tcl_LimitExceeded(interp)) {
457 break;
458 }
459 is.input = Tcl_GetStdChannel(TCL_STDIN);
460 if (is.input == NULL) {
461 break;
462 }
463 }
464 if (Tcl_IsShared(is.commandPtr)) {
465 Tcl_DecrRefCount(is.commandPtr);
466 is.commandPtr = Tcl_DuplicateObj(is.commandPtr);
467 Tcl_IncrRefCount(is.commandPtr);
468 }
469 length = Tcl_GetsObj(is.input, is.commandPtr);
470 if (length < 0) {
471 if (Tcl_InputBlocked(is.input)) {
472 /*
473 * This can only happen if stdin has been set to
474 * non-blocking. In that case cycle back and try again.
475 * This sets up a tight polling loop (since we have no
476 * event loop running). If this causes bad CPU hogging, we
477 * might try toggling the blocking on stdin instead.
478 */
479
480 continue;
481 }
482
483 /*
484 * Either EOF, or an error on stdin; we're done
485 */
486
487 break;
488 }
489
490 /*
491 * Add the newline removed by Tcl_GetsObj back to the string. Have
492 * to add it back before testing completeness, because it can make
493 * a difference. [Bug 1775878]
494 */
495
496 if (Tcl_IsShared(is.commandPtr)) {
497 Tcl_DecrRefCount(is.commandPtr);
498 is.commandPtr = Tcl_DuplicateObj(is.commandPtr);
499 Tcl_IncrRefCount(is.commandPtr);
500 }
501 Tcl_AppendToObj(is.commandPtr, "\n", 1);
502 if (!TclObjCommandComplete(is.commandPtr)) {
503 is.prompt = PROMPT_CONTINUE;
504 continue;
505 }
506
507 is.prompt = PROMPT_START;
508
509 /*
510 * The final newline is syntactically redundant, and causes some
511 * error messages troubles deeper in, so lop it back off.
512 */
513
514 (void)Tcl_GetStringFromObj(is.commandPtr, &length);
515 Tcl_SetObjLength(is.commandPtr, --length);
516 code = Tcl_RecordAndEvalObj(interp, is.commandPtr,
517 TCL_EVAL_GLOBAL);
518 is.input = Tcl_GetStdChannel(TCL_STDIN);
519 Tcl_DecrRefCount(is.commandPtr);
520 TclNewObj(is.commandPtr);
521 Tcl_IncrRefCount(is.commandPtr);
522 if (code != TCL_OK) {
523 chan = Tcl_GetStdChannel(TCL_STDERR);
524 if (chan) {
525 Tcl_WriteObj(chan, Tcl_GetObjResult(interp));
526 Tcl_WriteChars(chan, "\n", 1);
527 }
528 } else if (is.tty) {
529 resultPtr = Tcl_GetObjResult(interp);
530 Tcl_IncrRefCount(resultPtr);
531 (void)Tcl_GetStringFromObj(resultPtr, &length);
532 chan = Tcl_GetStdChannel(TCL_STDOUT);
533 if ((length > 0) && chan) {
534 Tcl_WriteObj(chan, resultPtr);
535 Tcl_WriteChars(chan, "\n", 1);
536 }
537 Tcl_DecrRefCount(resultPtr);
538 }
539 } else { /* (mainLoopProc != NULL) */
540 /*
541 * If a main loop has been defined while running interactively, we
542 * want to start a fileevent based prompt by establishing a
543 * channel handler for stdin.
544 */
545
546 if (is.input) {
547 if (is.tty) {
548 Prompt(interp, &is);
549 }
550
551 Tcl_CreateChannelHandler(is.input, TCL_READABLE,
552 StdinProc, &is);
553 }
554
555 mainLoopProc();
556 Tcl_SetMainLoop(NULL);
557
558 if (is.input) {
559 Tcl_DeleteChannelHandler(is.input, StdinProc, &is);
560 }
561 is.input = Tcl_GetStdChannel(TCL_STDIN);
562 }
563
564 /*
565 * This code here only for the (unsupported and deprecated) [checkmem]
566 * command.
567 */
568
569 #ifdef TCL_MEM_DEBUG
570 if (tclMemDumpFileName != NULL) {
571 Tcl_SetMainLoop(NULL);
572 Tcl_DeleteInterp(interp);
573 }
574 #endif /* TCL_MEM_DEBUG */
575 }
576
577 done:
578 mainLoopProc = TclGetMainLoop();
579 if ((exitCode == 0) && mainLoopProc && !Tcl_LimitExceeded(interp)) {
580 /*
581 * If everything has gone OK so far, call the main loop proc, if it
582 * exists. Packages (like Tk) can set it to start processing events at
583 * this point.
584 */
585
586 mainLoopProc();
587 Tcl_SetMainLoop(NULL);
588 }
589 if (is.commandPtr != NULL) {
590 Tcl_DecrRefCount(is.commandPtr);
591 }
592
593 /*
594 * Rather than calling exit, invoke the "exit" command so that users can
595 * replace "exit" with some other command to do additional cleanup on
596 * exit. The Tcl_EvalObjEx call should never return.
597 */
598
599 if (!Tcl_InterpDeleted(interp) && !Tcl_LimitExceeded(interp)) {
600 Tcl_Obj *cmd = Tcl_ObjPrintf("exit %d", exitCode);
601
602 Tcl_IncrRefCount(cmd);
603 Tcl_EvalObjEx(interp, cmd, TCL_EVAL_GLOBAL);
604 Tcl_DecrRefCount(cmd);
605 }
606
607 /*
608 * If Tcl_EvalObjEx returns, trying to eval [exit], something unusual is
609 * happening. Maybe interp has been deleted; maybe [exit] was redefined,
610 * maybe we've blown up because of an exceeded limit. We still want to
611 * cleanup and exit.
612 */
613
614 Tcl_Exit(exitCode);
615 }
616
617 #if (TCL_MAJOR_VERSION == 8) && !defined(UNICODE)
618 #undef Tcl_Main
619 extern DLLEXPORT void
620 Tcl_Main(
621 int argc, /* Number of arguments. */
622 char **argv, /* Array of argument strings. */
623 Tcl_AppInitProc *appInitProc)
624 /* Application-specific initialization
625 * function to call after most initialization
626 * but before starting to execute commands. */
627 {
628 Tcl_MainEx(argc, argv, appInitProc, Tcl_CreateInterp());
629 }
630 #endif /* TCL_MAJOR_VERSION == 8 && !UNICODE */
631
632 #if !defined(_WIN32) || defined(UNICODE)
633
634 /*
635 *---------------------------------------------------------------
636 *
637 * Tcl_SetMainLoop --
638 *
639 * Sets an alternative main loop function.
640 *
641 * Results:
642 * None.
643 *
644 * Side effects:
645 * This function will be called before Tcl exits, allowing for the
646 * creation of an event loop.
647 *
648 *---------------------------------------------------------------
649 */
650
651 void
652 Tcl_SetMainLoop(
653 Tcl_MainLoopProc *proc)
654 {
655 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
656
657 tsdPtr->mainLoopProc = proc;
658 }
659
660 /*
661 *---------------------------------------------------------------
662 *
663 * TclGetMainLoop --
664 *
665 * Returns the current alternative main loop function.
666 *
667 * Results:
668 * Returns the previously defined main loop function, or NULL to indicate
669 * that no such function has been installed and standard tclsh behaviour
670 * (i.e., exit once the script is evaluated if not interactive) is
671 * requested..
672 *
673 * Side effects:
674 * None (other than possible creation of this file's TSD block).
675 *
676 *---------------------------------------------------------------
677 */
678
679 Tcl_MainLoopProc *
680 TclGetMainLoop(void)
681 {
682 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
683
684 return tsdPtr->mainLoopProc;
685 }
686
687 /*
688 *----------------------------------------------------------------------
689 *
690 * TclFullFinalizationRequested --
691 *
692 * This function returns true when either -DPURIFY is specified, or the
693 * environment variable TCL_FINALIZE_ON_EXIT is set and not "0". This
694 * predicate is called at places affecting the exit sequence, so that the
695 * default behavior is a fast and deadlock-free exit, and the modified
696 * behavior is a more thorough finalization for debugging purposes (leak
697 * hunting etc).
698 *
699 * Results:
700 * A boolean.
701 *
702 *----------------------------------------------------------------------
703 */
704
705 MODULE_SCOPE int
706 TclFullFinalizationRequested(void)
707 {
708 #ifdef PURIFY
709 return 1;
710 #else
711 const char *fin;
712 Tcl_DString ds;
713 int finalize = 0;
714
715 fin = TclGetEnv("TCL_FINALIZE_ON_EXIT", &ds);
716 finalize = ((fin != NULL) && strcmp(fin, "0"));
717 if (fin != NULL) {
718 Tcl_DStringFree(&ds);
719 }
720 return finalize;
721 #endif /* PURIFY */
722 }
723 #endif /* UNICODE */
724
725 /*
726 *----------------------------------------------------------------------
727 *
728 * StdinProc --
729 *
730 * This function is invoked by the event dispatcher whenever standard
731 * input becomes readable. It grabs the next line of input characters,
732 * adds them to a command being assembled, and executes the command if
733 * it's complete.
734 *
735 * Results:
736 * None.
737 *
738 * Side effects:
739 * Could be almost arbitrary, depending on the command that's typed.
740 *
741 *----------------------------------------------------------------------
742 */
743
744 static void
745 StdinProc(
746 ClientData clientData, /* The state of interactive cmd line */
747 int mask) /* Not used. */
748 {
749 int code;
750 int length;
751 InteractiveState *isPtr = (InteractiveState *)clientData;
752 Tcl_Channel chan = isPtr->input;
753 Tcl_Obj *commandPtr = isPtr->commandPtr;
754 Tcl_Interp *interp = isPtr->interp;
755 (void)mask;
756
757 if (Tcl_IsShared(commandPtr)) {
758 Tcl_DecrRefCount(commandPtr);
759 commandPtr = Tcl_DuplicateObj(commandPtr);
760 Tcl_IncrRefCount(commandPtr);
761 }
762 length = Tcl_GetsObj(chan, commandPtr);
763 if (length < 0) {
764 if (Tcl_InputBlocked(chan)) {
765 return;
766 }
767 if (isPtr->tty) {
768 /*
769 * Would be better to find a way to exit the mainLoop? Or perhaps
770 * evaluate [exit]? Leaving as is for now due to compatibility
771 * concerns.
772 */
773
774 Tcl_Exit(0);
775 }
776 Tcl_DeleteChannelHandler(chan, StdinProc, isPtr);
777 return;
778 }
779
780 if (Tcl_IsShared(commandPtr)) {
781 Tcl_DecrRefCount(commandPtr);
782 commandPtr = Tcl_DuplicateObj(commandPtr);
783 Tcl_IncrRefCount(commandPtr);
784 }
785 Tcl_AppendToObj(commandPtr, "\n", 1);
786 if (!TclObjCommandComplete(commandPtr)) {
787 isPtr->prompt = PROMPT_CONTINUE;
788 goto prompt;
789 }
790 isPtr->prompt = PROMPT_START;
791 (void)Tcl_GetStringFromObj(commandPtr, &length);
792 Tcl_SetObjLength(commandPtr, --length);
793
794 /*
795 * Disable the stdin channel handler while evaluating the command;
796 * otherwise if the command re-enters the event loop we might process
797 * commands from stdin before the current command is finished. Among other
798 * things, this will trash the text of the command being evaluated.
799 */
800
801 Tcl_CreateChannelHandler(chan, 0, StdinProc, isPtr);
802 code = Tcl_RecordAndEvalObj(interp, commandPtr, TCL_EVAL_GLOBAL);
803 isPtr->input = chan = Tcl_GetStdChannel(TCL_STDIN);
804 Tcl_DecrRefCount(commandPtr);
805 TclNewObj(commandPtr);
806 isPtr->commandPtr = commandPtr;
807 Tcl_IncrRefCount(commandPtr);
808 if (chan != NULL) {
809 Tcl_CreateChannelHandler(chan, TCL_READABLE, StdinProc, isPtr);
810 }
811 if (code != TCL_OK) {
812 chan = Tcl_GetStdChannel(TCL_STDERR);
813
814 if (chan != NULL) {
815 Tcl_WriteObj(chan, Tcl_GetObjResult(interp));
816 Tcl_WriteChars(chan, "\n", 1);
817 }
818 } else if (isPtr->tty) {
819 Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
820 chan = Tcl_GetStdChannel(TCL_STDOUT);
821
822 Tcl_IncrRefCount(resultPtr);
823 (void)Tcl_GetStringFromObj(resultPtr, &length);
824 if ((length > 0) && (chan != NULL)) {
825 Tcl_WriteObj(chan, resultPtr);
826 Tcl_WriteChars(chan, "\n", 1);
827 }
828 Tcl_DecrRefCount(resultPtr);
829 }
830
831 /*
832 * If a tty stdin is still around, output a prompt.
833 */
834
835 prompt:
836 if (isPtr->tty && (isPtr->input != NULL)) {
837 Prompt(interp, isPtr);
838 isPtr->input = Tcl_GetStdChannel(TCL_STDIN);
839 }
840 }
841
842 /*
843 *----------------------------------------------------------------------
844 *
845 * Prompt --
846 *
847 * Issue a prompt on standard output, or invoke a script to issue the
848 * prompt.
849 *
850 * Results:
851 * None.
852 *
853 * Side effects:
854 * A prompt gets output, and a Tcl script may be evaluated in interp.
855 *
856 *----------------------------------------------------------------------
857 */
858
859 static void
860 Prompt(
861 Tcl_Interp *interp, /* Interpreter to use for prompting. */
862 InteractiveState *isPtr) /* InteractiveState. Filled with PROMPT_NONE
863 * after a prompt is printed. */
864 {
865 Tcl_Obj *promptCmdPtr;
866 int code;
867 Tcl_Channel chan;
868
869 if (isPtr->prompt == PROMPT_NONE) {
870 return;
871 }
872
873 promptCmdPtr = Tcl_GetVar2Ex(interp,
874 (isPtr->prompt==PROMPT_CONTINUE ? "tcl_prompt2" : "tcl_prompt1"),
875 NULL, TCL_GLOBAL_ONLY);
876
877 if (Tcl_InterpDeleted(interp)) {
878 return;
879 }
880 if (promptCmdPtr == NULL) {
881 defaultPrompt:
882 if (isPtr->prompt == PROMPT_START) {
883 chan = Tcl_GetStdChannel(TCL_STDOUT);
884 if (chan != NULL) {
885 Tcl_WriteChars(chan, DEFAULT_PRIMARY_PROMPT,
886 sizeof(DEFAULT_PRIMARY_PROMPT) - 1);
887 }
888 }
889 } else {
890 code = Tcl_EvalObjEx(interp, promptCmdPtr, TCL_EVAL_GLOBAL);
891 if (code != TCL_OK) {
892 Tcl_AddErrorInfo(interp,
893 "\n (script that generates prompt)");
894 chan = Tcl_GetStdChannel(TCL_STDERR);
895 if (chan != NULL) {
896 Tcl_WriteObj(chan, Tcl_GetObjResult(interp));
897 Tcl_WriteChars(chan, "\n", 1);
898 }
899 goto defaultPrompt;
900 }
901 }
902
903 chan = Tcl_GetStdChannel(TCL_STDOUT);
904 if (chan != NULL) {
905 Tcl_Flush(chan);
906 }
907 isPtr->prompt = PROMPT_NONE;
908 }
909
910 /*
911 *----------------------------------------------------------------------
912 *
913 * FreeMainInterp --
914 *
915 * Exit handler used to cleanup the main interpreter and ancillary
916 * startup script storage at exit.
917 *
918 *----------------------------------------------------------------------
919 */
920
921 static void
922 FreeMainInterp(
923 ClientData clientData)
924 {
925 Tcl_Interp *interp = (Tcl_Interp *)clientData;
926
927 /*if (TclInExit()) return;*/
928
929 if (!Tcl_InterpDeleted(interp)) {
930 Tcl_DeleteInterp(interp);
931 }
932 Tcl_SetStartupScript(NULL, NULL);
933 Tcl_Release(interp);
934 }
935
936 /*
937 * Local Variables:
938 * mode: c
939 * c-basic-offset: 4
940 * fill-column: 78
941 * End:
942 */