Debian Codegraph @

generic/tclProc.c

raw
1 /*
2 * tclProc.c --
3 *
4 * This file contains routines that implement Tcl procedures, including
5 * the "proc" and "uplevel" commands.
6 *
7 * Copyright (c) 1987-1993 The Regents of the University of California.
8 * Copyright (c) 1994-1998 Sun Microsystems, Inc.
9 * Copyright (c) 2004-2006 Miguel Sofer
10 * Copyright (c) 2007 Daniel A. Steffen <[email protected]>
11 *
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 */
15
16 #include "tclInt.h"
17 #include "tclCompile.h"
18
19 /*
20 * Variables that are part of the [apply] command implementation and which
21 * have to be passed to the other side of the NRE call.
22 */
23
24 typedef struct {
25 Command cmd;
26 ExtraFrameInfo efi;
27 } ApplyExtraData;
28
29 /*
30 * Prototypes for static functions in this file
31 */
32
33 static void DupLambdaInternalRep(Tcl_Obj *objPtr,
34 Tcl_Obj *copyPtr);
35 static void FreeLambdaInternalRep(Tcl_Obj *objPtr);
36 static int InitArgsAndLocals(Tcl_Interp *interp,
37 Tcl_Obj *procNameObj, int skip);
38 static void InitResolvedLocals(Tcl_Interp *interp,
39 ByteCode *codePtr, Var *defPtr,
40 Namespace *nsPtr);
41 static void InitLocalCache(Proc *procPtr);
42 static void ProcBodyDup(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr);
43 static void ProcBodyFree(Tcl_Obj *objPtr);
44 static int ProcWrongNumArgs(Tcl_Interp *interp, int skip);
45 static void MakeProcError(Tcl_Interp *interp,
46 Tcl_Obj *procNameObj);
47 static void MakeLambdaError(Tcl_Interp *interp,
48 Tcl_Obj *procNameObj);
49 static int SetLambdaFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr);
50
51 static Tcl_NRPostProc ApplyNR2;
52 static Tcl_NRPostProc InterpProcNR2;
53 static Tcl_NRPostProc Uplevel_Callback;
54
55 /*
56 * The ProcBodyObjType type
57 */
58
59 const Tcl_ObjType tclProcBodyType = {
60 "procbody", /* name for this type */
61 ProcBodyFree, /* FreeInternalRep function */
62 ProcBodyDup, /* DupInternalRep function */
63 NULL, /* UpdateString function; Tcl_GetString and
64 * Tcl_GetStringFromObj should panic
65 * instead. */
66 NULL /* SetFromAny function; Tcl_ConvertToType
67 * should panic instead. */
68 };
69
70 /*
71 * The [upvar]/[uplevel] level reference type. Uses the longValue field
72 * to remember the integer value of a parsed #<integer> format.
73 *
74 * Uses the default behaviour throughout, and never disposes of the string
75 * rep; it's just a cache type.
76 */
77
78 static const Tcl_ObjType levelReferenceType = {
79 "levelReference",
80 NULL, NULL, NULL, NULL
81 };
82
83 /*
84 * The type of lambdas. Note that every lambda will *always* have a string
85 * representation.
86 *
87 * Internally, ptr1 is a pointer to a Proc instance that is not bound to a
88 * command name, and ptr2 is a pointer to the namespace that the Proc instance
89 * will execute within. IF YOU CHANGE THIS, CHECK IN tclDisassemble.c TOO.
90 */
91
92 const Tcl_ObjType tclLambdaType = {
93 "lambdaExpr", /* name */
94 FreeLambdaInternalRep, /* freeIntRepProc */
95 DupLambdaInternalRep, /* dupIntRepProc */
96 NULL, /* updateStringProc */
97 SetLambdaFromAny /* setFromAnyProc */
98 };
99
100 /*
101 *----------------------------------------------------------------------
102 *
103 * Tcl_ProcObjCmd --
104 *
105 * This object-based function is invoked to process the "proc" Tcl
106 * command. See the user documentation for details on what it does.
107 *
108 * Results:
109 * A standard Tcl object result value.
110 *
111 * Side effects:
112 * A new procedure gets created.
113 *
114 *----------------------------------------------------------------------
115 */
116
117 #undef TclObjInterpProc
118 int
119 Tcl_ProcObjCmd(
120 ClientData dummy, /* Not used. */
121 Tcl_Interp *interp, /* Current interpreter. */
122 int objc, /* Number of arguments. */
123 Tcl_Obj *const objv[]) /* Argument objects. */
124 {
125 Interp *iPtr = (Interp *) interp;
126 Proc *procPtr;
127 const char *procName;
128 const char *simpleName, *procArgs, *procBody;
129 Namespace *nsPtr, *altNsPtr, *cxtNsPtr;
130 Tcl_Command cmd;
131
132 if (objc != 4) {
133 Tcl_WrongNumArgs(interp, 1, objv, "name args body");
134 return TCL_ERROR;
135 }
136
137 /*
138 * Determine the namespace where the procedure should reside. Unless the
139 * command name includes namespace qualifiers, this will be the current
140 * namespace.
141 */
142
143 procName = TclGetString(objv[1]);
144 TclGetNamespaceForQualName(interp, procName, NULL, 0,
145 &nsPtr, &altNsPtr, &cxtNsPtr, &simpleName);
146
147 if (nsPtr == NULL) {
148 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
149 "can't create procedure \"%s\": unknown namespace",
150 procName));
151 Tcl_SetErrorCode(interp, "TCL", "VALUE", "COMMAND", (char *)NULL);
152 return TCL_ERROR;
153 }
154 if (simpleName == NULL) {
155 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
156 "can't create procedure \"%s\": bad procedure name",
157 procName));
158 Tcl_SetErrorCode(interp, "TCL", "VALUE", "COMMAND", (char *)NULL);
159 return TCL_ERROR;
160 }
161
162 /*
163 * Create the data structure to represent the procedure.
164 */
165
166 if (TclCreateProc(interp, nsPtr, simpleName, objv[2],
167 objv[3], &procPtr) != TCL_OK) {
168 Tcl_AddErrorInfo(interp, "\n (creating proc \"");
169 Tcl_AddErrorInfo(interp, simpleName);
170 Tcl_AddErrorInfo(interp, "\")");
171 return TCL_ERROR;
172 }
173
174 cmd = TclNRCreateCommandInNs(interp, simpleName, (Tcl_Namespace *) nsPtr,
175 TclObjInterpProc, TclNRInterpProc, procPtr, TclProcDeleteProc);
176
177 /*
178 * Now initialize the new procedure's cmdPtr field. This will be used
179 * later when the procedure is called to determine what namespace the
180 * procedure will run in. This will be different than the current
181 * namespace if the proc was renamed into a different namespace.
182 */
183
184 procPtr->cmdPtr = (Command *) cmd;
185
186 /*
187 * TIP #280: Remember the line the procedure body is starting on. In a
188 * bytecode context we ask the engine to provide us with the necessary
189 * information. This is for the initialization of the byte code compiler
190 * when the body is used for the first time.
191 *
192 * This code is nearly identical to the #280 code in SetLambdaFromAny, see
193 * this file. The differences are the different index of the body in the
194 * line array of the context, and the lambda code requires some special
195 * processing. Find a way to factor the common elements into a single
196 * function.
197 */
198
199 if (iPtr->cmdFramePtr) {
200 CmdFrame *contextPtr = (CmdFrame *)TclStackAlloc(interp, sizeof(CmdFrame));
201
202 *contextPtr = *iPtr->cmdFramePtr;
203 if (contextPtr->type == TCL_LOCATION_BC) {
204 /*
205 * Retrieve source information from the bytecode, if possible. If
206 * the information is retrieved successfully, context.type will be
207 * TCL_LOCATION_SOURCE and the reference held by
208 * context.data.eval.path will be counted.
209 */
210
211 TclGetSrcInfoForPc(contextPtr);
212 } else if (contextPtr->type == TCL_LOCATION_SOURCE) {
213 /*
214 * The copy into 'context' up above has created another reference
215 * to 'context.data.eval.path'; account for it.
216 */
217
218 Tcl_IncrRefCount(contextPtr->data.eval.path);
219 }
220
221 if (contextPtr->type == TCL_LOCATION_SOURCE) {
222 /*
223 * We can account for source location within a proc only if the
224 * proc body was not created by substitution.
225 */
226
227 if (contextPtr->line
228 && (contextPtr->nline >= 4) && (contextPtr->line[3] >= 0)) {
229 int isNew;
230 Tcl_HashEntry *hePtr;
231 CmdFrame *cfPtr = (CmdFrame *)ckalloc(sizeof(CmdFrame));
232
233 cfPtr->level = -1;
234 cfPtr->type = contextPtr->type;
235 cfPtr->line = (int *)ckalloc(sizeof(int));
236 cfPtr->line[0] = contextPtr->line[3];
237 cfPtr->nline = 1;
238 cfPtr->framePtr = NULL;
239 cfPtr->nextPtr = NULL;
240
241 cfPtr->data.eval.path = contextPtr->data.eval.path;
242 Tcl_IncrRefCount(cfPtr->data.eval.path);
243
244 cfPtr->cmd = NULL;
245 cfPtr->len = 0;
246
247 hePtr = Tcl_CreateHashEntry(iPtr->linePBodyPtr,
248 (char *)procPtr, &isNew);
249 if (!isNew) {
250 /*
251 * Get the old command frame and release it. See also
252 * TclProcCleanupProc in this file. Currently it seems as
253 * if only the procbodytest::proc command of the testsuite
254 * is able to trigger this situation.
255 */
256
257 CmdFrame *cfOldPtr = (CmdFrame *)Tcl_GetHashValue(hePtr);
258
259 if (cfOldPtr->type == TCL_LOCATION_SOURCE) {
260 Tcl_DecrRefCount(cfOldPtr->data.eval.path);
261 cfOldPtr->data.eval.path = NULL;
262 }
263 ckfree(cfOldPtr->line);
264 cfOldPtr->line = NULL;
265 ckfree(cfOldPtr);
266 }
267 Tcl_SetHashValue(hePtr, cfPtr);
268 }
269
270 /*
271 * 'contextPtr' is going out of scope; account for the reference
272 * that it's holding to the path name.
273 */
274
275 Tcl_DecrRefCount(contextPtr->data.eval.path);
276 contextPtr->data.eval.path = NULL;
277 }
278 TclStackFree(interp, contextPtr);
279 }
280
281 /*
282 * Optimize for no-op procs: if the body is not precompiled (like a TclPro
283 * procbody), and the argument list is just "args" and the body is empty,
284 * define a compileProc to compile a no-op.
285 *
286 * Notes:
287 * - cannot be done for any argument list without having different
288 * compiled/not-compiled behaviour in the "wrong argument #" case, or
289 * making this code much more complicated. In any case, it doesn't
290 * seem to make a lot of sense to verify the number of arguments we
291 * are about to ignore ...
292 * - could be enhanced to handle also non-empty bodies that contain only
293 * comments; however, parsing the body will slow down the compilation
294 * of all procs whose argument list is just _args_
295 */
296
297 if (objv[3]->typePtr == &tclProcBodyType) {
298 goto done;
299 }
300
301 procArgs = TclGetString(objv[2]);
302
303 while (*procArgs == ' ') {
304 procArgs++;
305 }
306
307 if ((procArgs[0] == 'a') && (strncmp(procArgs, "args", 4) == 0)) {
308 int numBytes;
309
310 procArgs +=4;
311 while (*procArgs != '\0') {
312 if (*procArgs != ' ') {
313 goto done;
314 }
315 procArgs++;
316 }
317
318 /*
319 * The argument list is just "args"; check the body
320 */
321
322 procBody = TclGetStringFromObj(objv[3], &numBytes);
323 if (TclParseAllWhiteSpace(procBody, numBytes) < numBytes) {
324 goto done;
325 }
326
327 /*
328 * The body is just spaces: link the compileProc
329 */
330
331 ((Command *) cmd)->compileProc = TclCompileNoOp;
332 }
333
334 done:
335 return TCL_OK;
336 }
337
338 /*
339 *----------------------------------------------------------------------
340 *
341 * TclCreateProc --
342 *
343 * Creates the data associated with a Tcl procedure definition. This
344 * function knows how to handle two types of body objects: strings and
345 * procbody. Strings are the traditional (and common) value for bodies,
346 * procbody are values created by extensions that have loaded a
347 * previously compiled script.
348 *
349 * Results:
350 * Returns TCL_OK on success, along with a pointer to a Tcl procedure
351 * definition in procPtrPtr where the cmdPtr field is not initialised.
352 * This definition should be freed by calling TclProcCleanupProc() when
353 * it is no longer needed. Returns TCL_ERROR if anything goes wrong.
354 *
355 * Side effects:
356 * If anything goes wrong, this function returns an error message in the
357 * interpreter.
358 *
359 *----------------------------------------------------------------------
360 */
361
362 int
363 TclCreateProc(
364 Tcl_Interp *interp, /* Interpreter containing proc. */
365 Namespace *nsPtr, /* Namespace containing this proc. */
366 const char *procName, /* Unqualified name of this proc. */
367 Tcl_Obj *argsPtr, /* Description of arguments. */
368 Tcl_Obj *bodyPtr, /* Command body. */
369 Proc **procPtrPtr) /* Returns: pointer to proc data. */
370 {
371 Interp *iPtr = (Interp *) interp;
372
373 Proc *procPtr;
374 int i, result, numArgs;
375 CompiledLocal *localPtr = NULL;
376 Tcl_Obj **argArray;
377 int precompiled = 0;
378
379 if (bodyPtr->typePtr == &tclProcBodyType) {
380 /*
381 * Because the body is a TclProProcBody, the actual body is already
382 * compiled, and it is not shared with anyone else, so it's OK not to
383 * unshare it (as a matter of fact, it is bad to unshare it, because
384 * there may be no source code).
385 *
386 * We don't create and initialize a Proc structure for the procedure;
387 * rather, we use what is in the body object. We increment the ref
388 * count of the Proc struct since the command (soon to be created)
389 * will be holding a reference to it.
390 */
391
392 procPtr = bodyPtr->internalRep.twoPtrValue.ptr1;
393 procPtr->iPtr = iPtr;
394 procPtr->refCount++;
395 precompiled = 1;
396 } else {
397 /*
398 * If the procedure's body object is shared because its string value
399 * is identical to, e.g., the body of another procedure, we must
400 * create a private copy for this procedure to use. Such sharing of
401 * procedure bodies is rare but can cause problems. A procedure body
402 * is compiled in a context that includes the number of "slots"
403 * allocated by the compiler for local variables. There is a local
404 * variable slot for each formal parameter (the
405 * "procPtr->numCompiledLocals = numArgs" assignment below). This
406 * means that the same code can not be shared by two procedures that
407 * have a different number of arguments, even if their bodies are
408 * identical. Note that we don't use Tcl_DuplicateObj since we would
409 * not want any bytecode internal representation.
410 */
411
412 if (Tcl_IsShared(bodyPtr)) {
413 const char *bytes;
414 int length;
415 Tcl_Obj *sharedBodyPtr = bodyPtr;
416
417 bytes = TclGetStringFromObj(bodyPtr, &length);
418 bodyPtr = Tcl_NewStringObj(bytes, length);
419
420 /*
421 * TIP #280.
422 * Ensure that the continuation line data for the original body is
423 * not lost and applies to the new body as well.
424 */
425
426 TclContinuationsCopy(bodyPtr, sharedBodyPtr);
427 }
428
429 /*
430 * Create and initialize a Proc structure for the procedure. We
431 * increment the ref count of the procedure's body object since there
432 * will be a reference to it in the Proc structure.
433 */
434
435 Tcl_IncrRefCount(bodyPtr);
436
437 procPtr = (Proc *)ckalloc(sizeof(Proc));
438 procPtr->iPtr = iPtr;
439 procPtr->refCount = 1;
440 procPtr->bodyPtr = bodyPtr;
441 procPtr->numArgs = 0; /* Actual argument count is set below. */
442 procPtr->numCompiledLocals = 0;
443 procPtr->firstLocalPtr = NULL;
444 procPtr->lastLocalPtr = NULL;
445 }
446
447 /*
448 * Break up the argument list into argument specifiers, then process each
449 * argument specifier. If the body is precompiled, processing is limited
450 * to checking that the parsed argument is consistent with the one stored
451 * in the Proc.
452 */
453
454 result = TclListObjGetElements(interp, argsPtr, &numArgs, &argArray);
455 if (result != TCL_OK) {
456 goto procError;
457 }
458
459 if (precompiled) {
460 if (numArgs > procPtr->numArgs) {
461 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
462 "procedure \"%s\": arg list contains %d entries, "
463 "precompiled header expects %d", procName, numArgs,
464 procPtr->numArgs));
465 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
466 "BYTECODELIES", (char *)NULL);
467 goto procError;
468 }
469 localPtr = procPtr->firstLocalPtr;
470 } else {
471 procPtr->numArgs = numArgs;
472 procPtr->numCompiledLocals = numArgs;
473 }
474
475 for (i = 0; i < numArgs; i++) {
476 const char *argname, *p, *last;
477 int fieldCount, nameLength;
478 Tcl_Obj **fieldValues;
479
480 /*
481 * Now divide the specifier up into name and default.
482 */
483
484 result = TclListObjGetElements(interp, argArray[i], &fieldCount,
485 &fieldValues);
486 if (result != TCL_OK) {
487 goto procError;
488 }
489 if (fieldCount > 2) {
490 Tcl_Obj *errorObj = Tcl_NewStringObj(
491 "too many fields in argument specifier \"", -1);
492 Tcl_AppendObjToObj(errorObj, argArray[i]);
493 Tcl_AppendToObj(errorObj, "\"", -1);
494 Tcl_SetObjResult(interp, errorObj);
495 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
496 "FORMALARGUMENTFORMAT", (char *)NULL);
497 goto procError;
498 }
499 if ((fieldCount == 0) || (Tcl_GetCharLength(fieldValues[0]) == 0)) {
500 Tcl_SetObjResult(interp, Tcl_NewStringObj(
501 "argument with no name", -1));
502 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
503 "FORMALARGUMENTFORMAT", (char *)NULL);
504 goto procError;
505 }
506
507 /*
508 * Check that the formal parameter name is a scalar.
509 */
510
511 p = argname = TclGetStringFromObj(fieldValues[0], &nameLength);
512 last = argname + nameLength;
513 while (p < last) {
514 if (*p == '(') {
515 if (last[-1] == ')') { /* We have an array element. */
516 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
517 "formal parameter \"%s\" is an array element",
518 TclGetString(fieldValues[0])));
519 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
520 "FORMALARGUMENTFORMAT", (char *)NULL);
521 goto procError;
522 }
523 } else if (p[0] == ':' && p[1] == ':') {
524 Tcl_Obj *errorObj = Tcl_NewStringObj(
525 "formal parameter \"", -1);
526 Tcl_AppendObjToObj(errorObj, fieldValues[0]);
527 Tcl_AppendToObj(errorObj, "\" is not a simple name", -1);
528 Tcl_SetObjResult(interp, errorObj);
529 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
530 "FORMALARGUMENTFORMAT", (char *)NULL);
531 goto procError;
532 }
533 p++;
534 }
535
536 if (precompiled) {
537 /*
538 * Compare the parsed argument with the stored one. Note that the
539 * only flag value that makes sense at this point is VAR_ARGUMENT
540 * (its value was kept the same as pre VarReform to simplify
541 * tbcload's processing of older byetcodes).
542 *
543 * The only other flag value that is important to retrieve from
544 * precompiled procs is VAR_TEMPORARY (also unchanged). It is
545 * needed later when retrieving the variable names.
546 */
547
548 if ((localPtr->nameLength != nameLength)
549 || (memcmp(localPtr->name, argname, nameLength) != 0)
550 || (localPtr->frameIndex != i)
551 || !(localPtr->flags & VAR_ARGUMENT)
552 || (localPtr->defValuePtr == NULL && fieldCount == 2)
553 || (localPtr->defValuePtr != NULL && fieldCount != 2)) {
554 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
555 "procedure \"%s\": formal parameter %d is "
556 "inconsistent with precompiled body", procName, i));
557 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
558 "BYTECODELIES", (char *)NULL);
559 goto procError;
560 }
561
562 /*
563 * Compare the default value if any.
564 */
565
566 if (localPtr->defValuePtr != NULL) {
567 int tmpLength, valueLength;
568 const char *tmpPtr = TclGetStringFromObj(localPtr->defValuePtr,
569 &tmpLength);
570 const char *value = TclGetStringFromObj(fieldValues[1],
571 &valueLength);
572
573 if ((valueLength != tmpLength)
574 || memcmp(value, tmpPtr, tmpLength) != 0
575 ) {
576 Tcl_Obj *errorObj = Tcl_ObjPrintf(
577 "procedure \"%s\": formal parameter \"", procName);
578 Tcl_AppendObjToObj(errorObj, fieldValues[0]);
579 Tcl_AppendToObj(errorObj, "\" has "
580 "default value inconsistent with precompiled body", -1);
581 Tcl_SetObjResult(interp, errorObj);
582 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
583 "BYTECODELIES", (char *)NULL);
584 goto procError;
585 }
586 }
587 if ((i == numArgs - 1)
588 && (localPtr->nameLength == 4)
589 && (localPtr->name[0] == 'a')
590 && (strcmp(localPtr->name, "args") == 0)) {
591 localPtr->flags |= VAR_IS_ARGS;
592 }
593
594 localPtr = localPtr->nextPtr;
595 } else {
596 /*
597 * Allocate an entry in the runtime procedure frame's array of
598 * local variables for the argument.
599 */
600
601 localPtr = (CompiledLocal *)ckalloc(
602 TclOffset(CompiledLocal, name) + 1U + fieldValues[0]->length);
603 if (procPtr->firstLocalPtr == NULL) {
604 procPtr->firstLocalPtr = procPtr->lastLocalPtr = localPtr;
605 } else {
606 procPtr->lastLocalPtr->nextPtr = localPtr;
607 procPtr->lastLocalPtr = localPtr;
608 }
609 localPtr->nextPtr = NULL;
610 localPtr->nameLength = nameLength;
611 localPtr->frameIndex = i;
612 localPtr->flags = VAR_ARGUMENT;
613 localPtr->resolveInfo = NULL;
614
615 if (fieldCount == 2) {
616 localPtr->defValuePtr = fieldValues[1];
617 Tcl_IncrRefCount(localPtr->defValuePtr);
618 } else {
619 localPtr->defValuePtr = NULL;
620 }
621 memcpy(localPtr->name, argname, fieldValues[0]->length + 1);
622 if ((i == numArgs - 1)
623 && (localPtr->nameLength == 4)
624 && (localPtr->name[0] == 'a')
625 && (memcmp(localPtr->name, "args", 4) == 0)) {
626 localPtr->flags |= VAR_IS_ARGS;
627 }
628 }
629 }
630
631 *procPtrPtr = procPtr;
632 return TCL_OK;
633
634 procError:
635 if (precompiled) {
636 procPtr->refCount--;
637 } else {
638 Tcl_DecrRefCount(bodyPtr);
639 while (procPtr->firstLocalPtr != NULL) {
640 localPtr = procPtr->firstLocalPtr;
641 procPtr->firstLocalPtr = localPtr->nextPtr;
642
643 if (localPtr->defValuePtr != NULL) {
644 Tcl_DecrRefCount(localPtr->defValuePtr);
645 }
646
647 ckfree(localPtr);
648 }
649 ckfree(procPtr);
650 }
651 return TCL_ERROR;
652 }
653
654 /*
655 *----------------------------------------------------------------------
656 *
657 * TclGetFrame --
658 *
659 * Given a description of a procedure frame, such as the first argument
660 * to an "uplevel" or "upvar" command, locate the call frame for the
661 * appropriate level of procedure.
662 *
663 * Results:
664 * The return value is -1 if an error occurred in finding the frame (in
665 * this case an error message is left in the interp's result). 1 is
666 * returned if string was either a number or a number preceded by "#" and
667 * it specified a valid frame. 0 is returned if string isn't one of the
668 * two things above (in this case, the lookup acts as if string were
669 * "1"). The variable pointed to by framePtrPtr is filled in with the
670 * address of the desired frame (unless an error occurs, in which case it
671 * isn't modified).
672 *
673 * Side effects:
674 * None.
675 *
676 *----------------------------------------------------------------------
677 */
678
679 int
680 TclGetFrame(
681 Tcl_Interp *interp, /* Interpreter in which to find frame. */
682 const char *name, /* String describing frame. */
683 CallFrame **framePtrPtr) /* Store pointer to frame here (or NULL if
684 * global frame indicated). */
685 {
686 Interp *iPtr = (Interp *) interp;
687 int curLevel, level, result;
688 CallFrame *framePtr;
689
690 /*
691 * Parse string to figure out which level number to go to.
692 */
693
694 result = 1;
695 curLevel = iPtr->varFramePtr->level;
696 if (*name== '#') {
697 if (Tcl_GetInt(NULL, name+1, &level) != TCL_OK || level < 0) {
698 goto levelError;
699 }
700 } else if (isdigit(UCHAR(*name))) { /* INTL: digit */
701 if (Tcl_GetInt(NULL, name, &level) != TCL_OK) {
702 goto levelError;
703 }
704 level = curLevel - level;
705 } else {
706 /*
707 * (historical, TODO) If name does not contain a level (#0 or 1),
708 * TclGetFrame and Tcl_UpVar2 uses current level - 1
709 */
710 level = curLevel - 1;
711 result = 0;
712 name = "1"; /* be more consistent with TclObjGetFrame (error at top - 1) */
713 }
714
715 /*
716 * Figure out which frame to use, and return it to the caller.
717 */
718
719 for (framePtr = iPtr->varFramePtr; framePtr != NULL;
720 framePtr = framePtr->callerVarPtr) {
721 if (framePtr->level == level) {
722 break;
723 }
724 }
725 if (framePtr == NULL) {
726 goto levelError;
727 }
728
729 *framePtrPtr = framePtr;
730 return result;
731
732 levelError:
733 Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad level \"%s\"", name));
734 Tcl_SetErrorCode(interp, "TCL", "VALUE", "STACKLEVEL", (char *)NULL);
735 return -1;
736 }
737
738 /*
739 *----------------------------------------------------------------------
740 *
741 * TclObjGetFrame --
742 *
743 * Given a description of a procedure frame, such as the first argument
744 * to an "uplevel" or "upvar" command, locate the call frame for the
745 * appropriate level of procedure.
746 *
747 * Results:
748 * The return value is -1 if an error occurred in finding the frame (in
749 * this case an error message is left in the interp's result). 1 is
750 * returned if objPtr was either an int or an int preceded by "#" and
751 * it specified a valid frame. 0 is returned if objPtr isn't one of the
752 * two things above (in this case, the lookup acts as if objPtr were
753 * "1"). The variable pointed to by framePtrPtr is filled in with the
754 * address of the desired frame (unless an error occurs, in which case it
755 * isn't modified).
756 *
757 * Side effects:
758 * None.
759 *
760 *----------------------------------------------------------------------
761 */
762
763 int
764 TclObjGetFrame(
765 Tcl_Interp *interp, /* Interpreter in which to find frame. */
766 Tcl_Obj *objPtr, /* Object describing frame. */
767 CallFrame **framePtrPtr) /* Store pointer to frame here (or NULL if
768 * global frame indicated). */
769 {
770 Interp *iPtr = (Interp *) interp;
771 int curLevel, level, result;
772 const char *name = NULL;
773
774 /*
775 * Parse object to figure out which level number to go to.
776 */
777
778 result = 0;
779 curLevel = iPtr->varFramePtr->level;
780
781 /*
782 * Check for integer first, since that has potential to spare us
783 * a generation of a stringrep.
784 */
785
786 if (objPtr == NULL) {
787 /* Do nothing */
788 } else if (TCL_OK == Tcl_GetIntFromObj(NULL, objPtr, &level)
789 && (level >= 0)) {
790 level = curLevel - level;
791 result = 1;
792 } else if (objPtr->typePtr == &levelReferenceType) {
793 level = (int) objPtr->internalRep.longValue;
794 result = 1;
795 } else {
796 name = TclGetString(objPtr);
797 if (name[0] == '#') {
798 if (TCL_OK == Tcl_GetInt(NULL, name+1, &level) && level >= 0) {
799 TclFreeIntRep(objPtr);
800 objPtr->typePtr = &levelReferenceType;
801 objPtr->internalRep.longValue = level;
802 result = 1;
803 } else {
804 result = -1;
805 }
806 } else if (isdigit(UCHAR(name[0]))) { /* INTL: digit */
807 /*
808 * If this were an integer, we'd have succeeded already.
809 * Docs say we have to treat this as a 'bad level' error.
810 */
811 result = -1;
812 }
813 }
814
815 if (result == 0) {
816 level = curLevel - 1;
817 name = "1";
818 }
819 if (result != -1) {
820 if (level >= 0) {
821 CallFrame *framePtr;
822 for (framePtr = iPtr->varFramePtr; framePtr != NULL;
823 framePtr = framePtr->callerVarPtr) {
824 if (framePtr->level == level) {
825 *framePtrPtr = framePtr;
826 return result;
827 }
828 }
829 }
830 if (name == NULL) {
831 name = TclGetString(objPtr);
832 }
833 }
834
835 Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad level \"%s\"", name));
836 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "LEVEL", name, (char *)NULL);
837 return -1;
838 }
839
840 /*
841 *----------------------------------------------------------------------
842 *
843 * Tcl_UplevelObjCmd --
844 *
845 * This object function is invoked to process the "uplevel" Tcl command.
846 * See the user documentation for details on what it does.
847 *
848 * Results:
849 * A standard Tcl object result value.
850 *
851 * Side effects:
852 * See the user documentation.
853 *
854 *----------------------------------------------------------------------
855 */
856
857 static int
858 Uplevel_Callback(
859 ClientData data[],
860 Tcl_Interp *interp,
861 int result)
862 {
863 CallFrame *savedVarFramePtr = (CallFrame *)data[0];
864
865 if (result == TCL_ERROR) {
866 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
867 "\n (\"uplevel\" body line %d)", Tcl_GetErrorLine(interp)));
868 }
869
870 /*
871 * Restore the variable frame, and return.
872 */
873
874 ((Interp *)interp)->varFramePtr = savedVarFramePtr;
875 return result;
876 }
877
878 int
879 Tcl_UplevelObjCmd(
880 ClientData clientData,
881 Tcl_Interp *interp, /* Current interpreter. */
882 int objc, /* Number of arguments. */
883 Tcl_Obj *const objv[]) /* Argument objects. */
884 {
885 return Tcl_NRCallObjProc(interp, TclNRUplevelObjCmd, clientData, objc, objv);
886 }
887
888 int
889 TclNRUplevelObjCmd(
890 ClientData dummy, /* Not used. */
891 Tcl_Interp *interp, /* Current interpreter. */
892 int objc, /* Number of arguments. */
893 Tcl_Obj *const objv[]) /* Argument objects. */
894 {
895
896 Interp *iPtr = (Interp *) interp;
897 CmdFrame *invoker = NULL;
898 int word = 0;
899 int result;
900 CallFrame *savedVarFramePtr, *framePtr;
901 Tcl_Obj *objPtr;
902
903 if (objc < 2) {
904 /* to do
905 * simplify things by interpreting the argument as a command when there
906 * is only one argument. This requires a TIP since currently a single
907 * argument is interpreted as a level indicator if possible.
908 */
909 uplevelSyntax:
910 Tcl_WrongNumArgs(interp, 1, objv, "?level? command ?arg ...?");
911 return TCL_ERROR;
912 } else if (!TclHasStringRep(objv[1]) && objc == 2) {
913 int status ,llength;
914 status = TclListObjLength(interp, objv[1], &llength);
915 if (status == TCL_OK && llength > 1) {
916 /* the first argument can't interpreted as a level. Avoid
917 * generating a string representation of the script. */
918 result = TclGetFrame(interp, "1", &framePtr);
919 if (result == -1) {
920 return TCL_ERROR;
921 }
922 objc -= 1;
923 objv += 1;
924 goto havelevel;
925 }
926 }
927
928 /*
929 * Find the level to use for executing the command.
930 */
931
932 result = TclObjGetFrame(interp, objv[1], &framePtr);
933 if (result == -1) {
934 return TCL_ERROR;
935 }
936 objc -= result + 1;
937 if (objc == 0) {
938 goto uplevelSyntax;
939 }
940 objv += result + 1;
941
942 havelevel:
943
944 /*
945 * Modify the interpreter state to execute in the given frame.
946 */
947
948 savedVarFramePtr = iPtr->varFramePtr;
949 iPtr->varFramePtr = framePtr;
950
951 /*
952 * Execute the residual arguments as a command.
953 */
954
955 if (objc == 1) {
956 /*
957 * TIP #280. Make actual argument location available to eval'd script
958 */
959
960 TclArgumentGet(interp, objv[0], &invoker, &word);
961 objPtr = objv[0];
962
963 } else {
964 /*
965 * More than one argument: concatenate them together with spaces
966 * between, then evaluate the result. Tcl_EvalObjEx will delete the
967 * object when it decrements its refcount after eval'ing it.
968 */
969
970 objPtr = Tcl_ConcatObj(objc, objv);
971 }
972
973 TclNRAddCallback(interp, Uplevel_Callback, savedVarFramePtr, NULL, NULL,
974 NULL);
975 return TclNREvalObjEx(interp, objPtr, 0, invoker, word);
976 }
977
978 /*
979 *----------------------------------------------------------------------
980 *
981 * TclFindProc --
982 *
983 * Given the name of a procedure, return a pointer to the record
984 * describing the procedure. The procedure will be looked up using the
985 * usual rules: first in the current namespace and then in the global
986 * namespace.
987 *
988 * Results:
989 * NULL is returned if the name doesn't correspond to any procedure.
990 * Otherwise, the return value is a pointer to the procedure's record. If
991 * the name is found but refers to an imported command that points to a
992 * "real" procedure defined in another namespace, a pointer to that
993 * "real" procedure's structure is returned.
994 *
995 * Side effects:
996 * None.
997 *
998 *----------------------------------------------------------------------
999 */
1000
1001 Proc *
1002 TclFindProc(
1003 Interp *iPtr, /* Interpreter in which to look. */
1004 const char *procName) /* Name of desired procedure. */
1005 {
1006 Tcl_Command cmd;
1007 Command *cmdPtr;
1008
1009 cmd = Tcl_FindCommand((Tcl_Interp *) iPtr, procName, NULL, /*flags*/ 0);
1010 if (cmd == (Tcl_Command) NULL) {
1011 return NULL;
1012 }
1013 cmdPtr = (Command *) cmd;
1014
1015 return TclIsProc(cmdPtr);
1016 }
1017
1018 /*
1019 *----------------------------------------------------------------------
1020 *
1021 * TclIsProc --
1022 *
1023 * Tells whether a command is a Tcl procedure or not.
1024 *
1025 * Results:
1026 * If the given command is actually a Tcl procedure, the return value is
1027 * the address of the record describing the procedure. Otherwise the
1028 * return value is 0.
1029 *
1030 * Side effects:
1031 * None.
1032 *
1033 *----------------------------------------------------------------------
1034 */
1035
1036 Proc *
1037 TclIsProc(
1038 Command *cmdPtr) /* Command to test. */
1039 {
1040 Tcl_Command origCmd = TclGetOriginalCommand((Tcl_Command) cmdPtr);
1041
1042 if (origCmd != NULL) {
1043 cmdPtr = (Command *) origCmd;
1044 }
1045 if (cmdPtr->deleteProc == TclProcDeleteProc) {
1046 return (Proc *)cmdPtr->objClientData;
1047 }
1048 return NULL;
1049 }
1050
1051 static int
1052 ProcWrongNumArgs(
1053 Tcl_Interp *interp,
1054 int skip)
1055 {
1056 CallFrame *framePtr = ((Interp *)interp)->varFramePtr;
1057 Proc *procPtr = framePtr->procPtr;
1058 int localCt = procPtr->numCompiledLocals, numArgs, i;
1059 Tcl_Obj **desiredObjs;
1060 const char *final = NULL;
1061
1062 /*
1063 * Build up desired argument list for Tcl_WrongNumArgs
1064 */
1065
1066 numArgs = framePtr->procPtr->numArgs;
1067 desiredObjs = (Tcl_Obj **)TclStackAlloc(interp,
1068 sizeof(Tcl_Obj *) * (numArgs+1));
1069
1070 if (framePtr->isProcCallFrame & FRAME_IS_LAMBDA) {
1071 desiredObjs[0] = Tcl_NewStringObj("lambdaExpr", -1);
1072 } else {
1073 #ifdef AVOID_HACKS_FOR_ITCL
1074 desiredObjs[0] = framePtr->objv[skip-1];
1075 #else
1076 desiredObjs[0] = Tcl_NewListObj(1, framePtr->objv + skip - 1);
1077 #endif /* AVOID_HACKS_FOR_ITCL */
1078 }
1079 Tcl_IncrRefCount(desiredObjs[0]);
1080
1081 if (localCt > 0) {
1082 Var *defPtr = (Var *)(&framePtr->localCachePtr->varName0 + localCt);
1083
1084 for (i=1 ; i<=numArgs ; i++, defPtr++) {
1085 Tcl_Obj *argObj;
1086 Tcl_Obj *namePtr = localName(framePtr, i-1);
1087
1088 if (defPtr->value.objPtr != NULL) {
1089 TclNewObj(argObj);
1090 Tcl_AppendStringsToObj(argObj, "?", TclGetString(namePtr), "?", (char *)NULL);
1091 } else if (defPtr->flags & VAR_IS_ARGS) {
1092 numArgs--;
1093 final = "?arg ...?";
1094 break;
1095 } else {
1096 argObj = namePtr;
1097 Tcl_IncrRefCount(namePtr);
1098 }
1099 desiredObjs[i] = argObj;
1100 }
1101 }
1102
1103 Tcl_ResetResult(interp);
1104 Tcl_WrongNumArgs(interp, numArgs+1, desiredObjs, final);
1105
1106 for (i=0 ; i<=numArgs ; i++) {
1107 Tcl_DecrRefCount(desiredObjs[i]);
1108 }
1109 TclStackFree(interp, desiredObjs);
1110 return TCL_ERROR;
1111 }
1112
1113 /*
1114 *----------------------------------------------------------------------
1115 *
1116 * TclInitCompiledLocals --
1117 *
1118 * This routine is invoked in order to initialize the compiled locals
1119 * table for a new call frame.
1120 *
1121 * DEPRECATED: functionality has been inlined elsewhere; this function
1122 * remains to insure binary compatibility with Itcl.
1123 *
1124 * Results:
1125 * None.
1126 *
1127 * Side effects:
1128 * May invoke various name resolvers in order to determine which
1129 * variables are being referenced at runtime.
1130 *
1131 *----------------------------------------------------------------------
1132 */
1133
1134 void
1135 TclInitCompiledLocals(
1136 Tcl_Interp *interp, /* Current interpreter. */
1137 CallFrame *framePtr, /* Call frame to initialize. */
1138 Namespace *nsPtr) /* Pointer to current namespace. */
1139 {
1140 Var *varPtr = framePtr->compiledLocals;
1141 Tcl_Obj *bodyPtr;
1142 ByteCode *codePtr;
1143
1144 bodyPtr = framePtr->procPtr->bodyPtr;
1145 if (bodyPtr->typePtr != &tclByteCodeType) {
1146 Tcl_Panic("body object for proc attached to frame is not a byte code type");
1147 }
1148 codePtr = bodyPtr->internalRep.twoPtrValue.ptr1;
1149
1150 if (framePtr->numCompiledLocals) {
1151 if (!codePtr->localCachePtr) {
1152 InitLocalCache(framePtr->procPtr) ;
1153 }
1154 framePtr->localCachePtr = codePtr->localCachePtr;
1155 framePtr->localCachePtr->refCount++;
1156 }
1157
1158 InitResolvedLocals(interp, codePtr, varPtr, nsPtr);
1159 }
1160
1161 /*
1162 *----------------------------------------------------------------------
1163 *
1164 * InitResolvedLocals --
1165 *
1166 * This routine is invoked in order to initialize the compiled locals
1167 * table for a new call frame.
1168 *
1169 * Results:
1170 * None.
1171 *
1172 * Side effects:
1173 * May invoke various name resolvers in order to determine which
1174 * variables are being referenced at runtime.
1175 *
1176 *----------------------------------------------------------------------
1177 */
1178
1179 static void
1180 InitResolvedLocals(
1181 Tcl_Interp *interp, /* Current interpreter. */
1182 ByteCode *codePtr,
1183 Var *varPtr,
1184 Namespace *nsPtr) /* Pointer to current namespace. */
1185 {
1186 Interp *iPtr = (Interp *) interp;
1187 int haveResolvers = (nsPtr->compiledVarResProc || iPtr->resolverPtr);
1188 CompiledLocal *firstLocalPtr, *localPtr;
1189 int varNum;
1190 Tcl_ResolvedVarInfo *resVarInfo;
1191
1192 /*
1193 * Find the localPtr corresponding to varPtr
1194 */
1195
1196 varNum = varPtr - iPtr->framePtr->compiledLocals;
1197 localPtr = iPtr->framePtr->procPtr->firstLocalPtr;
1198 while (varNum--) {
1199 localPtr = localPtr->nextPtr;
1200 }
1201
1202 if (!(haveResolvers && (codePtr->flags & TCL_BYTECODE_RESOLVE_VARS))) {
1203 goto doInitResolvedLocals;
1204 }
1205
1206 /*
1207 * This is the first run after a recompile, or else the resolver epoch
1208 * has changed: update the resolver cache.
1209 */
1210
1211 firstLocalPtr = localPtr;
1212 for (; localPtr != NULL; localPtr = localPtr->nextPtr) {
1213 if (localPtr->resolveInfo) {
1214 if (localPtr->resolveInfo->deleteProc) {
1215 localPtr->resolveInfo->deleteProc(localPtr->resolveInfo);
1216 } else {
1217 ckfree(localPtr->resolveInfo);
1218 }
1219 localPtr->resolveInfo = NULL;
1220 }
1221 localPtr->flags &= ~VAR_RESOLVED;
1222
1223 if (haveResolvers &&
1224 !(localPtr->flags & (VAR_ARGUMENT|VAR_TEMPORARY))) {
1225 ResolverScheme *resPtr = iPtr->resolverPtr;
1226 Tcl_ResolvedVarInfo *vinfo;
1227 int result;
1228
1229 if (nsPtr->compiledVarResProc) {
1230 result = nsPtr->compiledVarResProc(nsPtr->interp,
1231 localPtr->name, localPtr->nameLength,
1232 (Tcl_Namespace *) nsPtr, &vinfo);
1233 } else {
1234 result = TCL_CONTINUE;
1235 }
1236
1237 while ((result == TCL_CONTINUE) && resPtr) {
1238 if (resPtr->compiledVarResProc) {
1239 result = resPtr->compiledVarResProc(nsPtr->interp,
1240 localPtr->name, localPtr->nameLength,
1241 (Tcl_Namespace *) nsPtr, &vinfo);
1242 }
1243 resPtr = resPtr->nextPtr;
1244 }
1245 if (result == TCL_OK) {
1246 localPtr->resolveInfo = vinfo;
1247 localPtr->flags |= VAR_RESOLVED;
1248 }
1249 }
1250 }
1251 localPtr = firstLocalPtr;
1252 codePtr->flags &= ~TCL_BYTECODE_RESOLVE_VARS;
1253
1254 /*
1255 * Initialize the array of local variables stored in the call frame. Some
1256 * variables may have special resolution rules. In that case, we call
1257 * their "resolver" procs to get our hands on the variable, and we make
1258 * the compiled local a link to the real variable.
1259 */
1260
1261 doInitResolvedLocals:
1262 for (; localPtr != NULL; varPtr++, localPtr = localPtr->nextPtr) {
1263 varPtr->flags = 0;
1264 varPtr->value.objPtr = NULL;
1265
1266 /*
1267 * Now invoke the resolvers to determine the exact variables that
1268 * should be used.
1269 */
1270
1271 resVarInfo = localPtr->resolveInfo;
1272 if (resVarInfo && resVarInfo->fetchProc) {
1273 Var *resolvedVarPtr = (Var *)
1274 resVarInfo->fetchProc(interp, resVarInfo);
1275
1276 if (resolvedVarPtr) {
1277 if (TclIsVarInHash(resolvedVarPtr)) {
1278 VarHashRefCount(resolvedVarPtr)++;
1279 }
1280 varPtr->flags = VAR_LINK;
1281 varPtr->value.linkPtr = resolvedVarPtr;
1282 }
1283 }
1284 }
1285 }
1286
1287 void
1288 TclFreeLocalCache(
1289 Tcl_Interp *interp,
1290 LocalCache *localCachePtr)
1291 {
1292 int i;
1293 Tcl_Obj **namePtrPtr = &localCachePtr->varName0;
1294
1295 for (i = 0; i < localCachePtr->numVars; i++, namePtrPtr++) {
1296 Tcl_Obj *objPtr = *namePtrPtr;
1297
1298 if (objPtr) {
1299 /* TclReleaseLiteral calls Tcl_DecrRefCount for us */
1300 TclReleaseLiteral(interp, objPtr);
1301 }
1302 }
1303 ckfree(localCachePtr);
1304 }
1305
1306 static void
1307 InitLocalCache(
1308 Proc *procPtr)
1309 {
1310 Interp *iPtr = procPtr->iPtr;
1311 ByteCode *codePtr = procPtr->bodyPtr->internalRep.twoPtrValue.ptr1;
1312 int localCt = procPtr->numCompiledLocals;
1313 int numArgs = procPtr->numArgs, i = 0;
1314
1315 Tcl_Obj **namePtr;
1316 Var *varPtr;
1317 LocalCache *localCachePtr;
1318 CompiledLocal *localPtr;
1319 int isNew;
1320
1321 /*
1322 * Cache the names and initial values of local variables; store the
1323 * cache in both the framePtr for this execution and in the codePtr
1324 * for future calls.
1325 */
1326
1327 localCachePtr = (LocalCache *)ckalloc(TclOffset(LocalCache, varName0)
1328 + localCt * sizeof(Tcl_Obj *)
1329 + numArgs * sizeof(Var));
1330
1331 namePtr = &localCachePtr->varName0;
1332 varPtr = (Var *) (namePtr + localCt);
1333 localPtr = procPtr->firstLocalPtr;
1334 while (localPtr) {
1335 if (TclIsVarTemporary(localPtr)) {
1336 *namePtr = NULL;
1337 } else {
1338 *namePtr = TclCreateLiteral(iPtr, localPtr->name,
1339 localPtr->nameLength, /* hash */ (unsigned int) -1,
1340 &isNew, /* nsPtr */ NULL, 0, NULL);
1341 Tcl_IncrRefCount(*namePtr);
1342 }
1343
1344 if (i < numArgs) {
1345 varPtr->flags = (localPtr->flags & VAR_IS_ARGS);
1346 varPtr->value.objPtr = localPtr->defValuePtr;
1347 varPtr++;
1348 i++;
1349 }
1350 namePtr++;
1351 localPtr = localPtr->nextPtr;
1352 }
1353 codePtr->localCachePtr = localCachePtr;
1354 localCachePtr->refCount = 1;
1355 localCachePtr->numVars = localCt;
1356 }
1357
1358 /*
1359 *----------------------------------------------------------------------
1360 *
1361 * InitArgsAndLocals --
1362 *
1363 * This routine is invoked in order to initialize the arguments and other
1364 * compiled locals table for a new call frame.
1365 *
1366 * Results:
1367 * A standard Tcl result.
1368 *
1369 * Side effects:
1370 * Allocates memory on the stack for the compiled local variables, the
1371 * caller is responsible for freeing them. Initialises all variables. May
1372 * invoke various name resolvers in order to determine which variables
1373 * are being referenced at runtime.
1374 *
1375 *----------------------------------------------------------------------
1376 */
1377
1378 static int
1379 InitArgsAndLocals(
1380 Tcl_Interp *interp,/* Interpreter in which procedure was
1381 * invoked. */
1382 Tcl_Obj *procNameObj, /* Procedure name for error reporting. */
1383 int skip) /* Number of initial arguments to be skipped,
1384 * i.e., words in the "command name". */
1385 {
1386 CallFrame *framePtr = ((Interp *)interp)->varFramePtr;
1387 Proc *procPtr = framePtr->procPtr;
1388 ByteCode *codePtr = procPtr->bodyPtr->internalRep.twoPtrValue.ptr1;
1389 Var *varPtr, *defPtr;
1390 int localCt = procPtr->numCompiledLocals, numArgs, argCt, i, imax;
1391 Tcl_Obj *const *argObjs;
1392
1393 /*
1394 * Make sure that the local cache of variable names and initial values has
1395 * been initialised properly .
1396 */
1397
1398 if (localCt) {
1399 if (!codePtr->localCachePtr) {
1400 InitLocalCache(procPtr) ;
1401 }
1402 framePtr->localCachePtr = codePtr->localCachePtr;
1403 framePtr->localCachePtr->refCount++;
1404 defPtr = (Var *) (&framePtr->localCachePtr->varName0 + localCt);
1405 } else {
1406 defPtr = NULL;
1407 }
1408
1409 /*
1410 * Create the "compiledLocals" array. Make sure it is large enough to hold
1411 * all the procedure's compiled local variables, including its formal
1412 * parameters.
1413 */
1414
1415 varPtr = (Var *)TclStackAlloc(interp, localCt * sizeof(Var));
1416 framePtr->compiledLocals = varPtr;
1417 framePtr->numCompiledLocals = localCt;
1418
1419 /*
1420 * Match and assign the call's actual parameters to the procedure's formal
1421 * arguments. The formal arguments are described by the first numArgs
1422 * entries in both the Proc structure's local variable list and the call
1423 * frame's local variable array.
1424 */
1425
1426 numArgs = procPtr->numArgs;
1427 argCt = framePtr->objc - skip; /* Set it to the number of args to the
1428 * procedure. */
1429 if (numArgs == 0) {
1430 if (argCt) {
1431 goto incorrectArgs;
1432 } else {
1433 goto correctArgs;
1434 }
1435 }
1436 argObjs = framePtr->objv + skip;
1437 imax = ((argCt < numArgs-1) ? argCt : numArgs-1);
1438 for (i = 0; i < imax; i++, varPtr++, defPtr ? defPtr++ : defPtr) {
1439 /*
1440 * "Normal" arguments; last formal is special, depends on it being
1441 * 'args'.
1442 */
1443
1444 Tcl_Obj *objPtr = argObjs[i];
1445
1446 varPtr->flags = 0;
1447 varPtr->value.objPtr = objPtr;
1448 Tcl_IncrRefCount(objPtr); /* Local var is a reference. */
1449 }
1450 for (; i < numArgs-1; i++, varPtr++, defPtr ? defPtr++ : defPtr) {
1451 /*
1452 * This loop is entered if argCt < (numArgs-1). Set default values;
1453 * last formal is special.
1454 */
1455
1456 Tcl_Obj *objPtr = defPtr ? defPtr->value.objPtr : NULL;
1457
1458 if (!objPtr) {
1459 goto incorrectArgs;
1460 }
1461 varPtr->flags = 0;
1462 varPtr->value.objPtr = objPtr;
1463 Tcl_IncrRefCount(objPtr); /* Local var reference. */
1464 }
1465
1466 /*
1467 * When we get here, the last formal argument remains to be defined:
1468 * defPtr and varPtr point to the last argument to be initialized.
1469 */
1470
1471 varPtr->flags = 0;
1472 if (defPtr && defPtr->flags & VAR_IS_ARGS) {
1473 Tcl_Obj *listPtr = Tcl_NewListObj(argCt-i, argObjs+i);
1474
1475 varPtr->value.objPtr = listPtr;
1476 Tcl_IncrRefCount(listPtr); /* Local var is a reference. */
1477 } else if (argCt == numArgs) {
1478 Tcl_Obj *objPtr = argObjs[i];
1479
1480 varPtr->value.objPtr = objPtr;
1481 Tcl_IncrRefCount(objPtr); /* Local var is a reference. */
1482 } else if ((argCt < numArgs) && defPtr && defPtr->value.objPtr) {
1483 Tcl_Obj *objPtr = defPtr->value.objPtr;
1484
1485 varPtr->value.objPtr = objPtr;
1486 Tcl_IncrRefCount(objPtr); /* Local var is a reference. */
1487 } else {
1488 goto incorrectArgs;
1489 }
1490 varPtr++;
1491
1492 /*
1493 * Initialise and resolve the remaining compiledLocals. In the absence of
1494 * resolvers, they are undefined local vars: (flags=0, value=NULL).
1495 */
1496
1497 correctArgs:
1498 if (numArgs < localCt) {
1499 if (!framePtr->nsPtr->compiledVarResProc
1500 && !((Interp *)interp)->resolverPtr) {
1501 memset(varPtr, 0, (localCt - numArgs)*sizeof(Var));
1502 } else {
1503 InitResolvedLocals(interp, codePtr, varPtr, framePtr->nsPtr);
1504 }
1505 }
1506
1507 return TCL_OK;
1508
1509 /*
1510 * Initialise all compiled locals to avoid problems at DeleteLocalVars.
1511 */
1512
1513 incorrectArgs:
1514 if ((skip != 1) &&
1515 TclInitRewriteEnsemble(interp, skip-1, 0, framePtr->objv)) {
1516 TclNRAddCallback(interp, TclClearRootEnsemble, NULL, NULL, NULL, NULL);
1517 }
1518 memset(varPtr, 0,
1519 ((framePtr->compiledLocals + localCt)-varPtr) * sizeof(Var));
1520 return ProcWrongNumArgs(interp, skip);
1521 }
1522
1523 /*
1524 *----------------------------------------------------------------------
1525 *
1526 * TclPushProcCallFrame --
1527 *
1528 * Compiles a proc body if necessary, then pushes a CallFrame suitable
1529 * for executing it.
1530 *
1531 * Results:
1532 * A standard Tcl object result value.
1533 *
1534 * Side effects:
1535 * The proc's body may be recompiled. A CallFrame is pushed, it will have
1536 * to be popped by the caller.
1537 *
1538 *----------------------------------------------------------------------
1539 */
1540
1541 int
1542 TclPushProcCallFrame(
1543 ClientData clientData, /* Record describing procedure to be
1544 * interpreted. */
1545 Tcl_Interp *interp,/* Interpreter in which procedure was
1546 * invoked. */
1547 int objc, /* Count of number of arguments to this
1548 * procedure. */
1549 Tcl_Obj *const objv[], /* Argument value objects. */
1550 int isLambda) /* 1 if this is a call by ApplyObjCmd: it
1551 * needs special rules for error msg */
1552 {
1553 Proc *procPtr = (Proc *)clientData;
1554 Namespace *nsPtr = procPtr->cmdPtr->nsPtr;
1555 CallFrame *framePtr, **framePtrPtr;
1556 int result;
1557 ByteCode *codePtr;
1558
1559 /*
1560 * If necessary (i.e. if we haven't got a suitable compilation already
1561 * cached) compile the procedure's body. The compiler will allocate frame
1562 * slots for the procedure's non-argument local variables. Note that
1563 * compiling the body might increase procPtr->numCompiledLocals if new
1564 * local variables are found while compiling.
1565 */
1566
1567 if (procPtr->bodyPtr->typePtr == &tclByteCodeType) {
1568 Interp *iPtr = (Interp *) interp;
1569
1570 /*
1571 * When we've got bytecode, this is the check for validity. That is,
1572 * the bytecode must be for the right interpreter (no cross-leaks!),
1573 * the code must be from the current epoch (so subcommand compilation
1574 * is up-to-date), the namespace must match (so variable handling
1575 * is right) and the resolverEpoch must match (so that new shadowed
1576 * commands and/or resolver changes are considered).
1577 * Ensure the ByteCode's procPtr is the same (or it's precompiled).
1578 */
1579
1580 codePtr = procPtr->bodyPtr->internalRep.twoPtrValue.ptr1;
1581 if (((Interp *) *codePtr->interpHandle != iPtr)
1582 || (codePtr->compileEpoch != iPtr->compileEpoch)
1583 || (codePtr->nsPtr != nsPtr)
1584 || (codePtr->nsEpoch != nsPtr->resolverEpoch)
1585 || ((codePtr->procPtr != procPtr) && procPtr->bodyPtr->bytes)
1586 ) {
1587 goto doCompilation;
1588 }
1589 } else {
1590 doCompilation:
1591 result = TclProcCompileProc(interp, procPtr, procPtr->bodyPtr, nsPtr,
1592 (isLambda ? "body of lambda term" : "body of proc"),
1593 TclGetString(objv[isLambda]));
1594 if (result != TCL_OK) {
1595 return result;
1596 }
1597 }
1598
1599 /*
1600 * Set up and push a new call frame for the new procedure invocation.
1601 * This call frame will execute in the proc's namespace, which might be
1602 * different than the current namespace. The proc's namespace is that of
1603 * its command, which can change if the command is renamed from one
1604 * namespace to another.
1605 */
1606
1607 framePtrPtr = &framePtr;
1608 (void) TclPushStackFrame(interp, (Tcl_CallFrame **) framePtrPtr,
1609 (Tcl_Namespace *) nsPtr,
1610 (isLambda? (FRAME_IS_PROC|FRAME_IS_LAMBDA) : FRAME_IS_PROC));
1611
1612 framePtr->objc = objc;
1613 framePtr->objv = objv;
1614 framePtr->procPtr = procPtr;
1615
1616 return TCL_OK;
1617 }
1618
1619 /*
1620 *----------------------------------------------------------------------
1621 *
1622 * TclObjInterpProc --
1623 *
1624 * When a Tcl procedure gets invoked during bytecode evaluation, this
1625 * object-based routine gets invoked to interpret the procedure.
1626 *
1627 * Results:
1628 * A standard Tcl object result value.
1629 *
1630 * Side effects:
1631 * Depends on the commands in the procedure.
1632 *
1633 *----------------------------------------------------------------------
1634 */
1635
1636 int
1637 TclObjInterpProc(
1638 ClientData clientData, /* Record describing procedure to be
1639 * interpreted. */
1640 Tcl_Interp *interp,/* Interpreter in which procedure was
1641 * invoked. */
1642 int objc, /* Count of number of arguments to this
1643 * procedure. */
1644 Tcl_Obj *const objv[]) /* Argument value objects. */
1645 {
1646 /*
1647 * Not used much in the core; external interface for iTcl
1648 */
1649
1650 return Tcl_NRCallObjProc(interp, TclNRInterpProc, clientData, objc, objv);
1651 }
1652
1653 int
1654 TclNRInterpProc(
1655 ClientData clientData, /* Record describing procedure to be
1656 * interpreted. */
1657 Tcl_Interp *interp,/* Interpreter in which procedure was
1658 * invoked. */
1659 int objc, /* Count of number of arguments to this
1660 * procedure. */
1661 Tcl_Obj *const objv[]) /* Argument value objects. */
1662 {
1663 int result = TclPushProcCallFrame(clientData, interp, objc, objv,
1664 /*isLambda*/ 0);
1665
1666 if (result != TCL_OK) {
1667 return TCL_ERROR;
1668 }
1669 return TclNRInterpProcCore(interp, objv[0], 1, &MakeProcError);
1670 }
1671
1672 /*
1673 *----------------------------------------------------------------------
1674 *
1675 * TclNRInterpProcCore --
1676 *
1677 * When a Tcl procedure, lambda term or anything else that works like a
1678 * procedure gets invoked during bytecode evaluation, this object-based
1679 * routine gets invoked to interpret the body.
1680 *
1681 * Results:
1682 * A standard Tcl object result value.
1683 *
1684 * Side effects:
1685 * Nearly anything; depends on the commands in the procedure body.
1686 *
1687 *----------------------------------------------------------------------
1688 */
1689
1690 int
1691 TclNRInterpProcCore(
1692 Tcl_Interp *interp,/* Interpreter in which procedure was
1693 * invoked. */
1694 Tcl_Obj *procNameObj, /* Procedure name for error reporting. */
1695 int skip, /* Number of initial arguments to be skipped,
1696 * i.e., words in the "command name". */
1697 ProcErrorProc *errorProc) /* How to convert results from the script into
1698 * results of the overall procedure. */
1699 {
1700 Interp *iPtr = (Interp *) interp;
1701 Proc *procPtr = iPtr->varFramePtr->procPtr;
1702 int result;
1703 CallFrame *freePtr;
1704 ByteCode *codePtr;
1705
1706 result = InitArgsAndLocals(interp, procNameObj, skip);
1707 if (result != TCL_OK) {
1708 freePtr = iPtr->framePtr;
1709 Tcl_PopCallFrame(interp); /* Pop but do not free. */
1710 TclStackFree(interp, freePtr->compiledLocals);
1711 /* Free compiledLocals. */
1712 TclStackFree(interp, freePtr); /* Free CallFrame. */
1713 return TCL_ERROR;
1714 }
1715
1716 #if defined(TCL_COMPILE_DEBUG)
1717 if (tclTraceExec >= 1) {
1718 CallFrame *framePtr = iPtr->varFramePtr;
1719 int i;
1720
1721 if (framePtr->isProcCallFrame & FRAME_IS_LAMBDA) {
1722 fprintf(stdout, "Calling lambda ");
1723 } else {
1724 fprintf(stdout, "Calling proc ");
1725 }
1726 for (i = 0; i < framePtr->objc; i++) {
1727 TclPrintObject(stdout, framePtr->objv[i], 15);
1728 fprintf(stdout, " ");
1729 }
1730 fprintf(stdout, "\n");
1731 fflush(stdout);
1732 }
1733 #endif /*TCL_COMPILE_DEBUG*/
1734
1735 #ifdef USE_DTRACE
1736 if (TCL_DTRACE_PROC_ARGS_ENABLED()) {
1737 int l = iPtr->varFramePtr->isProcCallFrame & FRAME_IS_LAMBDA ? 1 : 0;
1738 const char *a[10];
1739 int i;
1740
1741 for (i = 0 ; i < 10 ; i++) {
1742 a[i] = (l < iPtr->varFramePtr->objc ?
1743 TclGetString(iPtr->varFramePtr->objv[l]) : NULL);
1744 l++;
1745 }
1746 TCL_DTRACE_PROC_ARGS(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7],
1747 a[8], a[9]);
1748 }
1749 if (TCL_DTRACE_PROC_INFO_ENABLED() && iPtr->cmdFramePtr) {
1750 Tcl_Obj *info = TclInfoFrame(interp, iPtr->cmdFramePtr);
1751 const char *a[6]; int i[2];
1752
1753 TclDTraceInfo(info, a, i);
1754 TCL_DTRACE_PROC_INFO(a[0], a[1], a[2], a[3], i[0], i[1], a[4], a[5]);
1755 TclDecrRefCount(info);
1756 }
1757 if (TCL_DTRACE_PROC_ENTRY_ENABLED()) {
1758 int l = iPtr->varFramePtr->isProcCallFrame & FRAME_IS_LAMBDA ? 1 : 0;
1759
1760 TCL_DTRACE_PROC_ENTRY(l < iPtr->varFramePtr->objc ?
1761 TclGetString(iPtr->varFramePtr->objv[l]) : NULL,
1762 iPtr->varFramePtr->objc - l - 1,
1763 (Tcl_Obj **)(iPtr->varFramePtr->objv + l + 1));
1764 }
1765 if (TCL_DTRACE_PROC_ENTRY_ENABLED()) {
1766 int l = iPtr->varFramePtr->isProcCallFrame & FRAME_IS_LAMBDA ? 1 : 0;
1767
1768 TCL_DTRACE_PROC_ENTRY(l < iPtr->varFramePtr->objc ?
1769 TclGetString(iPtr->varFramePtr->objv[l]) : NULL,
1770 iPtr->varFramePtr->objc - l - 1,
1771 (Tcl_Obj **)(iPtr->varFramePtr->objv + l + 1));
1772 }
1773 #endif /* USE_DTRACE */
1774
1775 /*
1776 * Invoke the commands in the procedure's body.
1777 */
1778
1779 procPtr->refCount++;
1780 codePtr = procPtr->bodyPtr->internalRep.twoPtrValue.ptr1;
1781
1782 TclNRAddCallback(interp, InterpProcNR2, procNameObj, errorProc,
1783 NULL, NULL);
1784 return TclNRExecuteByteCode(interp, codePtr);
1785 }
1786
1787 static int
1788 InterpProcNR2(
1789 ClientData data[],
1790 Tcl_Interp *interp,
1791 int result)
1792 {
1793 Interp *iPtr = (Interp *) interp;
1794 Proc *procPtr = iPtr->varFramePtr->procPtr;
1795 CallFrame *freePtr;
1796 Tcl_Obj *procNameObj = (Tcl_Obj *)data[0];
1797 ProcErrorProc *errorProc = (ProcErrorProc *)data[1];
1798
1799 if (TCL_DTRACE_PROC_RETURN_ENABLED()) {
1800 int l = iPtr->varFramePtr->isProcCallFrame & FRAME_IS_LAMBDA ? 1 : 0;
1801
1802 TCL_DTRACE_PROC_RETURN(l < iPtr->varFramePtr->objc ?
1803 TclGetString(iPtr->varFramePtr->objv[l]) : NULL, result);
1804 }
1805 if (procPtr->refCount-- <= 1) {
1806 TclProcCleanupProc(procPtr);
1807 }
1808
1809 /*
1810 * Free the stack-allocated compiled locals and CallFrame. It is important
1811 * to pop the call frame without freeing it first: the compiledLocals
1812 * cannot be freed before the frame is popped, as the local variables must
1813 * be deleted. But the compiledLocals must be freed first, as they were
1814 * allocated later on the stack.
1815 */
1816
1817 if (result != TCL_OK) {
1818 goto process;
1819 }
1820
1821 done:
1822 if (TCL_DTRACE_PROC_RESULT_ENABLED()) {
1823 int l = iPtr->varFramePtr->isProcCallFrame & FRAME_IS_LAMBDA ? 1 : 0;
1824 Tcl_Obj *r = Tcl_GetObjResult(interp);
1825
1826 TCL_DTRACE_PROC_RESULT(l < iPtr->varFramePtr->objc ?
1827 TclGetString(iPtr->varFramePtr->objv[l]) : NULL, result,
1828 TclGetString(r), r);
1829 }
1830
1831 freePtr = iPtr->framePtr;
1832 Tcl_PopCallFrame(interp); /* Pop but do not free. */
1833 TclStackFree(interp, freePtr->compiledLocals);
1834 /* Free compiledLocals. */
1835 TclStackFree(interp, freePtr); /* Free CallFrame. */
1836 return result;
1837
1838 /*
1839 * Process any non-TCL_OK result code.
1840 */
1841
1842 process:
1843 switch (result) {
1844 case TCL_RETURN:
1845 /*
1846 * If it is a 'return', do the TIP#90 processing now.
1847 */
1848
1849 result = TclUpdateReturnInfo((Interp *) interp);
1850 break;
1851
1852 case TCL_CONTINUE:
1853 case TCL_BREAK:
1854 /*
1855 * It's an error to get to this point from a 'break' or 'continue', so
1856 * transform to an error now.
1857 */
1858
1859 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1860 "invoked \"%s\" outside of a loop",
1861 ((result == TCL_BREAK) ? "break" : "continue")));
1862 Tcl_SetErrorCode(interp, "TCL", "RESULT", "UNEXPECTED", (char *)NULL);
1863 result = TCL_ERROR;
1864
1865 /* FALLTHRU */
1866
1867 case TCL_ERROR:
1868 /*
1869 * Now it _must_ be an error, so we need to log it as such. This means
1870 * filling out the error trace. Luckily, we just hand this off to the
1871 * function handed to us as an argument.
1872 */
1873
1874 errorProc(interp, procNameObj);
1875 }
1876 goto done;
1877 }
1878
1879 /*
1880 *----------------------------------------------------------------------
1881 *
1882 * TclProcCompileProc --
1883 *
1884 * Called just before a procedure is executed to compile the body to byte
1885 * codes. If the type of the body is not "byte code" or if the compile
1886 * conditions have changed (namespace context, epoch counters, etc.) then
1887 * the body is recompiled. Otherwise, this function does nothing.
1888 *
1889 * Results:
1890 * None.
1891 *
1892 * Side effects:
1893 * May change the internal representation of the body object to compiled
1894 * code.
1895 *
1896 *----------------------------------------------------------------------
1897 */
1898
1899 int
1900 TclProcCompileProc(
1901 Tcl_Interp *interp, /* Interpreter containing procedure. */
1902 Proc *procPtr, /* Data associated with procedure. */
1903 Tcl_Obj *bodyPtr, /* Body of proc. (Usually procPtr->bodyPtr,
1904 * but could be any code fragment compiled in
1905 * the context of this procedure.) */
1906 Namespace *nsPtr, /* Namespace containing procedure. */
1907 const char *description, /* string describing this body of code. */
1908 const char *procName) /* Name of this procedure. */
1909 {
1910 Interp *iPtr = (Interp *) interp;
1911 Tcl_CallFrame *framePtr;
1912 ByteCode *codePtr = bodyPtr->internalRep.twoPtrValue.ptr1;
1913
1914 /*
1915 * If necessary, compile the procedure's body. The compiler will allocate
1916 * frame slots for the procedure's non-argument local variables. If the
1917 * ByteCode already exists, make sure it hasn't been invalidated by
1918 * someone redefining a core command (this might make the compiled code
1919 * wrong). Also, if the code was compiled in/for a different interpreter,
1920 * we recompile it. Note that compiling the body might increase
1921 * procPtr->numCompiledLocals if new local variables are found while
1922 * compiling.
1923 *
1924 * Ensure the ByteCode's procPtr is the same (or it is pure precompiled).
1925 * Precompiled procedure bodies, however, are immutable and therefore they
1926 * are not recompiled, even if things have changed.
1927 */
1928
1929 if (bodyPtr->typePtr == &tclByteCodeType) {
1930 if (((Interp *) *codePtr->interpHandle == iPtr)
1931 && (codePtr->compileEpoch == iPtr->compileEpoch)
1932 && (codePtr->nsPtr == nsPtr)
1933 && (codePtr->nsEpoch == nsPtr->resolverEpoch)
1934 && ((codePtr->procPtr == procPtr) || !bodyPtr->bytes)
1935 ) {
1936 return TCL_OK;
1937 }
1938
1939 if (codePtr->flags & TCL_BYTECODE_PRECOMPILED) {
1940 if ((Interp *) *codePtr->interpHandle != iPtr) {
1941 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1942 "a precompiled script jumped interps", -1));
1943 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC",
1944 "CROSSINTERPBYTECODE", (char *)NULL);
1945 return TCL_ERROR;
1946 }
1947 codePtr->compileEpoch = iPtr->compileEpoch;
1948 codePtr->nsPtr = nsPtr;
1949 } else {
1950 TclFreeIntRep(bodyPtr);
1951 }
1952 }
1953
1954 if (bodyPtr->typePtr != &tclByteCodeType) {
1955 Tcl_HashEntry *hePtr;
1956
1957 #ifdef TCL_COMPILE_DEBUG
1958 if (tclTraceCompile >= 1) {
1959 /*
1960 * Display a line summarizing the top level command we are about
1961 * to compile.
1962 */
1963
1964 Tcl_Obj *message;
1965
1966 TclNewLiteralStringObj(message, "Compiling ");
1967 Tcl_IncrRefCount(message);
1968 Tcl_AppendStringsToObj(message, description, " \"", NULL);
1969 Tcl_AppendLimitedToObj(message, procName, -1, 50, NULL);
1970 fprintf(stdout, "%s\"\n", TclGetString(message));
1971 Tcl_DecrRefCount(message);
1972 }
1973 #endif
1974
1975 /*
1976 * Plug the current procPtr into the interpreter and coerce the code
1977 * body to byte codes. The interpreter needs to know which proc it's
1978 * compiling so that it can access its list of compiled locals.
1979 *
1980 * TRICKY NOTE: Be careful to push a call frame with the proper
1981 * namespace context, so that the byte codes are compiled in the
1982 * appropriate class context.
1983 */
1984
1985 iPtr->compiledProcPtr = procPtr;
1986
1987 if (procPtr->numCompiledLocals > procPtr->numArgs) {
1988 CompiledLocal *clPtr = procPtr->firstLocalPtr;
1989 CompiledLocal *lastPtr = NULL;
1990 int i, numArgs = procPtr->numArgs;
1991
1992 for (i = 0; i < numArgs; i++) {
1993 lastPtr = clPtr;
1994 clPtr = clPtr->nextPtr;
1995 }
1996
1997 if (lastPtr) {
1998 lastPtr->nextPtr = NULL;
1999 } else {
2000 procPtr->firstLocalPtr = NULL;
2001 }
2002 procPtr->lastLocalPtr = lastPtr;
2003 while (clPtr) {
2004 CompiledLocal *toFree = clPtr;
2005
2006 clPtr = clPtr->nextPtr;
2007 if (toFree->resolveInfo) {
2008 if (toFree->resolveInfo->deleteProc) {
2009 toFree->resolveInfo->deleteProc(toFree->resolveInfo);
2010 } else {
2011 ckfree(toFree->resolveInfo);
2012 }
2013 }
2014 ckfree(toFree);
2015 }
2016 procPtr->numCompiledLocals = procPtr->numArgs;
2017 }
2018
2019 (void) TclPushStackFrame(interp, &framePtr, (Tcl_Namespace *) nsPtr,
2020 /* isProcCallFrame */ 0);
2021
2022 /*
2023 * TIP #280: We get the invoking context from the cmdFrame which
2024 * was saved by 'Tcl_ProcObjCmd' (using linePBodyPtr).
2025 */
2026
2027 hePtr = Tcl_FindHashEntry(iPtr->linePBodyPtr, (char *) procPtr);
2028
2029 /*
2030 * Constructed saved frame has body as word 0. See Tcl_ProcObjCmd.
2031 */
2032
2033 iPtr->invokeWord = 0;
2034 iPtr->invokeCmdFramePtr = hePtr ? (CmdFrame *)Tcl_GetHashValue(hePtr) : NULL;
2035 TclSetByteCodeFromAny(interp, bodyPtr, NULL, NULL);
2036 iPtr->invokeCmdFramePtr = NULL;
2037 TclPopStackFrame(interp);
2038 } else if (codePtr->nsEpoch != nsPtr->resolverEpoch) {
2039 /*
2040 * The resolver epoch has changed, but we only need to invalidate the
2041 * resolver cache.
2042 */
2043
2044 codePtr->nsEpoch = nsPtr->resolverEpoch;
2045 codePtr->flags |= TCL_BYTECODE_RESOLVE_VARS;
2046 }
2047 return TCL_OK;
2048 }
2049
2050 /*
2051 *----------------------------------------------------------------------
2052 *
2053 * MakeProcError --
2054 *
2055 * Function called by TclObjInterpProc to create the stack information
2056 * upon an error from a procedure.
2057 *
2058 * Results:
2059 * The interpreter's error info trace is set to a value that supplements
2060 * the error code.
2061 *
2062 * Side effects:
2063 * none.
2064 *
2065 *----------------------------------------------------------------------
2066 */
2067
2068 static void
2069 MakeProcError(
2070 Tcl_Interp *interp, /* The interpreter in which the procedure was
2071 * called. */
2072 Tcl_Obj *procNameObj) /* Name of the procedure. Used for error
2073 * messages and trace information. */
2074 {
2075 int overflow, limit = 60, nameLen;
2076 const char *procName = TclGetStringFromObj(procNameObj, &nameLen);
2077
2078 overflow = (nameLen > limit);
2079 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
2080 "\n (procedure \"%.*s%s\" line %d)",
2081 (overflow ? limit : nameLen), procName,
2082 (overflow ? "..." : ""), Tcl_GetErrorLine(interp)));
2083 }
2084
2085 /*
2086 *----------------------------------------------------------------------
2087 *
2088 * TclProcDeleteProc --
2089 *
2090 * This function is invoked just before a command procedure is removed
2091 * from an interpreter. Its job is to release all the resources allocated
2092 * to the procedure.
2093 *
2094 * Results:
2095 * None.
2096 *
2097 * Side effects:
2098 * Memory gets freed, unless the procedure is actively being executed.
2099 * In this case the cleanup is delayed until the last call to the current
2100 * procedure completes.
2101 *
2102 *----------------------------------------------------------------------
2103 */
2104
2105 void
2106 TclProcDeleteProc(
2107 ClientData clientData) /* Procedure to be deleted. */
2108 {
2109 Proc *procPtr = (Proc *)clientData;
2110
2111 if (procPtr->refCount-- <= 1) {
2112 TclProcCleanupProc(procPtr);
2113 }
2114 }
2115
2116 /*
2117 *----------------------------------------------------------------------
2118 *
2119 * TclProcCleanupProc --
2120 *
2121 * This function does all the real work of freeing up a Proc structure.
2122 * It's called only when the structure's reference count becomes zero.
2123 *
2124 * Results:
2125 * None.
2126 *
2127 * Side effects:
2128 * Memory gets freed.
2129 *
2130 *----------------------------------------------------------------------
2131 */
2132
2133 void
2134 TclProcCleanupProc(
2135 Proc *procPtr) /* Procedure to be deleted. */
2136 {
2137 CompiledLocal *localPtr;
2138 Tcl_Obj *bodyPtr = procPtr->bodyPtr;
2139 Tcl_Obj *defPtr;
2140 Tcl_ResolvedVarInfo *resVarInfo;
2141 Tcl_HashEntry *hePtr = NULL;
2142 CmdFrame *cfPtr = NULL;
2143 Interp *iPtr = procPtr->iPtr;
2144
2145 if (bodyPtr != NULL) {
2146 /* procPtr is stored in body's ByteCode, so ensure to reset it. */
2147 if (bodyPtr->typePtr == &tclByteCodeType) {
2148 ByteCode *codePtr = bodyPtr->internalRep.twoPtrValue.ptr1;
2149 if (codePtr->procPtr == procPtr) {
2150 codePtr->procPtr = NULL;
2151 }
2152 }
2153 Tcl_DecrRefCount(bodyPtr);
2154 }
2155 for (localPtr = procPtr->firstLocalPtr; localPtr != NULL; ) {
2156 CompiledLocal *nextPtr = localPtr->nextPtr;
2157
2158 resVarInfo = localPtr->resolveInfo;
2159 if (resVarInfo) {
2160 if (resVarInfo->deleteProc) {
2161 resVarInfo->deleteProc(resVarInfo);
2162 } else {
2163 ckfree(resVarInfo);
2164 }
2165 }
2166
2167 if (localPtr->defValuePtr != NULL) {
2168 defPtr = localPtr->defValuePtr;
2169 Tcl_DecrRefCount(defPtr);
2170 }
2171 ckfree(localPtr);
2172 localPtr = nextPtr;
2173 }
2174 ckfree(procPtr);
2175
2176 /*
2177 * TIP #280: Release the location data associated with this Proc
2178 * structure, if any. The interpreter may not exist (For example for
2179 * procbody structures created by tbcload.
2180 */
2181
2182 if (iPtr == NULL) {
2183 return;
2184 }
2185
2186 hePtr = Tcl_FindHashEntry(iPtr->linePBodyPtr, (char *) procPtr);
2187 if (!hePtr) {
2188 return;
2189 }
2190
2191 cfPtr = (CmdFrame *)Tcl_GetHashValue(hePtr);
2192
2193 if (cfPtr) {
2194 if (cfPtr->type == TCL_LOCATION_SOURCE) {
2195 Tcl_DecrRefCount(cfPtr->data.eval.path);
2196 cfPtr->data.eval.path = NULL;
2197 }
2198 ckfree(cfPtr->line);
2199 cfPtr->line = NULL;
2200 ckfree(cfPtr);
2201 }
2202 Tcl_DeleteHashEntry(hePtr);
2203 }
2204
2205 /*
2206 *----------------------------------------------------------------------
2207 *
2208 * TclUpdateReturnInfo --
2209 *
2210 * This function is called when procedures return, and at other points
2211 * where the TCL_RETURN code is used. It examines the returnLevel and
2212 * returnCode to determine the real return status.
2213 *
2214 * Results:
2215 * The return value is the true completion code to use for the procedure
2216 * or script, instead of TCL_RETURN.
2217 *
2218 * Side effects:
2219 * None.
2220 *
2221 *----------------------------------------------------------------------
2222 */
2223
2224 int
2225 TclUpdateReturnInfo(
2226 Interp *iPtr) /* Interpreter for which TCL_RETURN exception
2227 * is being processed. */
2228 {
2229 int code = TCL_RETURN;
2230
2231 iPtr->returnLevel--;
2232 if (iPtr->returnLevel < 0) {
2233 Tcl_Panic("TclUpdateReturnInfo: negative return level");
2234 }
2235 if (iPtr->returnLevel == 0) {
2236 /*
2237 * Now we've reached the level to return the requested -code.
2238 * Since iPtr->returnLevel and iPtr->returnCode have completed
2239 * their task, we now reset them to default values so that any
2240 * bare "return TCL_RETURN" that may follow will work [Bug 2152286].
2241 */
2242
2243 code = iPtr->returnCode;
2244 iPtr->returnLevel = 1;
2245 iPtr->returnCode = TCL_OK;
2246 if (code == TCL_ERROR) {
2247 iPtr->flags |= ERR_LEGACY_COPY;
2248 }
2249 }
2250 return code;
2251 }
2252
2253 /*
2254 *----------------------------------------------------------------------
2255 *
2256 * TclGetObjInterpProc --
2257 *
2258 * Returns a pointer to the TclObjInterpProc function; this is different
2259 * from the value obtained from the TclObjInterpProc reference on systems
2260 * like Windows where import and export versions of a function exported
2261 * by a DLL exist.
2262 *
2263 * Results:
2264 * Returns the internal address of the TclObjInterpProc function.
2265 *
2266 * Side effects:
2267 * None.
2268 *
2269 *----------------------------------------------------------------------
2270 */
2271
2272 Tcl_ObjCmdProc *
2273 TclGetObjInterpProc(void)
2274 {
2275 return TclObjInterpProc;
2276 }
2277
2278 /*
2279 *----------------------------------------------------------------------
2280 *
2281 * TclNewProcBodyObj --
2282 *
2283 * Creates a new object, of type "procbody", whose internal
2284 * representation is the given Proc struct. The newly created object's
2285 * reference count is 0.
2286 *
2287 * Results:
2288 * Returns a pointer to a newly allocated Tcl_Obj, NULL on error.
2289 *
2290 * Side effects:
2291 * The reference count in the ByteCode attached to the Proc is bumped up
2292 * by one, since the internal rep stores a pointer to it.
2293 *
2294 *----------------------------------------------------------------------
2295 */
2296
2297 Tcl_Obj *
2298 TclNewProcBodyObj(
2299 Proc *procPtr) /* the Proc struct to store as the internal
2300 * representation. */
2301 {
2302 Tcl_Obj *objPtr;
2303
2304 if (!procPtr) {
2305 return NULL;
2306 }
2307
2308 TclNewObj(objPtr);
2309 if (objPtr) {
2310 objPtr->typePtr = &tclProcBodyType;
2311 objPtr->internalRep.twoPtrValue.ptr1 = procPtr;
2312
2313 procPtr->refCount++;
2314 }
2315
2316 return objPtr;
2317 }
2318
2319 /*
2320 *----------------------------------------------------------------------
2321 *
2322 * ProcBodyDup --
2323 *
2324 * Tcl_ObjType's Dup function for the proc body object. Bumps the
2325 * reference count on the Proc stored in the internal representation.
2326 *
2327 * Results:
2328 * None.
2329 *
2330 * Side effects:
2331 * Sets up the object in dupPtr to be a duplicate of the one in srcPtr.
2332 *
2333 *----------------------------------------------------------------------
2334 */
2335
2336 static void
2337 ProcBodyDup(
2338 Tcl_Obj *srcPtr, /* Object to copy. */
2339 Tcl_Obj *dupPtr) /* Target object for the duplication. */
2340 {
2341 Proc *procPtr = srcPtr->internalRep.twoPtrValue.ptr1;
2342
2343 dupPtr->typePtr = &tclProcBodyType;
2344 dupPtr->internalRep.twoPtrValue.ptr1 = procPtr;
2345 procPtr->refCount++;
2346 }
2347
2348 /*
2349 *----------------------------------------------------------------------
2350 *
2351 * ProcBodyFree --
2352 *
2353 * Tcl_ObjType's Free function for the proc body object. The reference
2354 * count on its Proc struct is decreased by 1; if the count reaches 0,
2355 * the proc is freed.
2356 *
2357 * Results:
2358 * None.
2359 *
2360 * Side effects:
2361 * If the reference count on the Proc struct reaches 0, the struct is
2362 * freed.
2363 *
2364 *----------------------------------------------------------------------
2365 */
2366
2367 static void
2368 ProcBodyFree(
2369 Tcl_Obj *objPtr) /* The object to clean up. */
2370 {
2371 Proc *procPtr = objPtr->internalRep.twoPtrValue.ptr1;
2372
2373 if (procPtr->refCount-- <= 1) {
2374 TclProcCleanupProc(procPtr);
2375 }
2376 }
2377
2378 /*
2379 *----------------------------------------------------------------------
2380 *
2381 * DupLambdaInternalRep, FreeLambdaInternalRep, SetLambdaFromAny --
2382 *
2383 * How to manage the internal representations of lambda term objects.
2384 * Syntactically they look like a two- or three-element list, where the
2385 * first element is the formal arguments, the second is the the body, and
2386 * the (optional) third is the namespace to execute the lambda term
2387 * within (the global namespace is assumed if it is absent).
2388 *
2389 *----------------------------------------------------------------------
2390 */
2391
2392 static void
2393 DupLambdaInternalRep(
2394 Tcl_Obj *srcPtr, /* Object with internal rep to copy. */
2395 Tcl_Obj *copyPtr) /* Object with internal rep to set. */
2396 {
2397 Proc *procPtr = srcPtr->internalRep.twoPtrValue.ptr1;
2398 Tcl_Obj *nsObjPtr = srcPtr->internalRep.twoPtrValue.ptr2;
2399
2400 copyPtr->internalRep.twoPtrValue.ptr1 = procPtr;
2401 copyPtr->internalRep.twoPtrValue.ptr2 = nsObjPtr;
2402
2403 procPtr->refCount++;
2404 Tcl_IncrRefCount(nsObjPtr);
2405 copyPtr->typePtr = &tclLambdaType;
2406 }
2407
2408 static void
2409 FreeLambdaInternalRep(
2410 Tcl_Obj *objPtr) /* CmdName object with internal representation
2411 * to free. */
2412 {
2413 Proc *procPtr = objPtr->internalRep.twoPtrValue.ptr1;
2414 Tcl_Obj *nsObjPtr = objPtr->internalRep.twoPtrValue.ptr2;
2415
2416 if (procPtr->refCount-- == 1) {
2417 TclProcCleanupProc(procPtr);
2418 }
2419 TclDecrRefCount(nsObjPtr);
2420 objPtr->typePtr = NULL;
2421 }
2422
2423 static int
2424 SetLambdaFromAny(
2425 Tcl_Interp *interp, /* Used for error reporting if not NULL. */
2426 Tcl_Obj *objPtr) /* The object to convert. */
2427 {
2428 Interp *iPtr = (Interp *) interp;
2429 const char *name;
2430 Tcl_Obj *argsPtr, *bodyPtr, *nsObjPtr, **objv;
2431 int isNew, objc, result;
2432 CmdFrame *cfPtr = NULL;
2433 Proc *procPtr;
2434
2435 if (interp == NULL) {
2436 return TCL_ERROR;
2437 }
2438
2439 /*
2440 * Convert objPtr to list type first; if it cannot be converted, or if its
2441 * length is not 2, then it cannot be converted to tclLambdaType.
2442 */
2443
2444 result = TclListObjGetElements(NULL, objPtr, &objc, &objv);
2445 if ((result != TCL_OK) || ((objc != 2) && (objc != 3))) {
2446 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2447 "can't interpret \"%s\" as a lambda expression",
2448 TclGetString(objPtr)));
2449 Tcl_SetErrorCode(interp, "TCL", "VALUE", "LAMBDA", (char *)NULL);
2450 return TCL_ERROR;
2451 }
2452
2453 argsPtr = objv[0];
2454 bodyPtr = objv[1];
2455
2456 /*
2457 * Create and initialize the Proc struct. The cmdPtr field is set to NULL
2458 * to signal that this is an anonymous function.
2459 */
2460
2461 name = TclGetString(objPtr);
2462
2463 if (TclCreateProc(interp, /*ignored nsPtr*/ NULL, name, argsPtr, bodyPtr,
2464 &procPtr) != TCL_OK) {
2465 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
2466 "\n (parsing lambda expression \"%s\")", name));
2467 return TCL_ERROR;
2468 }
2469
2470 /*
2471 * CAREFUL: TclCreateProc returns refCount==1! [Bug 1578454]
2472 * procPtr->refCount = 1;
2473 */
2474
2475 procPtr->cmdPtr = NULL;
2476
2477 /*
2478 * TIP #280: Remember the line the apply body is starting on. In a Byte
2479 * code context we ask the engine to provide us with the necessary
2480 * information. This is for the initialization of the byte code compiler
2481 * when the body is used for the first time.
2482 *
2483 * NOTE: The body is the second word in the 'objPtr'. Its location,
2484 * accessible through 'context.line[1]' (see below) is therefore only the
2485 * first approximation of the actual line the body is on. We have to use
2486 * the string rep of the 'objPtr' to determine the exact line. This is
2487 * available already through 'name'. Use 'TclListLines', see 'switch'
2488 * (tclCmdMZ.c).
2489 *
2490 * This code is nearly identical to the #280 code in Tcl_ProcObjCmd, see
2491 * this file. The differences are the different index of the body in the
2492 * line array of the context, and the special processing mentioned in the
2493 * previous paragraph to track into the list. Find a way to factor the
2494 * common elements into a single function.
2495 */
2496
2497 if (iPtr->cmdFramePtr) {
2498 CmdFrame *contextPtr = (CmdFrame *)TclStackAlloc(interp, sizeof(CmdFrame));
2499
2500 *contextPtr = *iPtr->cmdFramePtr;
2501 if (contextPtr->type == TCL_LOCATION_BC) {
2502 /*
2503 * Retrieve the source context from the bytecode. This call
2504 * accounts for the reference to the source file, if any, held in
2505 * 'context.data.eval.path'.
2506 */
2507
2508 TclGetSrcInfoForPc(contextPtr);
2509 } else if (contextPtr->type == TCL_LOCATION_SOURCE) {
2510 /*
2511 * We created a new reference to the source file path name when we
2512 * created 'context' above. Account for the reference.
2513 */
2514
2515 Tcl_IncrRefCount(contextPtr->data.eval.path);
2516
2517 }
2518
2519 if (contextPtr->type == TCL_LOCATION_SOURCE) {
2520 /*
2521 * We can record source location within a lambda only if the body
2522 * was not created by substitution.
2523 */
2524
2525 if (contextPtr->line
2526 && (contextPtr->nline >= 2) && (contextPtr->line[1] >= 0)) {
2527 int buf[2];
2528
2529 /*
2530 * Move from approximation (line of list cmd word) to actual
2531 * location (line of 2nd list element).
2532 */
2533
2534 cfPtr = (CmdFrame *)ckalloc(sizeof(CmdFrame));
2535 TclListLines(objPtr, contextPtr->line[1], 2, buf, NULL);
2536
2537 cfPtr->level = -1;
2538 cfPtr->type = contextPtr->type;
2539 cfPtr->line = (int *)ckalloc(sizeof(int));
2540 cfPtr->line[0] = buf[1];
2541 cfPtr->nline = 1;
2542 cfPtr->framePtr = NULL;
2543 cfPtr->nextPtr = NULL;
2544
2545 cfPtr->data.eval.path = contextPtr->data.eval.path;
2546 Tcl_IncrRefCount(cfPtr->data.eval.path);
2547
2548 cfPtr->cmd = NULL;
2549 cfPtr->len = 0;
2550 }
2551
2552 /*
2553 * 'contextPtr' is going out of scope. Release the reference that
2554 * it's holding to the source file path
2555 */
2556
2557 Tcl_DecrRefCount(contextPtr->data.eval.path);
2558 }
2559 TclStackFree(interp, contextPtr);
2560 }
2561 Tcl_SetHashValue(Tcl_CreateHashEntry(iPtr->linePBodyPtr, procPtr,
2562 &isNew), cfPtr);
2563
2564 /*
2565 * Set the namespace for this lambda: given by objv[2] understood as a
2566 * global reference, or else global per default.
2567 */
2568
2569 if (objc == 2) {
2570 TclNewLiteralStringObj(nsObjPtr, "::");
2571 } else {
2572 const char *nsName = TclGetString(objv[2]);
2573
2574 if ((*nsName != ':') || (*(nsName+1) != ':')) {
2575 TclNewLiteralStringObj(nsObjPtr, "::");
2576 Tcl_AppendObjToObj(nsObjPtr, objv[2]);
2577 } else {
2578 nsObjPtr = objv[2];
2579 }
2580 }
2581
2582 Tcl_IncrRefCount(nsObjPtr);
2583
2584 /*
2585 * Free the list internalrep of objPtr - this will free argsPtr, but
2586 * bodyPtr retains a reference from the Proc structure. Then finish the
2587 * conversion to tclLambdaType.
2588 */
2589
2590 TclFreeIntRep(objPtr);
2591
2592 objPtr->internalRep.twoPtrValue.ptr1 = procPtr;
2593 objPtr->internalRep.twoPtrValue.ptr2 = nsObjPtr;
2594 objPtr->typePtr = &tclLambdaType;
2595 return TCL_OK;
2596 }
2597
2598 /*
2599 *----------------------------------------------------------------------
2600 *
2601 * Tcl_ApplyObjCmd --
2602 *
2603 * This object-based function is invoked to process the "apply" Tcl
2604 * command. See the user documentation for details on what it does.
2605 *
2606 * Results:
2607 * A standard Tcl object result value.
2608 *
2609 * Side effects:
2610 * Depends on the content of the lambda term (i.e., objv[1]).
2611 *
2612 *----------------------------------------------------------------------
2613 */
2614
2615 int
2616 Tcl_ApplyObjCmd(
2617 ClientData clientData,
2618 Tcl_Interp *interp, /* Current interpreter. */
2619 int objc, /* Number of arguments. */
2620 Tcl_Obj *const objv[]) /* Argument objects. */
2621 {
2622 return Tcl_NRCallObjProc(interp, TclNRApplyObjCmd, clientData, objc, objv);
2623 }
2624
2625 int
2626 TclNRApplyObjCmd(
2627 ClientData dummy, /* Not used. */
2628 Tcl_Interp *interp, /* Current interpreter. */
2629 int objc, /* Number of arguments. */
2630 Tcl_Obj *const objv[]) /* Argument objects. */
2631 {
2632 Interp *iPtr = (Interp *) interp;
2633 Proc *procPtr = NULL;
2634 Tcl_Obj *lambdaPtr, *nsObjPtr;
2635 int result;
2636 Tcl_Namespace *nsPtr;
2637 ApplyExtraData *extraPtr;
2638
2639 if (objc < 2) {
2640 Tcl_WrongNumArgs(interp, 1, objv, "lambdaExpr ?arg ...?");
2641 return TCL_ERROR;
2642 }
2643
2644 /*
2645 * Set lambdaPtr, convert it to tclLambdaType in the current interp if
2646 * necessary.
2647 */
2648
2649 lambdaPtr = objv[1];
2650 if (lambdaPtr->typePtr == &tclLambdaType) {
2651 procPtr = lambdaPtr->internalRep.twoPtrValue.ptr1;
2652 }
2653
2654 if ((procPtr == NULL) || (procPtr->iPtr != iPtr)) {
2655 result = SetLambdaFromAny(interp, lambdaPtr);
2656 if (result != TCL_OK) {
2657 return result;
2658 }
2659 procPtr = lambdaPtr->internalRep.twoPtrValue.ptr1;
2660 }
2661
2662 /*
2663 * Find the namespace where this lambda should run, and push a call frame
2664 * for that namespace. Note that TclObjInterpProc() will pop it.
2665 */
2666
2667 nsObjPtr = lambdaPtr->internalRep.twoPtrValue.ptr2;
2668 result = TclGetNamespaceFromObj(interp, nsObjPtr, &nsPtr);
2669 if (result != TCL_OK) {
2670 return TCL_ERROR;
2671 }
2672
2673 extraPtr = (ApplyExtraData *)TclStackAlloc(interp, sizeof(ApplyExtraData));
2674 memset(&extraPtr->cmd, 0, sizeof(Command));
2675 procPtr->cmdPtr = &extraPtr->cmd;
2676 extraPtr->cmd.nsPtr = (Namespace *) nsPtr;
2677
2678 /*
2679 * TIP#280 (semi-)HACK!
2680 *
2681 * Using cmd.clientData to tell [info frame] how to render the lambdaPtr.
2682 * The InfoFrameCmd will detect this case by testing cmd.hPtr for NULL.
2683 * This condition holds here because of the memset() above, and nowhere
2684 * else (in the core). Regular commands always have a valid hPtr, and
2685 * lambda's never.
2686 */
2687
2688 extraPtr->efi.length = 1;
2689 extraPtr->efi.fields[0].name = "lambda";
2690 extraPtr->efi.fields[0].proc = NULL;
2691 extraPtr->efi.fields[0].clientData = lambdaPtr;
2692 extraPtr->cmd.clientData = &extraPtr->efi;
2693
2694 result = TclPushProcCallFrame(procPtr, interp, objc, objv, 1);
2695 if (result == TCL_OK) {
2696 TclNRAddCallback(interp, ApplyNR2, extraPtr, NULL, NULL, NULL);
2697 result = TclNRInterpProcCore(interp, objv[1], 2, &MakeLambdaError);
2698 }
2699 return result;
2700 }
2701
2702 static int
2703 ApplyNR2(
2704 ClientData data[],
2705 Tcl_Interp *interp,
2706 int result)
2707 {
2708 ApplyExtraData *extraPtr = (ApplyExtraData *)data[0];
2709
2710 TclStackFree(interp, extraPtr);
2711 return result;
2712 }
2713
2714 /*
2715 *----------------------------------------------------------------------
2716 *
2717 * MakeLambdaError --
2718 *
2719 * Function called by TclObjInterpProc to create the stack information
2720 * upon an error from a lambda term.
2721 *
2722 * Results:
2723 * The interpreter's error info trace is set to a value that supplements
2724 * the error code.
2725 *
2726 * Side effects:
2727 * none.
2728 *
2729 *----------------------------------------------------------------------
2730 */
2731
2732 static void
2733 MakeLambdaError(
2734 Tcl_Interp *interp, /* The interpreter in which the procedure was
2735 * called. */
2736 Tcl_Obj *procNameObj) /* Name of the procedure. Used for error
2737 * messages and trace information. */
2738 {
2739 int overflow, limit = 60, nameLen;
2740 const char *procName = TclGetStringFromObj(procNameObj, &nameLen);
2741
2742 overflow = (nameLen > limit);
2743 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
2744 "\n (lambda term \"%.*s%s\" line %d)",
2745 (overflow ? limit : nameLen), procName,
2746 (overflow ? "..." : ""), Tcl_GetErrorLine(interp)));
2747 }
2748
2749 /*
2750 *----------------------------------------------------------------------
2751 *
2752 * TclGetCmdFrameForProcedure --
2753 *
2754 * How to get the CmdFrame information for a procedure.
2755 *
2756 * Results:
2757 * A pointer to the CmdFrame (only guaranteed to be valid until the next
2758 * Tcl command is processed or the interpreter's state is otherwise
2759 * modified) or a NULL if the information is not available.
2760 *
2761 * Side effects:
2762 * none.
2763 *
2764 *----------------------------------------------------------------------
2765 */
2766
2767 CmdFrame *
2768 TclGetCmdFrameForProcedure(
2769 Proc *procPtr) /* The procedure whose cmd-frame is to be
2770 * looked up. */
2771 {
2772 Tcl_HashEntry *hePtr;
2773
2774 if (procPtr == NULL || procPtr->iPtr == NULL) {
2775 return NULL;
2776 }
2777 hePtr = Tcl_FindHashEntry(procPtr->iPtr->linePBodyPtr, procPtr);
2778 if (hePtr == NULL) {
2779 return NULL;
2780 }
2781 return (CmdFrame *) Tcl_GetHashValue(hePtr);
2782 }
2783
2784 /*
2785 * Local Variables:
2786 * mode: c
2787 * c-basic-offset: 4
2788 * fill-column: 78
2789 * End:
2790 */