From 239854b80c97ffda9f1300635a18bfb1350c1e53 Mon Sep 17 00:00:00 2001 From: Miguel Sofer Date: Wed, 17 Jul 2002 10:36:21 +0000 Subject: variable access optimisations --- ChangeLog | 15 + generic/tclExecute.c | 650 +++-- generic/tclInt.h | 26 +- generic/tclVar.c | 7158 +++++++++++++++++++++++++------------------------- 4 files changed, 4025 insertions(+), 3824 deletions(-) diff --git a/ChangeLog b/ChangeLog index 874196c..bf9453f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,18 @@ +2002-07-17 Miguel Sofer + + * generic/tclExecute.c: modified to do variable lookup explicitly, + and then either inlining the variable access or else calling the new + TclPtr(Set|Get|Incr)Var functions in tclVar.c + * generic/tclInt.h: declare some functions previously local to + tclVar.c for usage by TEBC. + * generic/tclVar.c: removed local declarations; moved all special + accessor functions for indexed variables to the end of the file - + they are unused and ready for removal, but left there for the time + being as they are in the internal stubs table. + + ** WARNING FOR BYTECODE MAINTAINERS ** + TCL_COMPILE_DEBUG is currently not functional; will be fixed ASAP. + 2002-07-16 Mo DeJong * unix/Makefile.in: diff --git a/generic/tclExecute.c b/generic/tclExecute.c index 024509e..c7538b5 100644 --- a/generic/tclExecute.c +++ b/generic/tclExecute.c @@ -11,7 +11,7 @@ * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * - * RCS: @(#) $Id: tclExecute.c,v 1.77 2002/07/16 01:12:50 msofer Exp $ + * RCS: @(#) $Id: tclExecute.c,v 1.78 2002/07/17 10:36:22 msofer Exp $ */ #include "tclInt.h" @@ -174,14 +174,14 @@ long tclObjsShared[TCL_MAX_SHARED_OBJ_STATS] = { 0, 0, 0, 0, 0 }; #define NEXT_INST_V(pcAdjustment, nCleanup, result) \ pc += (pcAdjustment);\ + cleanup = (nCleanup);\ if (result) {\ if ((result) > 0) {\ Tcl_IncrRefCount(objResultPtr);\ }\ - cleanup = (nCleanup);\ goto cleanupV_pushObjResultPtr;\ } else {\ - panic("ERROR: bad usage of macro NEXT_INST_V");\ + goto cleanupV;\ } @@ -1054,15 +1054,19 @@ TclExecuteByteCode(interp, codePtr) int traceInstructions = (tclTraceExec == 3); char cmdNameBuf[21]; #endif - Tcl_Obj *valuePtr, *value2Ptr, *objPtr, *elemPtr; + Tcl_Obj *valuePtr, *value2Ptr, *objPtr; char *bytes; int length; long i = 0; /* Init. avoids compiler warning. */ #ifndef TCL_WIDE_INT_IS_LONG Tcl_WideInt w; #endif - int cleanup; + register int cleanup; Tcl_Obj *objResultPtr; +// + char *part1, *part2; + Var *varPtr, *arrayPtr; + CallFrame *varFramePtr = iPtr->varFramePtr; /* * This procedure uses a stack to hold information about catch commands. @@ -1127,6 +1131,9 @@ TclExecuteByteCode(interp, codePtr) cleanupV_pushObjResultPtr: switch (cleanup) { + case 0: + PUSH_OBJECT(objResultPtr); + goto cleanup0; default: cleanup -= 2; while (cleanup--) { @@ -1145,13 +1152,24 @@ TclExecuteByteCode(interp, codePtr) stackPtr[stackTop] = objResultPtr; goto cleanup0; - cleanup2: - valuePtr = POP_OBJECT(); - TclDecrRefCount(valuePtr); - - cleanup1: - valuePtr = POP_OBJECT(); - TclDecrRefCount(valuePtr); + cleanupV: + switch (cleanup) { + default: + cleanup -= 2; + while (cleanup--) { + valuePtr = POP_OBJECT(); + TclDecrRefCount(valuePtr); + } + case 2: + cleanup2: + valuePtr = POP_OBJECT(); + TclDecrRefCount(valuePtr); + case 1: + cleanup1: + valuePtr = POP_OBJECT(); + TclDecrRefCount(valuePtr); + case 0: + } cleanup0: @@ -1420,66 +1438,93 @@ TclExecuteByteCode(interp, codePtr) TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(objPtr)), valuePtr); NEXT_INST_F(1, 1, -1); /* already has right refct */ + /* + * --------------------------------------------------------- + * Start of INST_LOAD instructions. + * + * WARNING: more 'goto' here than your doctor recommended! + * The different instructions set the value of some variables + * and then jump to somme common execution code. + */ + case INST_LOAD_SCALAR1: opnd = TclGetUInt1AtPtr(pc+1); - DECACHE_STACK_INFO(); - objResultPtr = TclGetIndexedScalar(interp, opnd, TCL_LEAVE_ERR_MSG); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u => ERROR: ", opnd), - Tcl_GetObjResult(interp)); - result = TCL_ERROR; - goto checkForCatch; + varPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = varPtr->name; + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; } - TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr); - NEXT_INST_F(2, 0, 1); + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr) + && (varPtr->tracePtr == NULL)) { + /* + * No errors, no traces: just get the value. + */ + objResultPtr = varPtr->value.objPtr; + TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr); + NEXT_INST_F(2, 0, 1); + } + pcAdjustment = 2; + cleanup = 0; + arrayPtr = NULL; + part2 = NULL; + goto doCallPtrGetVar; case INST_LOAD_SCALAR4: opnd = TclGetUInt4AtPtr(pc+1); - DECACHE_STACK_INFO(); - objResultPtr = TclGetIndexedScalar(interp, opnd, TCL_LEAVE_ERR_MSG); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u => ERROR: ", opnd), Tcl_GetObjResult(interp)); - result = TCL_ERROR; - goto checkForCatch; + varPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = varPtr->name; + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; } - TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr); - NEXT_INST_F(5, 0, 1); + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr) + && (varPtr->tracePtr == NULL)) { + /* + * No errors, no traces: just get the value. + */ + objResultPtr = varPtr->value.objPtr; + TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr); + NEXT_INST_F(5, 0, 1); + } + pcAdjustment = 5; + cleanup = 0; + arrayPtr = NULL; + part2 = NULL; + goto doCallPtrGetVar; case INST_LOAD_ARRAY_STK: - elemPtr = stackPtr[stackTop]; /* element name */ + cleanup = 2; + part2 = Tcl_GetString(stackPtr[stackTop]); /* element name */ objPtr = stackPtr[stackTop-1]; /* array name */ goto doLoadStk; case INST_LOAD_STK: case INST_LOAD_SCALAR_STK: - elemPtr = NULL; + cleanup = 1; + part2 = NULL; objPtr = stackPtr[stackTop]; /* variable name */ doLoadStk: - DECACHE_STACK_INFO(); - objResultPtr = Tcl_ObjGetVar2(interp, objPtr, elemPtr, TCL_LEAVE_ERR_MSG); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - if (elemPtr != NULL) { - TRACE_WITH_OBJ(("\"%.30s(%.30s)\" => ERROR: ", - O2S(objPtr), O2S(elemPtr)), Tcl_GetObjResult(interp)); - } else { - TRACE_WITH_OBJ(("\"%.30s\" => ERROR: ", O2S(objPtr)), - Tcl_GetObjResult(interp)); - } + part1 = TclGetString(objPtr); + varPtr = TclObjLookupVar(interp, objPtr, part2, + TCL_LEAVE_ERR_MSG, "read", + /*createPart1*/ 0, + /*createPart2*/ 1, &arrayPtr); + if (varPtr == NULL) { result = TCL_ERROR; goto checkForCatch; } - if (elemPtr != NULL) { - TRACE_WITH_OBJ(("\"%.30s(%.30s)\" => ", - O2S(objPtr), O2S(elemPtr)), objResultPtr); - NEXT_INST_F(1, 2, 1); - } else { - TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(objPtr)), objResultPtr); - NEXT_INST_F(1, 1, 1); + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr) + && (varPtr->tracePtr == NULL) + && ((arrayPtr == NULL) + || (arrayPtr->tracePtr == NULL))) { + /* + * No errors, no traces: just get the value. + */ + objResultPtr = varPtr->value.objPtr; + NEXT_INST_V(1, cleanup, 1); } + pcAdjustment = 1; + goto doCallPtrGetVar; case INST_LOAD_ARRAY4: opnd = TclGetUInt4AtPtr(pc+1); @@ -1489,147 +1534,115 @@ TclExecuteByteCode(interp, codePtr) case INST_LOAD_ARRAY1: opnd = TclGetUInt1AtPtr(pc+1); pcAdjustment = 2; - + doLoadArray: - elemPtr = stackPtr[stackTop]; - - DECACHE_STACK_INFO(); - objResultPtr = TclGetElementOfIndexedArray(interp, opnd, - elemPtr, TCL_LEAVE_ERR_MSG); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u \"%.30s\" => ERROR: ", - opnd, O2S(elemPtr)), Tcl_GetObjResult(interp)); + part2 = TclGetString(stackPtr[stackTop]); + arrayPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = arrayPtr->name; + while (TclIsVarLink(arrayPtr)) { + arrayPtr = arrayPtr->value.linkPtr; + } + varPtr = TclLookupArrayElement(interp, part1, part2, + TCL_LEAVE_ERR_MSG, "read", 0, 1, arrayPtr); + if (varPtr == NULL) { result = TCL_ERROR; goto checkForCatch; } - TRACE_WITH_OBJ(("%u \"%.30s\" => ", - opnd, O2S(elemPtr)), objResultPtr); - NEXT_INST_F(pcAdjustment, 1, 1); - - case INST_LAPPEND_SCALAR4: - opnd = TclGetUInt4AtPtr(pc+1); - pcAdjustment = 5; - storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE - | TCL_LIST_ELEMENT | TCL_TRACE_READS); - goto doStoreScalar; - - case INST_LAPPEND_SCALAR1: - opnd = TclGetUInt1AtPtr(pc+1); - pcAdjustment = 2; - storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE - | TCL_LIST_ELEMENT | TCL_TRACE_READS); - goto doStoreScalar; - - case INST_APPEND_SCALAR4: - opnd = TclGetUInt4AtPtr(pc+1); - pcAdjustment = 5; - storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE); - goto doStoreScalar; - - case INST_APPEND_SCALAR1: - opnd = TclGetUInt1AtPtr(pc+1); - pcAdjustment = 2; - storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE); - goto doStoreScalar; - - case INST_STORE_SCALAR4: - opnd = TclGetUInt4AtPtr(pc+1); - pcAdjustment = 5; - storeFlags = TCL_LEAVE_ERR_MSG; - goto doStoreScalar; + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr) + && (varPtr->tracePtr == NULL) + && ((arrayPtr == NULL) + || (arrayPtr->tracePtr == NULL))) { + /* + * No errors, no traces: just get the value. + */ + objResultPtr = varPtr->value.objPtr; + NEXT_INST_F(pcAdjustment, 1, 1); + } + cleanup = 1; + goto doCallPtrGetVar; - case INST_STORE_SCALAR1: - opnd = TclGetUInt1AtPtr(pc+1); - pcAdjustment = 2; - storeFlags = TCL_LEAVE_ERR_MSG; + doCallPtrGetVar: + /* + * There are either errors or the variable is traced: + * call TclPtrGetVar to process fully. + */ - doStoreScalar: - valuePtr = stackPtr[stackTop]; DECACHE_STACK_INFO(); - objResultPtr = TclSetIndexedScalar(interp, opnd, valuePtr, storeFlags); + objResultPtr = TclPtrGetVar(interp, varPtr, arrayPtr, part1, + part2, TCL_LEAVE_ERR_MSG); CACHE_STACK_INFO(); if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u <- \"%.30s\" => ERROR: ", - opnd, O2S(valuePtr)), Tcl_GetObjResult(interp)); result = TCL_ERROR; goto checkForCatch; } - TRACE_WITH_OBJ(("%u <- \"%.30s\" => ", - opnd, O2S(valuePtr)), objResultPtr); + NEXT_INST_V(pcAdjustment, cleanup, 1); - if (*(pc+pcAdjustment) == INST_POP) { - NEXT_INST_F((pcAdjustment+1), 1, 0); - } - NEXT_INST_F(pcAdjustment, 1, 1); + /* + * End of INST_LOAD instructions. + * --------------------------------------------------------- + */ + + /* + * --------------------------------------------------------- + * Start of INST_STORE and related instructions. + * + * WARNING: more 'goto' here than your doctor recommended! + * The different instructions set the value of some variables + * and then jump to somme common execution code. + */ case INST_LAPPEND_STK: valuePtr = stackPtr[stackTop]; /* value to append */ - elemPtr = NULL; + part2 = NULL; storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE | TCL_LIST_ELEMENT | TCL_TRACE_READS); goto doStoreStk; case INST_LAPPEND_ARRAY_STK: valuePtr = stackPtr[stackTop]; /* value to append */ - elemPtr = stackPtr[stackTop - 1]; + part2 = TclGetString(stackPtr[stackTop - 1]); storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE | TCL_LIST_ELEMENT | TCL_TRACE_READS); goto doStoreStk; case INST_APPEND_STK: valuePtr = stackPtr[stackTop]; /* value to append */ - elemPtr = NULL; + part2 = NULL; storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE); goto doStoreStk; case INST_APPEND_ARRAY_STK: valuePtr = stackPtr[stackTop]; /* value to append */ - elemPtr = stackPtr[stackTop - 1]; + part2 = TclGetString(stackPtr[stackTop - 1]); storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE); goto doStoreStk; case INST_STORE_ARRAY_STK: valuePtr = stackPtr[stackTop]; - elemPtr = stackPtr[stackTop - 1]; + part2 = TclGetString(stackPtr[stackTop - 1]); storeFlags = TCL_LEAVE_ERR_MSG; goto doStoreStk; case INST_STORE_STK: case INST_STORE_SCALAR_STK: valuePtr = stackPtr[stackTop]; - elemPtr = NULL; + part2 = NULL; storeFlags = TCL_LEAVE_ERR_MSG; doStoreStk: - objPtr = stackPtr[stackTop - 1 - (elemPtr != NULL)]; /* variable name */ - DECACHE_STACK_INFO(); - objResultPtr = Tcl_ObjSetVar2(interp, objPtr, elemPtr, valuePtr, storeFlags); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - if (elemPtr != NULL) { - TRACE_WITH_OBJ(("\"%.30s(%.30s)\" <- \"%.30s\" => ERROR: ", - O2S(objPtr), O2S(elemPtr), O2S(valuePtr)), - Tcl_GetObjResult(interp)); - } else { - TRACE_WITH_OBJ(("\"%.30s\" <- \"%.30s\" => ERROR: ", - O2S(objPtr), O2S(valuePtr)), Tcl_GetObjResult(interp)); - } + objPtr = stackPtr[stackTop - 1 - (part2 != NULL)]; /* variable name */ + part1 = TclGetString(objPtr); + varPtr = TclObjLookupVar(interp, objPtr, part2, + TCL_LEAVE_ERR_MSG, "set", + /*createPart1*/ 1, + /*createPart2*/ 1, &arrayPtr); + if (varPtr == NULL) { result = TCL_ERROR; goto checkForCatch; } - if (elemPtr != NULL) { - TRACE_WITH_OBJ(("\"%.30s(%.30s)\" <- \"%.30s\" => ", - O2S(objPtr), O2S(elemPtr), O2S(objResultPtr)), objResultPtr); - NEXT_INST_V(1, 3, 1); - } else { - TRACE_WITH_OBJ(("\"%.30s\" <- \"%.30s\" => ", - O2S(objPtr), O2S(valuePtr)), objResultPtr); - if (*(pc+1) == INST_POP) { - NEXT_INST_F(2, 2, 0); - } - NEXT_INST_F(1, 2, 1); - } + cleanup = ((part2 == NULL)? 2 : 3); + pcAdjustment = 1; + goto doCallPtrSetVar; case INST_LAPPEND_ARRAY4: opnd = TclGetUInt4AtPtr(pc+1); @@ -1670,35 +1683,128 @@ TclExecuteByteCode(interp, codePtr) doStoreArray: valuePtr = stackPtr[stackTop]; - elemPtr = stackPtr[stackTop - 1]; - DECACHE_STACK_INFO(); - objResultPtr = TclSetElementOfIndexedArray(interp, opnd, - elemPtr, valuePtr, storeFlags); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u \"%.30s\" <- \"%.30s\" => ERROR: ", - opnd, O2S(elemPtr), O2S(valuePtr)), Tcl_GetObjResult(interp)); + part2 = TclGetString(stackPtr[stackTop - 1]); + arrayPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = arrayPtr->name; + while (TclIsVarLink(arrayPtr)) { + arrayPtr = arrayPtr->value.linkPtr; + } + varPtr = TclLookupArrayElement(interp, part1, part2, + TCL_LEAVE_ERR_MSG, "set", 1, 1, arrayPtr); + if (varPtr == NULL) { result = TCL_ERROR; goto checkForCatch; } - TRACE_WITH_OBJ(("%u \"%.30s\" <- \"%.30s\" => ", - opnd, O2S(elemPtr), O2S(valuePtr)), objResultPtr); + cleanup = 2; + goto doCallPtrSetVar; + + case INST_LAPPEND_SCALAR4: + opnd = TclGetUInt4AtPtr(pc+1); + pcAdjustment = 5; + storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE + | TCL_LIST_ELEMENT | TCL_TRACE_READS); + goto doStoreScalar; + case INST_LAPPEND_SCALAR1: + opnd = TclGetUInt1AtPtr(pc+1); + pcAdjustment = 2; + storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE + | TCL_LIST_ELEMENT | TCL_TRACE_READS); + goto doStoreScalar; + + case INST_APPEND_SCALAR4: + opnd = TclGetUInt4AtPtr(pc+1); + pcAdjustment = 5; + storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE); + goto doStoreScalar; + + case INST_APPEND_SCALAR1: + opnd = TclGetUInt1AtPtr(pc+1); + pcAdjustment = 2; + storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE); + goto doStoreScalar; + + case INST_STORE_SCALAR4: + opnd = TclGetUInt4AtPtr(pc+1); + pcAdjustment = 5; + storeFlags = TCL_LEAVE_ERR_MSG; + goto doStoreScalar; + + case INST_STORE_SCALAR1: + opnd = TclGetUInt1AtPtr(pc+1); + pcAdjustment = 2; + storeFlags = TCL_LEAVE_ERR_MSG; + + doStoreScalar: + valuePtr = stackPtr[stackTop]; + varPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = varPtr->name; + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; + } + cleanup = 1; + arrayPtr = NULL; + part2 = NULL; + + doCallPtrSetVar: + if ((storeFlags == TCL_LEAVE_ERR_MSG) + && !((varPtr->flags & VAR_IN_HASHTABLE) + && (varPtr->hPtr == NULL)) + && (varPtr->tracePtr == NULL) + && (TclIsVarScalar(varPtr) + || TclIsVarUndefined(varPtr)) + && ((arrayPtr == NULL) + || (arrayPtr->tracePtr == NULL))) { + /* + * No traces, no errors, plain 'set': we can safely inline. + * The value *will* be set to what's requested, so that + * the stack top remains pointing to the same Tcl_Obj. + */ + valuePtr = varPtr->value.objPtr; + objResultPtr = stackPtr[stackTop]; + if (valuePtr != objResultPtr) { + if (valuePtr != NULL) { + TclDecrRefCount(valuePtr); + } else { + TclSetVarScalar(varPtr); + TclClearVarUndefined(varPtr); + } + varPtr->value.objPtr = objResultPtr; + Tcl_IncrRefCount(objResultPtr); + } + if (*(pc+pcAdjustment) == INST_POP) { + NEXT_INST_V((pcAdjustment+1), cleanup, 0); + } + NEXT_INST_V(pcAdjustment, cleanup, 1); + } else { + DECACHE_STACK_INFO(); + objResultPtr = TclPtrSetVar(interp, varPtr, arrayPtr, + part1, part2, valuePtr, storeFlags); + CACHE_STACK_INFO(); + if (objResultPtr == NULL) { + result = TCL_ERROR; + goto checkForCatch; + } + } if (*(pc+pcAdjustment) == INST_POP) { - NEXT_INST_F((pcAdjustment+1), 2, 0); + NEXT_INST_V((pcAdjustment+1), cleanup, 0); } - NEXT_INST_F(pcAdjustment, 2, 1); + NEXT_INST_V(pcAdjustment, cleanup, 1); - case INST_LIST: - /* - * Pop the opnd (objc) top stack elements into a new list obj - * and then decrement their ref counts. - */ - opnd = TclGetUInt4AtPtr(pc+1); - objResultPtr = Tcl_NewListObj(opnd, &(stackPtr[stackTop - (opnd-1)])); - TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr); - NEXT_INST_V(5, opnd, 1); + /* + * End of INST_STORE and related instructions. + * --------------------------------------------------------- + */ + + /* + * --------------------------------------------------------- + * Start of INST_INCR instructions. + * + * WARNING: more 'goto' here than your doctor recommended! + * The different instructions set the value of some variables + * and then jump to somme common execution code. + */ case INST_INCR_SCALAR1: case INST_INCR_ARRAY1: @@ -1736,26 +1842,32 @@ TclExecuteByteCode(interp, codePtr) goto doIncrStk; } - case INST_INCR_SCALAR1_IMM: - opnd = TclGetUInt1AtPtr(pc+1); - i = TclGetInt1AtPtr(pc+2); - pcAdjustment = 3; - - doIncrScalar: - DECACHE_STACK_INFO(); - objResultPtr = TclIncrIndexedScalar(interp, opnd, i); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u %ld => ERROR: ", opnd, i), Tcl_GetObjResult(interp)); + case INST_INCR_ARRAY_STK_IMM: + case INST_INCR_SCALAR_STK_IMM: + case INST_INCR_STK_IMM: + i = TclGetInt1AtPtr(pc+1); + pcAdjustment = 2; + + doIncrStk: + if ((*pc == INST_INCR_ARRAY_STK_IMM) + || (*pc == INST_INCR_ARRAY_STK)) { + part2 = TclGetString(stackPtr[stackTop]); + objPtr = stackPtr[stackTop - 1]; + } else { + part2 = NULL; + objPtr = stackPtr[stackTop]; + } + part1 = TclGetString(objPtr); + varPtr = TclObjLookupVar(interp, objPtr, part2, + TCL_LEAVE_ERR_MSG, "read", 0, 1, &arrayPtr); + if (varPtr == NULL) { + Tcl_AddObjErrorInfo(interp, + "\n (reading value of variable to increment)", -1); result = TCL_ERROR; goto checkForCatch; } - TRACE_WITH_OBJ(("%u %ld => ", opnd, i), objResultPtr); - - if (*(pc+pcAdjustment) == INST_POP) { - NEXT_INST_F((pcAdjustment+1), 0, 0); - } - NEXT_INST_F(pcAdjustment, 0, 1); + cleanup = ((part2 == NULL)? 1 : 2); + goto doIncrVar; case INST_INCR_ARRAY1_IMM: opnd = TclGetUInt1AtPtr(pc+1); @@ -1763,66 +1875,82 @@ TclExecuteByteCode(interp, codePtr) pcAdjustment = 3; doIncrArray: - elemPtr = stackPtr[stackTop]; - DECACHE_STACK_INFO(); - objResultPtr = TclIncrElementOfIndexedArray(interp, opnd, elemPtr, i); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - TRACE_WITH_OBJ(("%u \"%.30s\" (by %ld) => ERROR: ", - opnd, O2S(elemPtr), i), Tcl_GetObjResult(interp)); + part2 = TclGetString(stackPtr[stackTop]); + arrayPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = arrayPtr->name; + while (TclIsVarLink(arrayPtr)) { + arrayPtr = arrayPtr->value.linkPtr; + } + varPtr = TclLookupArrayElement(interp, part1, part2, + TCL_LEAVE_ERR_MSG, "read", 0, 1, arrayPtr); + if (varPtr == NULL) { + Tcl_AddObjErrorInfo(interp, + "\n (reading value of variable to increment)", -1); result = TCL_ERROR; goto checkForCatch; } - TRACE_WITH_OBJ(("%u \"%.30s\" (by %ld) => ", - opnd, O2S(elemPtr), i), objResultPtr); + cleanup = 1; + goto doIncrVar; - if (*(pc+pcAdjustment) == INST_POP) { - NEXT_INST_F((pcAdjustment+1), 1, 0); - } - NEXT_INST_F(pcAdjustment, 1, 1); - - case INST_INCR_ARRAY_STK_IMM: - case INST_INCR_SCALAR_STK_IMM: - case INST_INCR_STK_IMM: - i = TclGetInt1AtPtr(pc+1); - pcAdjustment = 2; - - doIncrStk: - if ((*pc == INST_INCR_ARRAY_STK_IMM) - || (*pc == INST_INCR_ARRAY_STK)) { - elemPtr = stackPtr[stackTop]; - objPtr = stackPtr[stackTop - 1]; - } else { - elemPtr = NULL; - objPtr = stackPtr[stackTop]; + case INST_INCR_SCALAR1_IMM: + opnd = TclGetUInt1AtPtr(pc+1); + i = TclGetInt1AtPtr(pc+2); + pcAdjustment = 3; + + doIncrScalar: + varPtr = &(varFramePtr->compiledLocals[opnd]); + part1 = varPtr->name; + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; } - DECACHE_STACK_INFO(); - objResultPtr = TclIncrVar2(interp, objPtr, elemPtr, i, TCL_LEAVE_ERR_MSG); - CACHE_STACK_INFO(); - if (objResultPtr == NULL) { - if (elemPtr != NULL) { - TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %ld) => ERROR: ", - O2S(objPtr), O2S(elemPtr), i), Tcl_GetObjResult(interp)); + arrayPtr = NULL; + part2 = NULL; + cleanup = 0; + + doIncrVar: + objPtr = varPtr->value.objPtr; + if (TclIsVarScalar(varPtr) + && !TclIsVarUndefined(varPtr) + && (varPtr->tracePtr == NULL) + && ((arrayPtr == NULL) + || (arrayPtr->tracePtr == NULL)) + && (objPtr->typePtr == &tclIntType)) { + /* + * No errors, no traces, the variable already has an + * integer value: inline processing. + */ + + i += objPtr->internalRep.longValue; + if (Tcl_IsShared(objPtr)) { + objResultPtr = Tcl_NewLongObj(i); + TclDecrRefCount(objPtr); + Tcl_IncrRefCount(objResultPtr); + varPtr->value.objPtr = objResultPtr; } else { - TRACE_WITH_OBJ(("\"%.30s\" %ld => ERROR: ", - O2S(objPtr), i), Tcl_GetObjResult(interp)); + Tcl_SetLongObj(objPtr, i); + objResultPtr = objPtr; } - result = TCL_ERROR; - goto checkForCatch; - } - if (elemPtr != NULL) { - TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %ld) => ", - O2S(objPtr), O2S(elemPtr), i), objResultPtr); - NEXT_INST_F(pcAdjustment, 2, 1); } else { - TRACE_WITH_OBJ(("\"%.30s\" %ld => ", O2S(objPtr), i), objResultPtr); - NEXT_INST_F(pcAdjustment, 1, 1); + DECACHE_STACK_INFO(); + objResultPtr = TclPtrIncrVar(interp, varPtr, arrayPtr, part1, + part2, i, TCL_LEAVE_ERR_MSG); + CACHE_STACK_INFO(); + if (objResultPtr == NULL) { + result = TCL_ERROR; + goto checkForCatch; + } } - + if (*(pc+pcAdjustment) == INST_POP) { + NEXT_INST_V((pcAdjustment+1), cleanup, 0); + } + NEXT_INST_V(pcAdjustment, cleanup, 1); + /* - * END INCR INSTRUCTIONS + * End of INST_INCR instructions. + * --------------------------------------------------------- */ + case INST_JUMP1: opnd = TclGetInt1AtPtr(pc+1); TRACE(("%d => new pc %u\n", opnd, @@ -2006,6 +2134,22 @@ TclExecuteByteCode(interp, codePtr) } } + /* + * --------------------------------------------------------- + * Start of INST_LIST and related instructions. + */ + + case INST_LIST: + /* + * Pop the opnd (objc) top stack elements into a new list obj + * and then decrement their ref counts. + */ + + opnd = TclGetUInt4AtPtr(pc+1); + objResultPtr = Tcl_NewListObj(opnd, &(stackPtr[stackTop - (opnd-1)])); + TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr); + NEXT_INST_V(5, opnd, 1); + case INST_LIST_LENGTH: valuePtr = stackPtr[stackTop]; @@ -2166,6 +2310,11 @@ TclExecuteByteCode(interp, codePtr) TRACE(("=> %s\n", O2S(objResultPtr))); NEXT_INST_F(1, 2, -1); + /* + * End of INST_LIST and related instructions. + * --------------------------------------------------------- + */ + case INST_STR_EQ: case INST_STR_NEQ: { @@ -3679,19 +3828,40 @@ TclExecuteByteCode(interp, codePtr) } varIndex = varListPtr->varIndexes[j]; - DECACHE_STACK_INFO(); - value2Ptr = TclSetIndexedScalar(interp, - varIndex, valuePtr, TCL_LEAVE_ERR_MSG); - CACHE_STACK_INFO(); - if (value2Ptr == NULL) { - TRACE_WITH_OBJ(("%u => ERROR init. index temp %d: ", - opnd, varIndex), - Tcl_GetObjResult(interp)); - if (setEmptyStr) { - TclDecrRefCount(valuePtr); + varPtr = &(varFramePtr->compiledLocals[varIndex]); + part1 = varPtr->name; + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; + } + if (!((varPtr->flags & VAR_IN_HASHTABLE) && (varPtr->hPtr == NULL)) + && (varPtr->tracePtr == NULL) + && (TclIsVarScalar(varPtr) || TclIsVarUndefined(varPtr))) { + value2Ptr = varPtr->value.objPtr; + if (valuePtr != value2Ptr) { + if (value2Ptr != NULL) { + TclDecrRefCount(value2Ptr); + } else { + TclSetVarScalar(varPtr); + TclClearVarUndefined(varPtr); + } + varPtr->value.objPtr = valuePtr; + Tcl_IncrRefCount(valuePtr); + } + } else { + DECACHE_STACK_INFO(); + value2Ptr = TclPtrSetVar(interp, varPtr, NULL, part1, + NULL, valuePtr, TCL_LEAVE_ERR_MSG); + CACHE_STACK_INFO(); + if (value2Ptr == NULL) { + TRACE_WITH_OBJ(("%u => ERROR init. index temp %d: ", + opnd, varIndex), + Tcl_GetObjResult(interp)); + if (setEmptyStr) { + TclDecrRefCount(valuePtr); + } + result = TCL_ERROR; + goto checkForCatch; } - result = TCL_ERROR; - goto checkForCatch; } valIndex++; } diff --git a/generic/tclInt.h b/generic/tclInt.h index 7eac73d..3fca93b 100644 --- a/generic/tclInt.h +++ b/generic/tclInt.h @@ -12,7 +12,7 @@ * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * - * RCS: @(#) $Id: tclInt.h,v 1.100 2002/07/16 16:38:41 dgp Exp $ + * RCS: @(#) $Id: tclInt.h,v 1.101 2002/07/17 10:36:23 msofer Exp $ */ #ifndef _TCLINT @@ -2058,6 +2058,30 @@ EXTERN int TclCompileWhileCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); /* + * Functions defined in generic/tclVar.c and currenttly exported only + * for use by the bytecode compiler and engine. Some of these could later + * be placed in the public interface. + */ + +EXTERN Var * TclLookupArrayElement _ANSI_ARGS_((Tcl_Interp *interp, + CONST char *arrayName, CONST char *elName, CONST int flags, + CONST char *msg, CONST int createPart1, + CONST int createPart2, Var *arrayPtr)); +EXTERN Var * TclObjLookupVar _ANSI_ARGS_((Tcl_Interp *interp, + Tcl_Obj *part1Ptr, CONST char *part2, int flags, + CONST char *msg, CONST int createPart1, + CONST int createPart2, Var **arrayPtrPtr)); +EXTERN Tcl_Obj *TclPtrGetVar _ANSI_ARGS_((Tcl_Interp *interp, Var *varPtr, + Var *arrayPtr, char *part1, CONST char *part2, + CONST int flags)); +EXTERN Tcl_Obj *TclPtrSetVar _ANSI_ARGS_((Tcl_Interp *interp, Var *varPtr, + Var *arrayPtr, char *part1, CONST char *part2, + Tcl_Obj *newValuePtr, CONST int flags)); +EXTERN Tcl_Obj *TclPtrIncrVar _ANSI_ARGS_((Tcl_Interp *interp, Var *varPtr, + Var *arrayPtr, char *part1, CONST char *part2, + CONST long i, CONST int flags)); + +/* *---------------------------------------------------------------- * Macros used by the Tcl core to create and release Tcl objects. * TclNewObj(objPtr) creates a new object denoting an empty string. diff --git a/generic/tclVar.c b/generic/tclVar.c index 487edc6..d8c9aad 100644 --- a/generic/tclVar.c +++ b/generic/tclVar.c @@ -15,7 +15,7 @@ * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * - * RCS: @(#) $Id: tclVar.c,v 1.56 2002/07/16 16:29:07 dgp Exp $ + * RCS: @(#) $Id: tclVar.c,v 1.57 2002/07/17 10:36:23 msofer Exp $ */ #include "tclInt.h" @@ -68,33 +68,15 @@ static int SetArraySearchObj _ANSI_ARGS_((Tcl_Interp *interp, /* - * Functions defined in this file and currently only used here and by the - * bytecode compiler and engine. Some of these could later be placed - * in the public interface. + * Functions defined in this file that may be exported in the future + * for use by the bytecode compiler and engine or to the public interface. */ -Var * TclLookupArrayElement _ANSI_ARGS_((Tcl_Interp *interp, - CONST char *arrayName, CONST char *elName, CONST int flags, - CONST char *msg, CONST int createPart1, - CONST int createPart2, Var *arrayPtr)); Var * TclLookupSimpleVar _ANSI_ARGS_((Tcl_Interp *interp, CONST char *varName, int flags, CONST int create, CONST char **errMsgPtr, int *indexPtr)); -Var * TclObjLookupVar _ANSI_ARGS_((Tcl_Interp *interp, - Tcl_Obj *part1Ptr, CONST char *part2, int flags, - CONST char *msg, CONST int createPart1, - CONST int createPart2, Var **arrayPtrPtr)); int TclObjUnsetVar2 _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *part1Ptr, CONST char *part2, int flags)); -Tcl_Obj * TclPtrGetVar _ANSI_ARGS_((Tcl_Interp *interp, Var *varPtr, - Var *arrayPtr, char *part1, CONST char *part2, - CONST int flags)); -Tcl_Obj * TclPtrSetVar _ANSI_ARGS_((Tcl_Interp *interp, Var *varPtr, - Var *arrayPtr, char *part1, CONST char *part2, - Tcl_Obj *newValuePtr, CONST int flags)); -Tcl_Obj * TclPtrIncrVar _ANSI_ARGS_((Tcl_Interp *interp, Var *varPtr, - Var *arrayPtr, char *part1, CONST char *part2, - CONST long i, CONST int flags)); static Tcl_FreeInternalRepProc FreeLocalVarName; static Tcl_DupInternalRepProc DupLocalVarName; @@ -1232,579 +1214,302 @@ TclPtrGetVar(interp, varPtr, arrayPtr, part1, part2, flags) /* *---------------------------------------------------------------------- * - * TclGetIndexedScalar -- + * Tcl_SetObjCmd -- * - * Return the Tcl object value of a local scalar variable in the active - * procedure, given its index in the procedure's array of compiler - * allocated local variables. + * This procedure is invoked to process the "set" Tcl command. + * See the user documentation for details on what it does. * * Results: - * The return value points to the current object value of the variable - * given by localIndex. If the specified variable doesn't exist, or - * there is a clash in array usage, or an error occurs while executing - * variable traces, then NULL is returned and a message will be left in - * the interpreter's result if TCL_LEAVE_ERR_MSG is set in flags. + * A standard Tcl result value. * * Side effects: - * The ref count for the returned object is _not_ incremented to - * reflect the returned reference; if you want to keep a reference to - * the object you must increment its ref count yourself. + * A variable's value may be changed. * *---------------------------------------------------------------------- */ -Tcl_Obj * -TclGetIndexedScalar(interp, localIndex, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be looked up. */ - register int localIndex; /* Index of variable in procedure's array - * of local variables. */ - int flags; /* TCL_LEAVE_ERR_MSG if to leave an error - * message in interpreter's result on an error. - * Otherwise no error message is left. */ + /* ARGSUSED */ +int +Tcl_SetObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ + register Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { - Interp *iPtr = (Interp *) interp; - CallFrame *varFramePtr = iPtr->varFramePtr; - /* Points to the procedure call frame whose - * variables are currently in use. Same as - * the current procedure's frame, if any, - * unless an "uplevel" is executing. */ - Var *compiledLocals = varFramePtr->compiledLocals; - register Var *varPtr; /* Points to the variable's in-frame Var - * structure. */ - char *varName; /* Name of the local variable. */ - CONST char *msg; - -#ifdef TCL_COMPILE_DEBUG - int localCt = varFramePtr->procPtr->numCompiledLocals; + Tcl_Obj *varValueObj; - if (compiledLocals == NULL) { - fprintf(stderr, "\nTclGetIndexedScalar: can't get "); - fprintf(stderr, "local %i in frame 0x%x, ", localIndex, - (unsigned int) varFramePtr); - fprintf(stderr, "no compiled locals\n"); - panic("TclGetIndexedScalar: no compiled locals in frame 0x%x", - (unsigned int) varFramePtr); - } - if ((localIndex < 0) || (localIndex >= localCt)) { - fprintf(stderr, "\nTclGetIndexedScalar: can't get "); - fprintf(stderr, "local %i in frame 0x%x " localIndex, - (unsigned int) varFramePtr); - fprintf(stderr, "with %i locals\n", localCt); - panic("TclGetIndexedScalar: bad local index %i in frame 0x%x", - localIndex, (unsigned int) varFramePtr); - } -#endif /* TCL_COMPILE_DEBUG */ - - varPtr = &(compiledLocals[localIndex]); - varName = varPtr->name; + if (objc == 2) { + varValueObj = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); + if (varValueObj == NULL) { + return TCL_ERROR; + } + Tcl_SetObjResult(interp, varValueObj); + return TCL_OK; + } else if (objc == 3) { - /* - * If varPtr is a link variable, we have a reference to some variable - * that was created through an "upvar" or "global" command, or we have a - * reference to a variable in an enclosing namespace. Traverse through - * any links until we find the referenced variable. - */ - - while (TclIsVarLink(varPtr)) { - varPtr = varPtr->value.linkPtr; + varValueObj = Tcl_ObjSetVar2(interp, objv[1], NULL, objv[2], + TCL_LEAVE_ERR_MSG); + if (varValueObj == NULL) { + return TCL_ERROR; + } + Tcl_SetObjResult(interp, varValueObj); + return TCL_OK; + } else { + Tcl_WrongNumArgs(interp, 1, objv, "varName ?newValue?"); + return TCL_ERROR; } +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_SetVar -- + * + * Change the value of a variable. + * + * Results: + * Returns a pointer to the malloc'ed string which is the character + * representation of the variable's new value. The caller must not + * modify this string. If the write operation was disallowed then NULL + * is returned; if the TCL_LEAVE_ERR_MSG flag is set, then an + * explanatory message will be left in the interp's result. Note that the + * returned string may not be the same as newValue; this is because + * variable traces may modify the variable's value. + * + * Side effects: + * If varName is defined as a local or global variable in interp, + * its value is changed to newValue. If varName isn't currently + * defined, then a new global variable by that name is created. + * + *---------------------------------------------------------------------- + */ - /* - * Invoke any traces that have been set for the variable. - */ +CONST char * +Tcl_SetVar(interp, varName, newValue, flags) + Tcl_Interp *interp; /* Command interpreter in which varName is + * to be looked up. */ + char *varName; /* Name of a variable in interp. */ + CONST char *newValue; /* New value for varName. */ + int flags; /* Various flags that tell how to set value: + * any of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG. */ +{ + return Tcl_SetVar2(interp, varName, (char *) NULL, newValue, flags); +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_SetVar2 -- + * + * Given a two-part variable name, which may refer either to a + * scalar variable or an element of an array, change the value + * of the variable. If the named scalar or array or element + * doesn't exist then create one. + * + * Results: + * Returns a pointer to the malloc'ed string which is the character + * representation of the variable's new value. The caller must not + * modify this string. If the write operation was disallowed because an + * array was expected but not found (or vice versa), then NULL is + * returned; if the TCL_LEAVE_ERR_MSG flag is set, then an explanatory + * message will be left in the interp's result. Note that the returned + * string may not be the same as newValue; this is because variable + * traces may modify the variable's value. + * + * Side effects: + * The value of the given variable is set. If either the array + * or the entry didn't exist then a new one is created. + * + *---------------------------------------------------------------------- + */ - if (varPtr->tracePtr != NULL) { - if (TCL_ERROR == CallVarTraces(iPtr, /*arrayPtr*/ NULL, varPtr, varName, - NULL, TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { - return NULL; - } - } +CONST char * +Tcl_SetVar2(interp, part1, part2, newValue, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be looked up. */ + char *part1; /* If part2 is NULL, this is name of scalar + * variable. Otherwise it is the name of + * an array. */ + CONST char *part2; /* Name of an element within an array, or + * NULL. */ + CONST char *newValue; /* New value for variable. */ + int flags; /* Various flags that tell how to set value: + * any of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT, or TCL_LEAVE_ERR_MSG */ +{ + register Tcl_Obj *valuePtr; + Tcl_Obj *varValuePtr; /* - * Make sure we're dealing with a scalar variable and not an array, and - * that the variable exists (isn't undefined). + * Create an object holding the variable's new value and use + * Tcl_SetVar2Ex to actually set the variable. */ - if (!TclIsVarScalar(varPtr) || TclIsVarUndefined(varPtr)) { - if (flags & TCL_LEAVE_ERR_MSG) { - if (TclIsVarArray(varPtr)) { - msg = isArray; - } else { - msg = noSuchVar; - } - VarErrMsg(interp, varName, NULL, "read", msg); - } + valuePtr = Tcl_NewStringObj(newValue, -1); + Tcl_IncrRefCount(valuePtr); + + varValuePtr = Tcl_SetVar2Ex(interp, part1, part2, valuePtr, flags); + Tcl_DecrRefCount(valuePtr); /* done with the object */ + + if (varValuePtr == NULL) { return NULL; } - return varPtr->value.objPtr; + return TclGetString(varValuePtr); } /* *---------------------------------------------------------------------- * - * TclGetElementOfIndexedArray -- + * Tcl_SetVar2Ex -- * - * Return the Tcl object value for an element in a local array - * variable. The element is named by the object elemPtr while the - * array is specified by its index in the active procedure's array - * of compiler allocated local variables. + * Given a two-part variable name, which may refer either to a scalar + * variable or an element of an array, change the value of the variable + * to a new Tcl object value. If the named scalar or array or element + * doesn't exist then create one. * * Results: - * The return value points to the current object value of the - * element. If the specified array or element doesn't exist, or there - * is a clash in array usage, or an error occurs while executing - * variable traces, then NULL is returned and a message will be left in - * the interpreter's result if TCL_LEAVE_ERR_MSG is set in flags. + * Returns a pointer to the Tcl_Obj holding the new value of the + * variable. If the write operation was disallowed because an array was + * expected but not found (or vice versa), then NULL is returned; if + * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will + * be left in the interpreter's result. Note that the returned object + * may not be the same one referenced by newValuePtr; this is because + * variable traces may modify the variable's value. * * Side effects: - * The ref count for the returned object is _not_ incremented to - * reflect the returned reference; if you want to keep a reference to - * the object you must increment its ref count yourself. + * The value of the given variable is set. If either the array or the + * entry didn't exist then a new variable is created. + * + * The reference count is decremented for any old value of the variable + * and incremented for its new value. If the new value for the variable + * is not the same one referenced by newValuePtr (perhaps as a result + * of a variable trace), then newValuePtr's ref count is left unchanged + * by Tcl_SetVar2Ex. newValuePtr's ref count is also left unchanged if + * we are appending it as a string value: that is, if "flags" includes + * TCL_APPEND_VALUE but not TCL_LIST_ELEMENT. + * + * The reference count for the returned object is _not_ incremented: if + * you want to keep a reference to the object you must increment its + * ref count yourself. * *---------------------------------------------------------------------- */ Tcl_Obj * -TclGetElementOfIndexedArray(interp, localIndex, elemPtr, flags) +Tcl_SetVar2Ex(interp, part1, part2, newValuePtr, flags) Tcl_Interp *interp; /* Command interpreter in which variable is - * to be looked up. */ - int localIndex; /* Index of array variable in procedure's - * array of local variables. */ - Tcl_Obj *elemPtr; /* Points to an object holding the name of - * an element to get in the array. */ - int flags; /* TCL_LEAVE_ERR_MSG if to leave an error - * message in interpreter's result on an error. - * Otherwise no error message is left. */ + * to be found. */ + char *part1; /* Name of an array (if part2 is non-NULL) + * or the name of a variable. */ + CONST char *part2; /* If non-NULL, gives the name of an element + * in the array part1. */ + Tcl_Obj *newValuePtr; /* New value for variable. */ + int flags; /* Various flags that tell how to set value: + * any of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT or TCL_LEAVE_ERR_MSG. */ { - Interp *iPtr = (Interp *) interp; - CallFrame *varFramePtr = iPtr->varFramePtr; - /* Points to the procedure call frame whose - * variables are currently in use. Same as - * the current procedure's frame, if any, - * unless an "uplevel" is executing. */ - Var *compiledLocals = varFramePtr->compiledLocals; - Var *arrayPtr; /* Points to the array's in-frame Var - * structure. */ - char *arrayName; /* Name of the local array. */ - Tcl_HashEntry *hPtr; - Var *varPtr = NULL; /* Points to the element's Var structure - * that we return. Initialized to avoid - * compiler warning. */ - CONST char *elem, *msg; - int new; - -#ifdef TCL_COMPILE_DEBUG - Proc *procPtr = varFramePtr->procPtr; - int localCt = procPtr->numCompiledLocals; - - if (compiledLocals == NULL) { - fprintf(stderr, "\nTclGetElementOfIndexedArray: can't get element "); - fprintf(stderr, "of local %i in frame 0x%x, " localIndex, - (unsigned int) varFramePtr); - fprintf(stderr, "no compiled locals\n"); - panic("TclGetIndexedScalar: no compiled locals in frame 0x%x", - (unsigned int) varFramePtr); - } - if ((localIndex < 0) || (localIndex >= localCt)) { - fprintf(stderr, "\nTclGetIndexedScalar: can't get element of " - "local %i in frame 0x%x with %i locals\n", localIndex, - (unsigned int) varFramePtr, localCt); - panic("TclGetElementOfIndexedArray: bad local index %i in frame 0x%x", - localIndex, (unsigned int) varFramePtr); - } -#endif /* TCL_COMPILE_DEBUG */ - - elem = TclGetString(elemPtr); - arrayPtr = &(compiledLocals[localIndex]); - arrayName = arrayPtr->name; - - /* - * If arrayPtr is a link variable, we have a reference to some variable - * that was created through an "upvar" or "global" command, or we have a - * reference to a variable in an enclosing namespace. Traverse through - * any links until we find the referenced variable. - */ - - while (TclIsVarLink(arrayPtr)) { - arrayPtr = arrayPtr->value.linkPtr; - } - - /* - * Make sure we're dealing with an array and that the array variable - * exists (isn't undefined). - */ - - if (!TclIsVarArray(arrayPtr) || TclIsVarUndefined(arrayPtr)) { - if (flags & TCL_LEAVE_ERR_MSG) { - VarErrMsg(interp, arrayName, elem, "read", noSuchVar); - } - goto errorReturn; - } - - /* - * Look up the element. Note that we must create the element (but leave - * it marked undefined) if it does not already exist. This allows a - * trace to create new array elements "on the fly" that did not exist - * before. A trace is always passed a variable for the array element. If - * the trace does not define the variable, it will be deleted below (at - * errorReturn) and an error returned. - */ - - hPtr = Tcl_CreateHashEntry(arrayPtr->value.tablePtr, elem, &new); - if (new) { - if (arrayPtr->searchPtr != NULL) { - DeleteSearches(arrayPtr); - } - varPtr = NewVar(); - Tcl_SetHashValue(hPtr, varPtr); - varPtr->hPtr = hPtr; - varPtr->nsPtr = varFramePtr->nsPtr; - TclSetVarArrayElement(varPtr); - } else { - varPtr = (Var *) Tcl_GetHashValue(hPtr); - } - - /* - * Invoke any traces that have been set for the element variable. - */ - - if ((varPtr->tracePtr != NULL) - || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { - if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, arrayName, elem, - TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { - goto errorReturn; - } - } + Var *varPtr, *arrayPtr; - /* - * Return the element if it's an existing scalar variable. - */ - - if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) { - return varPtr->value.objPtr; - } - - if (flags & TCL_LEAVE_ERR_MSG) { - if (TclIsVarArray(varPtr)) { - msg = isArray; - } else { - msg = noSuchVar; - } - VarErrMsg(interp, arrayName, elem, "read", msg); + varPtr = TclLookupVar(interp, part1, part2, flags, "set", + /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); + if (varPtr == NULL) { + return NULL; } - /* - * An error. If the variable doesn't exist anymore and no-one's using - * it, then free up the relevant structures and hash table entries. - */ - - errorReturn: - if ((varPtr != NULL) && TclIsVarUndefined(varPtr)) { - CleanupVar(varPtr, NULL); /* the array is not in a hashtable */ - } - return NULL; + return TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, + newValuePtr, flags); } /* *---------------------------------------------------------------------- * - * Tcl_SetObjCmd -- + * Tcl_ObjSetVar2 -- * - * This procedure is invoked to process the "set" Tcl command. - * See the user documentation for details on what it does. + * This function is the same as Tcl_SetVar2Ex above, except the + * variable names are passed in Tcl object instead of strings. * * Results: - * A standard Tcl result value. + * Returns a pointer to the Tcl_Obj holding the new value of the + * variable. If the write operation was disallowed because an array was + * expected but not found (or vice versa), then NULL is returned; if + * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will + * be left in the interpreter's result. Note that the returned object + * may not be the same one referenced by newValuePtr; this is because + * variable traces may modify the variable's value. * * Side effects: - * A variable's value may be changed. + * The value of the given variable is set. If either the array or the + * entry didn't exist then a new variable is created. * *---------------------------------------------------------------------- */ - /* ARGSUSED */ -int -Tcl_SetObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - register Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ +Tcl_Obj * +Tcl_ObjSetVar2(interp, part1Ptr, part2Ptr, newValuePtr, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be found. */ + register Tcl_Obj *part1Ptr; /* Points to an object holding the name of + * an array (if part2 is non-NULL) or the + * name of a variable. */ + register Tcl_Obj *part2Ptr; /* If non-null, points to an object holding + * the name of an element in the array + * part1Ptr. */ + Tcl_Obj *newValuePtr; /* New value for variable. */ + int flags; /* Various flags that tell how to set value: + * any of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT, or TCL_LEAVE_ERR_MSG. */ { - Tcl_Obj *varValueObj; + Var *varPtr, *arrayPtr; + char *part1, *part2; - if (objc == 2) { - varValueObj = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); - if (varValueObj == NULL) { - return TCL_ERROR; - } - Tcl_SetObjResult(interp, varValueObj); - return TCL_OK; - } else if (objc == 3) { + part1 = TclGetString(part1Ptr); + part2 = ((part2Ptr == NULL) ? NULL : Tcl_GetString(part2Ptr)); - varValueObj = Tcl_ObjSetVar2(interp, objv[1], NULL, objv[2], - TCL_LEAVE_ERR_MSG); - if (varValueObj == NULL) { - return TCL_ERROR; - } - Tcl_SetObjResult(interp, varValueObj); - return TCL_OK; - } else { - Tcl_WrongNumArgs(interp, 1, objv, "varName ?newValue?"); - return TCL_ERROR; + varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, "set", + /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); + if (varPtr == NULL) { + return NULL; } + + return TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, + newValuePtr, flags); } + /* *---------------------------------------------------------------------- * - * Tcl_SetVar -- + * TclPtrSetVar -- * - * Change the value of a variable. + * This function is the same as Tcl_SetVar2Ex above, except that + * it requires pointers to the variable's Var structs in addition + * to the variable names. * * Results: - * Returns a pointer to the malloc'ed string which is the character - * representation of the variable's new value. The caller must not - * modify this string. If the write operation was disallowed then NULL - * is returned; if the TCL_LEAVE_ERR_MSG flag is set, then an - * explanatory message will be left in the interp's result. Note that the - * returned string may not be the same as newValue; this is because + * Returns a pointer to the Tcl_Obj holding the new value of the + * variable. If the write operation was disallowed because an array was + * expected but not found (or vice versa), then NULL is returned; if + * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will + * be left in the interpreter's result. Note that the returned object + * may not be the same one referenced by newValuePtr; this is because * variable traces may modify the variable's value. * * Side effects: - * If varName is defined as a local or global variable in interp, - * its value is changed to newValue. If varName isn't currently - * defined, then a new global variable by that name is created. + * The value of the given variable is set. If either the array or the + * entry didn't exist then a new variable is created. + * *---------------------------------------------------------------------- */ -CONST char * -Tcl_SetVar(interp, varName, newValue, flags) - Tcl_Interp *interp; /* Command interpreter in which varName is - * to be looked up. */ - char *varName; /* Name of a variable in interp. */ - CONST char *newValue; /* New value for varName. */ - int flags; /* Various flags that tell how to set value: - * any of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG. */ -{ - return Tcl_SetVar2(interp, varName, (char *) NULL, newValue, flags); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_SetVar2 -- - * - * Given a two-part variable name, which may refer either to a - * scalar variable or an element of an array, change the value - * of the variable. If the named scalar or array or element - * doesn't exist then create one. - * - * Results: - * Returns a pointer to the malloc'ed string which is the character - * representation of the variable's new value. The caller must not - * modify this string. If the write operation was disallowed because an - * array was expected but not found (or vice versa), then NULL is - * returned; if the TCL_LEAVE_ERR_MSG flag is set, then an explanatory - * message will be left in the interp's result. Note that the returned - * string may not be the same as newValue; this is because variable - * traces may modify the variable's value. - * - * Side effects: - * The value of the given variable is set. If either the array - * or the entry didn't exist then a new one is created. - * - *---------------------------------------------------------------------- - */ - -CONST char * -Tcl_SetVar2(interp, part1, part2, newValue, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be looked up. */ - char *part1; /* If part2 is NULL, this is name of scalar - * variable. Otherwise it is the name of - * an array. */ - CONST char *part2; /* Name of an element within an array, or - * NULL. */ - CONST char *newValue; /* New value for variable. */ - int flags; /* Various flags that tell how to set value: - * any of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT, or TCL_LEAVE_ERR_MSG */ -{ - register Tcl_Obj *valuePtr; - Tcl_Obj *varValuePtr; - - /* - * Create an object holding the variable's new value and use - * Tcl_SetVar2Ex to actually set the variable. - */ - - valuePtr = Tcl_NewStringObj(newValue, -1); - Tcl_IncrRefCount(valuePtr); - - varValuePtr = Tcl_SetVar2Ex(interp, part1, part2, valuePtr, flags); - Tcl_DecrRefCount(valuePtr); /* done with the object */ - - if (varValuePtr == NULL) { - return NULL; - } - return TclGetString(varValuePtr); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_SetVar2Ex -- - * - * Given a two-part variable name, which may refer either to a scalar - * variable or an element of an array, change the value of the variable - * to a new Tcl object value. If the named scalar or array or element - * doesn't exist then create one. - * - * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * variable. If the write operation was disallowed because an array was - * expected but not found (or vice versa), then NULL is returned; if - * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will - * be left in the interpreter's result. Note that the returned object - * may not be the same one referenced by newValuePtr; this is because - * variable traces may modify the variable's value. - * - * Side effects: - * The value of the given variable is set. If either the array or the - * entry didn't exist then a new variable is created. - * - * The reference count is decremented for any old value of the variable - * and incremented for its new value. If the new value for the variable - * is not the same one referenced by newValuePtr (perhaps as a result - * of a variable trace), then newValuePtr's ref count is left unchanged - * by Tcl_SetVar2Ex. newValuePtr's ref count is also left unchanged if - * we are appending it as a string value: that is, if "flags" includes - * TCL_APPEND_VALUE but not TCL_LIST_ELEMENT. - * - * The reference count for the returned object is _not_ incremented: if - * you want to keep a reference to the object you must increment its - * ref count yourself. - * - *---------------------------------------------------------------------- - */ - -Tcl_Obj * -Tcl_SetVar2Ex(interp, part1, part2, newValuePtr, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be found. */ - char *part1; /* Name of an array (if part2 is non-NULL) - * or the name of a variable. */ - CONST char *part2; /* If non-NULL, gives the name of an element - * in the array part1. */ - Tcl_Obj *newValuePtr; /* New value for variable. */ - int flags; /* Various flags that tell how to set value: - * any of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT or TCL_LEAVE_ERR_MSG. */ -{ - Var *varPtr, *arrayPtr; - - varPtr = TclLookupVar(interp, part1, part2, flags, "set", - /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); - if (varPtr == NULL) { - return NULL; - } - - return TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, - newValuePtr, flags); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_ObjSetVar2 -- - * - * This function is the same as Tcl_SetVar2Ex above, except the - * variable names are passed in Tcl object instead of strings. - * - * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * variable. If the write operation was disallowed because an array was - * expected but not found (or vice versa), then NULL is returned; if - * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will - * be left in the interpreter's result. Note that the returned object - * may not be the same one referenced by newValuePtr; this is because - * variable traces may modify the variable's value. - * - * Side effects: - * The value of the given variable is set. If either the array or the - * entry didn't exist then a new variable is created. - * - *---------------------------------------------------------------------- - */ - -Tcl_Obj * -Tcl_ObjSetVar2(interp, part1Ptr, part2Ptr, newValuePtr, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be found. */ - register Tcl_Obj *part1Ptr; /* Points to an object holding the name of - * an array (if part2 is non-NULL) or the - * name of a variable. */ - register Tcl_Obj *part2Ptr; /* If non-null, points to an object holding - * the name of an element in the array - * part1Ptr. */ - Tcl_Obj *newValuePtr; /* New value for variable. */ - int flags; /* Various flags that tell how to set value: - * any of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT, or TCL_LEAVE_ERR_MSG. */ -{ - Var *varPtr, *arrayPtr; - char *part1, *part2; - - part1 = TclGetString(part1Ptr); - part2 = ((part2Ptr == NULL) ? NULL : Tcl_GetString(part2Ptr)); - - varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, "set", - /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); - if (varPtr == NULL) { - return NULL; - } - - return TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, - newValuePtr, flags); -} - - -/* - *---------------------------------------------------------------------- - * - * TclPtrSetVar -- - * - * This function is the same as Tcl_SetVar2Ex above, except that - * it requires pointers to the variable's Var structs in addition - * to the variable names. - * - * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * variable. If the write operation was disallowed because an array was - * expected but not found (or vice versa), then NULL is returned; if - * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will - * be left in the interpreter's result. Note that the returned object - * may not be the same one referenced by newValuePtr; this is because - * variable traces may modify the variable's value. - * - * Side effects: - * The value of the given variable is set. If either the array or the - * entry didn't exist then a new variable is created. - - * - *---------------------------------------------------------------------- - */ - -Tcl_Obj * -TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, newValuePtr, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is +Tcl_Obj * +TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, newValuePtr, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is * to be looked up. */ register Var *varPtr; Var *arrayPtr; @@ -1976,1513 +1681,1123 @@ TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, newValuePtr, flags) /* *---------------------------------------------------------------------- * - * TclSetIndexedScalar -- + * TclIncrVar2 -- * - * Change the Tcl object value of a local scalar variable in the active - * procedure, given its compile-time allocated index in the procedure's - * array of local variables. + * Given a two-part variable name, which may refer either to a scalar + * variable or an element of an array, increment the Tcl object value + * of the variable by a specified amount. * * Results: * Returns a pointer to the Tcl_Obj holding the new value of the - * variable given by localIndex. If the specified variable doesn't - * exist, or there is a clash in array usage, or an error occurs while - * executing variable traces, then NULL is returned and a message will - * be left in the interpreter's result if flags has TCL_LEAVE_ERR_MSG. - * Note that the returned object may not be the same one referenced by - * newValuePtr; this is because variable traces may modify the - * variable's value. + * variable. If the specified variable doesn't exist, or there is a + * clash in array usage, or an error occurs while executing variable + * traces, then NULL is returned and a message will be left in + * the interpreter's result. * * Side effects: - * The value of the given variable is set. The reference count is - * decremented for any old value of the variable and incremented for - * its new value. If as a result of a variable trace the new value for - * the variable is not the same one referenced by newValuePtr, then - * newValuePtr's ref count is left unchanged. The ref count for the - * returned object is _not_ incremented to reflect the returned - * reference; if you want to keep a reference to the object you must - * increment its ref count yourself. This procedure does not create - * new variables, but only sets those recognized at compile time. + * The value of the given variable is incremented by the specified + * amount. If either the array or the entry didn't exist then a new + * variable is created. The ref count for the returned object is _not_ + * incremented to reflect the returned reference; if you want to keep a + * reference to the object you must increment its ref count yourself. * *---------------------------------------------------------------------- */ Tcl_Obj * -TclSetIndexedScalar(interp, localIndex, newValuePtr, flags) +TclIncrVar2(interp, part1Ptr, part2Ptr, incrAmount, flags) Tcl_Interp *interp; /* Command interpreter in which variable is * to be found. */ - int localIndex; /* Index of variable in procedure's array - * of local variables. */ - Tcl_Obj *newValuePtr; /* New value for variable. */ - int flags; /* Various flags that tell how to set value: - * any of TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT or TCL_LEAVE_ERR_MSG. */ -{ - Interp *iPtr = (Interp *) interp; - CallFrame *varFramePtr = iPtr->varFramePtr; - /* Points to the procedure call frame whose - * variables are currently in use. Same as - * the current procedure's frame, if any, - * unless an "uplevel" is executing. */ - Var *compiledLocals = varFramePtr->compiledLocals; - register Var *varPtr; /* Points to the variable's in-frame Var - * structure. */ - char *varName; /* Name of the local variable. */ - Tcl_Obj *oldValuePtr; - Tcl_Obj *resultPtr = NULL; - -#ifdef TCL_COMPILE_DEBUG - Proc *procPtr = varFramePtr->procPtr; - int localCt = procPtr->numCompiledLocals; + Tcl_Obj *part1Ptr; /* Points to an object holding the name of + * an array (if part2 is non-NULL) or the + * name of a variable. */ + Tcl_Obj *part2Ptr; /* If non-null, points to an object holding + * the name of an element in the array + * part1Ptr. */ + long incrAmount; /* Amount to be added to variable. */ + int flags; /* Various flags that tell how to incr value: + * any of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG. */ +{ + Var *varPtr, *arrayPtr; + char *part1, *part2; - if (compiledLocals == NULL) { - fprintf(stderr, "\nTclSetIndexedScalar: can't set "); - fprintf(stderr, "local %i in ", localIndex); - fprintf(stderr, "frame 0x%x, no compiled locals\n", - (unsigned int) varFramePtr); - panic("TclSetIndexedScalar: no compiled locals in frame 0x%x", - (unsigned int) varFramePtr); - } - if ((localIndex < 0) || (localIndex >= localCt)) { - fprintf(stderr, "\nTclSetIndexedScalar: can't set "); - fprintf(stderr, "local %i in " localIndex); - fprintf(stderr, "frame 0x%x with %i locals\n", - (unsigned int) varFramePtr, localCt); - panic("TclSetIndexedScalar: bad local index %i in frame 0x%x", - localIndex, (unsigned int) varFramePtr); - } -#endif /* TCL_COMPILE_DEBUG */ - - varPtr = &(compiledLocals[localIndex]); - varName = varPtr->name; + part1 = TclGetString(part1Ptr); + part2 = ((part2Ptr == NULL)? NULL : TclGetString(part2Ptr)); - /* - * If varPtr is a link variable, we have a reference to some variable - * that was created through an "upvar" or "global" command, or we have a - * reference to a variable in an enclosing namespace. Traverse through - * any links until we find the referenced variable. - */ - - while (TclIsVarLink(varPtr)) { - varPtr = varPtr->value.linkPtr; + varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, "read", + 0, 1, &arrayPtr); + if (varPtr == NULL) { + Tcl_AddObjErrorInfo(interp, + "\n (reading value of variable to increment)", -1); + return NULL; } + return TclPtrIncrVar(interp, varPtr, arrayPtr, part1, part2, + incrAmount, flags); +} + +/* + *---------------------------------------------------------------------- + * + * TclPtrIncrVar -- + * + * Given the pointers to a variable and possible containing array, + * increment the Tcl object value of the variable by a specified + * amount. + * + * Results: + * Returns a pointer to the Tcl_Obj holding the new value of the + * variable. If the specified variable doesn't exist, or there is a + * clash in array usage, or an error occurs while executing variable + * traces, then NULL is returned and a message will be left in + * the interpreter's result. + * + * Side effects: + * The value of the given variable is incremented by the specified + * amount. If either the array or the entry didn't exist then a new + * variable is created. The ref count for the returned object is _not_ + * incremented to reflect the returned reference; if you want to keep a + * reference to the object you must increment its ref count yourself. + * + *---------------------------------------------------------------------- + */ - /* - * Invoke any read traces that have been set for the variable if it - * is requested; this is only done in the core when lappending. - */ - - if ((flags & TCL_TRACE_READS) && (varPtr->tracePtr != NULL)) { - if (TCL_ERROR == CallVarTraces(iPtr, /*arrayPtr*/ NULL, varPtr, varName, - NULL, TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { - return NULL; - } - } +Tcl_Obj * +TclPtrIncrVar(interp, varPtr, arrayPtr, part1, part2, incrAmount, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be found. */ + Var *varPtr; + Var *arrayPtr; + char *part1; /* Points to an object holding the name of + * an array (if part2 is non-NULL) or the + * name of a variable. */ + CONST char *part2; /* If non-null, points to an object holding + * the name of an element in the array + * part1Ptr. */ + long incrAmount; /* Amount to be added to variable. */ + int flags; /* Various flags that tell how to incr value: + * any of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG. */ +{ + register Tcl_Obj *varValuePtr; + int createdNewObj; /* Set 1 if var's value object is shared + * so we must increment a copy (i.e. copy + * on write). */ + long i; - /* - * If the variable is in a hashtable and its hPtr field is NULL, then we - * may have an upvar to an array element where the array was deleted - * or an upvar to a namespace variable whose namespace was deleted. - * Generate an error (allowing the variable to be reset would screw up - * our storage allocation and is meaningless anyway). - */ + varValuePtr = TclPtrGetVar(interp, varPtr, arrayPtr, part1, part2, flags); - if ((varPtr->flags & VAR_IN_HASHTABLE) && (varPtr->hPtr == NULL)) { - if (flags & TCL_LEAVE_ERR_MSG) { - if (TclIsVarArrayElement(varPtr)) { - VarErrMsg(interp, varName, NULL, "set", danglingElement); - } else { - VarErrMsg(interp, varName, NULL, "set", danglingVar); - } - } + if (varValuePtr == NULL) { + Tcl_AddObjErrorInfo(interp, + "\n (reading value of variable to increment)", -1); return NULL; } /* - * It's an error to try to set an array variable itself. + * Increment the variable's value. If the object is unshared we can + * modify it directly, otherwise we must create a new copy to modify: + * this is "copy on write". Then free the variable's old string + * representation, if any, since it will no longer be valid. */ - if (TclIsVarArray(varPtr) && !TclIsVarUndefined(varPtr)) { - if (flags & TCL_LEAVE_ERR_MSG) { - VarErrMsg(interp, varName, NULL, "set", isArray); + createdNewObj = 0; + if (Tcl_IsShared(varValuePtr)) { + varValuePtr = Tcl_DuplicateObj(varValuePtr); + createdNewObj = 1; + } +#ifdef TCL_WIDE_INT_IS_LONG + if (Tcl_GetLongFromObj(interp, varValuePtr, &i) != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ } return NULL; } - - /* - * Set the variable's new value and discard its old value. - */ - - oldValuePtr = varPtr->value.objPtr; - if (flags & TCL_APPEND_VALUE) { - if (TclIsVarUndefined(varPtr) && (oldValuePtr != NULL)) { - Tcl_DecrRefCount(oldValuePtr); /* discard old value */ - varPtr->value.objPtr = NULL; - oldValuePtr = NULL; - } - if (flags & TCL_LIST_ELEMENT) { /* append list element */ - if (oldValuePtr == NULL) { - TclNewObj(oldValuePtr); - varPtr->value.objPtr = oldValuePtr; - Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ - } else if (Tcl_IsShared(oldValuePtr)) { - varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); - Tcl_DecrRefCount(oldValuePtr); - oldValuePtr = varPtr->value.objPtr; - Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ - } - if (Tcl_ListObjAppendElement(interp, oldValuePtr, - newValuePtr) != TCL_OK) { - return NULL; - } - } else { /* append string */ - /* - * We append newValuePtr's bytes but don't change its ref count. - */ - - if (oldValuePtr == NULL) { - varPtr->value.objPtr = newValuePtr; - Tcl_IncrRefCount(newValuePtr); - } else { - if (Tcl_IsShared(oldValuePtr)) { /* append to copy */ - varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); - TclDecrRefCount(oldValuePtr); - oldValuePtr = varPtr->value.objPtr; - Tcl_IncrRefCount(oldValuePtr); /* since var is ref */ - } - Tcl_AppendObjToObj(oldValuePtr, newValuePtr); - } - } - } else if (newValuePtr != oldValuePtr) { /* set new value */ + Tcl_SetLongObj(varValuePtr, (i + incrAmount)); +#else + if (varValuePtr->typePtr == &tclWideIntType) { + Tcl_WideInt wide = varValuePtr->internalRep.wideValue; + Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); + } else if (varValuePtr->typePtr == &tclIntType) { + i = varValuePtr->internalRep.longValue; + Tcl_SetIntObj(varValuePtr, i + incrAmount); + } else { /* - * In this case we are replacing the value, so we don't need to - * do more than swap the objects. + * Not an integer or wide internal-rep... */ - - varPtr->value.objPtr = newValuePtr; - Tcl_IncrRefCount(newValuePtr); /* var is another ref to obj */ - if (oldValuePtr != NULL) { - TclDecrRefCount(oldValuePtr); /* discard old value */ + Tcl_WideInt wide; + if (Tcl_GetWideIntFromObj(interp, varValuePtr, &wide) != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ + } + return NULL; } - } - TclSetVarScalar(varPtr); - TclClearVarUndefined(varPtr); - - /* - * Invoke any write traces for the variable. - */ - - if (varPtr->tracePtr != NULL) { - if (TCL_ERROR == CallVarTraces(iPtr, /*arrayPtr*/ NULL, varPtr, varName, - NULL, TCL_TRACE_WRITES, (flags & TCL_LEAVE_ERR_MSG))) { - goto cleanup; + if (wide <= Tcl_LongAsWide(LONG_MAX) + && wide >= Tcl_LongAsWide(LONG_MIN)) { + Tcl_SetLongObj(varValuePtr, Tcl_WideAsLong(wide) + incrAmount); + } else { + Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); } } +#endif /* - * Return the variable's value unless the variable was changed in some - * gross way by a trace (e.g. it was unset and then recreated as an - * array). If it was changed is a gross way, just return an empty string - * object. + * Store the variable's new value and run any write traces. */ - - if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) { - return varPtr->value.objPtr; - } - resultPtr = Tcl_NewObj(); + return TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, + varValuePtr, flags); +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_UnsetVar -- + * + * Delete a variable, so that it may not be accessed anymore. + * + * Results: + * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR + * if the variable can't be unset. In the event of an error, + * if the TCL_LEAVE_ERR_MSG flag is set then an error message + * is left in the interp's result. + * + * Side effects: + * If varName is defined as a local or global variable in interp, + * it is deleted. + * + *---------------------------------------------------------------------- + */ - /* - * If the variable doesn't exist anymore and no-one's using it, then - * free up the relevant structures and hash table entries. - */ +int +Tcl_UnsetVar(interp, varName, flags) + Tcl_Interp *interp; /* Command interpreter in which varName is + * to be looked up. */ + char *varName; /* Name of a variable in interp. May be + * either a scalar name or an array name + * or an element in an array. */ + int flags; /* OR-ed combination of any of + * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY or + * TCL_LEAVE_ERR_MSG. */ +{ + return Tcl_UnsetVar2(interp, varName, (char *) NULL, flags); +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_UnsetVar2 -- + * + * Delete a variable, given a 2-part name. + * + * Results: + * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR + * if the variable can't be unset. In the event of an error, + * if the TCL_LEAVE_ERR_MSG flag is set then an error message + * is left in the interp's result. + * + * Side effects: + * If part1 and part2 indicate a local or global variable in interp, + * it is deleted. If part1 is an array name and part2 is NULL, then + * the whole array is deleted. + * + *---------------------------------------------------------------------- + */ - cleanup: - if (TclIsVarUndefined(varPtr)) { - CleanupVar(varPtr, NULL); - } - return resultPtr; +int +Tcl_UnsetVar2(interp, part1, part2, flags) + Tcl_Interp *interp; /* Command interpreter in which varName is + * to be looked up. */ + char *part1; /* Name of variable or array. */ + CONST char *part2; /* Name of element within array or NULL. */ + int flags; /* OR-ed combination of any of + * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, + * TCL_LEAVE_ERR_MSG. */ +{ + int result; + Tcl_Obj *part1Ptr; + + part1Ptr = Tcl_NewStringObj(part1, -1); + Tcl_IncrRefCount(part1Ptr); + result = TclObjUnsetVar2(interp, part1Ptr, part2, flags); + TclDecrRefCount(part1Ptr); + + return result; } + /* *---------------------------------------------------------------------- * - * TclSetElementOfIndexedArray -- + * TclObjUnsetVar2 -- * - * Change the Tcl object value of an element in a local array - * variable. The element is named by the object elemPtr while the array - * is specified by its index in the active procedure's array of - * compiler allocated local variables. + * Delete a variable, given a 2-object name. * * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * element. If the specified array or element doesn't exist, or there - * is a clash in array usage, or an error occurs while executing - * variable traces, then NULL is returned and a message will be left in - * the interpreter's result if flags has TCL_LEAVE_ERR_MSG. Note that the - * returned object may not be the same one referenced by newValuePtr; - * this is because variable traces may modify the variable's value. + * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR + * if the variable can't be unset. In the event of an error, + * if the TCL_LEAVE_ERR_MSG flag is set then an error message + * is left in the interp's result. * * Side effects: - * The value of the given array element is set. The reference count is - * decremented for any old value of the element and incremented for its - * new value. If as a result of a variable trace the new value for the - * element is not the same one referenced by newValuePtr, then - * newValuePtr's ref count is left unchanged. The ref count for the - * returned object is _not_ incremented to reflect the returned - * reference; if you want to keep a reference to the object you must - * increment its ref count yourself. This procedure will not create new - * array variables, but only sets elements of those arrays recognized - * at compile time. However, if the entry doesn't exist then a new - * variable is created. + * If part1ptr and part2Ptr indicate a local or global variable in interp, + * it is deleted. If part1Ptr is an array name and part2Ptr is NULL, then + * the whole array is deleted. * *---------------------------------------------------------------------- */ -Tcl_Obj * -TclSetElementOfIndexedArray(interp, localIndex, elemPtr, newValuePtr, flags) - Tcl_Interp *interp; /* Command interpreter in which the array is - * to be found. */ - int localIndex; /* Index of array variable in procedure's - * array of local variables. */ - Tcl_Obj *elemPtr; /* Points to an object holding the name of - * an element to set in the array. */ - Tcl_Obj *newValuePtr; /* New value for variable. */ - int flags; /* Various flags that tell how to set value: - * any of TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT or TCL_LEAVE_ERR_MSG. */ +int +TclObjUnsetVar2(interp, part1Ptr, part2, flags) + Tcl_Interp *interp; /* Command interpreter in which varName is + * to be looked up. */ + Tcl_Obj *part1Ptr; /* Name of variable or array. */ + CONST char *part2; /* Name of element within array or NULL. */ + int flags; /* OR-ed combination of any of + * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, + * TCL_LEAVE_ERR_MSG. */ { + Var dummyVar; + Var *varPtr, *dummyVarPtr; Interp *iPtr = (Interp *) interp; - CallFrame *varFramePtr = iPtr->varFramePtr; - /* Points to the procedure call frame whose - * variables are currently in use. Same as - * the current procedure's frame, if any, - * unless an "uplevel" is executing. */ - Var *compiledLocals = varFramePtr->compiledLocals; - Var *arrayPtr; /* Points to the array's in-frame Var - * structure. */ - char *arrayName; /* Name of the local array. */ - char *elem; - Tcl_HashEntry *hPtr; - Var *varPtr = NULL; /* Points to the element's Var structure - * that we return. */ - Tcl_Obj *resultPtr = NULL; - Tcl_Obj *oldValuePtr; - int new; - -#ifdef TCL_COMPILE_DEBUG - Proc *procPtr = varFramePtr->procPtr; - int localCt = procPtr->numCompiledLocals; + Var *arrayPtr; + ActiveVarTrace *activePtr; + Tcl_Obj *objPtr; + int result; + char *part1; - if (compiledLocals == NULL) { - fprintf(stderr, "\nTclSetElementOfIndexedArray: can't set element "); - fprintf(stderr, "of local %i in frame 0x%x, ", localIndex, - (unsigned int) varFramePtr); - fprintf(stderr, "no compiled locals\n"); - panic("TclSetIndexedScalar: no compiled locals in frame 0x%x", - (unsigned int) varFramePtr); - } - if ((localIndex < 0) || (localIndex >= localCt)) { - fprintf(stderr, "\nTclSetIndexedScalar: can't set element of "); - fprintf(stderr, "local %i in frame 0x%x ", localIndex, - (unsigned int) varFramePtr); - fprintf(stderr, "with %i locals\n", localCt); - panic("TclSetElementOfIndexedArray: bad local index %i in frame 0x%x", - localIndex, (unsigned int) varFramePtr); + part1 = TclGetString(part1Ptr); + varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, "unset", + /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); + if (varPtr == NULL) { + return TCL_ERROR; } -#endif /* TCL_COMPILE_DEBUG */ + + result = (TclIsVarUndefined(varPtr)? TCL_ERROR : TCL_OK); - elem = TclGetString(elemPtr); - arrayPtr = &(compiledLocals[localIndex]); - arrayName = arrayPtr->name; + if ((arrayPtr != NULL) && (arrayPtr->searchPtr != NULL)) { + DeleteSearches(arrayPtr); + } /* - * If arrayPtr is a link variable, we have a reference to some variable - * that was created through an "upvar" or "global" command, or we have a - * reference to a variable in an enclosing namespace. Traverse through - * any links until we find the referenced variable. + * The code below is tricky, because of the possibility that + * a trace procedure might try to access a variable being + * deleted. To handle this situation gracefully, do things + * in three steps: + * 1. Copy the contents of the variable to a dummy variable + * structure, and mark the original Var structure as undefined. + * 2. Invoke traces and clean up the variable, using the dummy copy. + * 3. If at the end of this the original variable is still + * undefined and has no outstanding references, then delete + * it (but it could have gotten recreated by a trace). */ - while (TclIsVarLink(arrayPtr)) { - arrayPtr = arrayPtr->value.linkPtr; - } + dummyVar = *varPtr; + TclSetVarUndefined(varPtr); + TclSetVarScalar(varPtr); + varPtr->value.objPtr = NULL; /* dummyVar points to any value object */ + varPtr->tracePtr = NULL; + varPtr->searchPtr = NULL; /* - * If the variable is in a hashtable and its hPtr field is NULL, then we - * may have an upvar to an array element where the array was deleted - * or an upvar to a namespace variable whose namespace was deleted. - * Generate an error (allowing the variable to be reset would screw up - * our storage allocation and is meaningless anyway). + * Call trace procedures for the variable being deleted. Then delete + * its traces. Be sure to abort any other traces for the variable + * that are still pending. Special tricks: + * 1. We need to increment varPtr's refCount around this: CallVarTraces + * will use dummyVar so it won't increment varPtr's refCount itself. + * 2. Turn off the VAR_TRACE_ACTIVE flag in dummyVar: we want to + * call unset traces even if other traces are pending. */ - if ((arrayPtr->flags & VAR_IN_HASHTABLE) && (arrayPtr->hPtr == NULL)) { - if (flags & TCL_LEAVE_ERR_MSG) { - if (TclIsVarArrayElement(arrayPtr)) { - VarErrMsg(interp, arrayName, elem, "set", danglingElement); - } else { - VarErrMsg(interp, arrayName, elem, "set", danglingVar); + if ((dummyVar.tracePtr != NULL) + || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { + varPtr->refCount++; + dummyVar.flags &= ~VAR_TRACE_ACTIVE; + CallVarTraces(iPtr, arrayPtr, &dummyVar, part1, part2, + (flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY)) + | TCL_TRACE_UNSETS, /* leaveErrMsg */ 0); + while (dummyVar.tracePtr != NULL) { + VarTrace *tracePtr = dummyVar.tracePtr; + dummyVar.tracePtr = tracePtr->nextPtr; + Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); + } + for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; + activePtr = activePtr->nextPtr) { + if (activePtr->varPtr == varPtr) { + activePtr->nextTracePtr = NULL; } } - goto errorReturn; + varPtr->refCount--; } /* - * Make sure we're dealing with an array. - */ - - if (TclIsVarUndefined(arrayPtr) && !TclIsVarArrayElement(arrayPtr)) { - TclSetVarArray(arrayPtr); - arrayPtr->value.tablePtr = - (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable)); - Tcl_InitHashTable(arrayPtr->value.tablePtr, TCL_STRING_KEYS); - TclClearVarUndefined(arrayPtr); - } else if (!TclIsVarArray(arrayPtr)) { - if (flags & TCL_LEAVE_ERR_MSG) { - VarErrMsg(interp, arrayName, elem, "set", needArray); - } - goto errorReturn; - } - - /* - * Look up the element. - */ - - hPtr = Tcl_CreateHashEntry(arrayPtr->value.tablePtr, elem, &new); - if (new) { - if (arrayPtr->searchPtr != NULL) { - DeleteSearches(arrayPtr); - } - varPtr = NewVar(); - Tcl_SetHashValue(hPtr, varPtr); - varPtr->hPtr = hPtr; - varPtr->nsPtr = varFramePtr->nsPtr; - TclSetVarArrayElement(varPtr); - } - varPtr = (Var *) Tcl_GetHashValue(hPtr); - - /* - * It's an error to try to set an array variable itself. - */ - - if (TclIsVarArray(varPtr)) { - if (flags & TCL_LEAVE_ERR_MSG) { - VarErrMsg(interp, arrayName, elem, "set", isArray); - } - goto errorReturn; - } - - /* - * Invoke any read traces that have been set for the variable if it - * is requested; this is only done in the core when lappending. - */ - - if ((flags & TCL_TRACE_READS) && ((varPtr->tracePtr != NULL) - || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL)))) { - if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, arrayName, elem, - TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { - goto errorReturn; - } - } - - /* - * Set the variable's new value and discard the old one. + * If the variable is an array, delete all of its elements. This must be + * done after calling the traces on the array, above (that's the way + * traces are defined). If it is a scalar, "discard" its object + * (decrement the ref count of its object, if any). */ - oldValuePtr = varPtr->value.objPtr; - if (flags & TCL_APPEND_VALUE) { - if (TclIsVarUndefined(varPtr) && (oldValuePtr != NULL)) { - Tcl_DecrRefCount(oldValuePtr); /* discard old value */ - varPtr->value.objPtr = NULL; - oldValuePtr = NULL; - } - if (flags & TCL_LIST_ELEMENT) { /* append list element */ - if (oldValuePtr == NULL) { - TclNewObj(oldValuePtr); - varPtr->value.objPtr = oldValuePtr; - Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ - } else if (Tcl_IsShared(oldValuePtr)) { - varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); - Tcl_DecrRefCount(oldValuePtr); - oldValuePtr = varPtr->value.objPtr; - Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ - } - if (Tcl_ListObjAppendElement(interp, oldValuePtr, - newValuePtr) != TCL_OK) { - return NULL; - } - } else { /* append string */ - /* - * We append newValuePtr's bytes but don't change its ref count. - */ - - if (oldValuePtr == NULL) { - varPtr->value.objPtr = newValuePtr; - Tcl_IncrRefCount(newValuePtr); - } else { - if (Tcl_IsShared(oldValuePtr)) { /* append to copy */ - varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); - TclDecrRefCount(oldValuePtr); - oldValuePtr = varPtr->value.objPtr; - Tcl_IncrRefCount(oldValuePtr); /* since var is ref */ - } - Tcl_AppendObjToObj(oldValuePtr, newValuePtr); - } - } - } else if (newValuePtr != oldValuePtr) { /* set new value */ + dummyVarPtr = &dummyVar; + if (TclIsVarArray(dummyVarPtr) && !TclIsVarUndefined(dummyVarPtr)) { /* - * In this case we are replacing the value, so we don't need to - * do more than swap the objects. + * Deleting the elements of the array may cause traces to be fired + * on those elements. Before deleting them, bump the reference count + * of the array, so that if those trace procs make a global or upvar + * link to the array, the array is not deleted when the call stack + * gets popped (we will delete the array ourselves later in this + * function). + * + * Bumping the count can lead to the odd situation that elements of the + * array are being deleted when the array still exists, but since the + * array is about to be removed anyway, that shouldn't really matter. */ - - varPtr->value.objPtr = newValuePtr; - Tcl_IncrRefCount(newValuePtr); /* var is another ref to obj */ - if (oldValuePtr != NULL) { - TclDecrRefCount(oldValuePtr); /* discard old value */ - } + varPtr->refCount++; + DeleteArray(iPtr, part1, dummyVarPtr, + (flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY)) + | TCL_TRACE_UNSETS); + /* Decr ref count */ + varPtr->refCount--; + } + if (TclIsVarScalar(dummyVarPtr) + && (dummyVarPtr->value.objPtr != NULL)) { + objPtr = dummyVarPtr->value.objPtr; + TclDecrRefCount(objPtr); + dummyVarPtr->value.objPtr = NULL; } - TclSetVarScalar(varPtr); - TclClearVarUndefined(varPtr); /* - * Invoke any write traces for the element variable. + * If the variable was a namespace variable, decrement its reference count. */ - - if ((varPtr->tracePtr != NULL) - || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { - if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, arrayName, elem, - TCL_TRACE_WRITES, (flags & TCL_LEAVE_ERR_MSG))) { - goto errorReturn; - } + + if (varPtr->flags & VAR_NAMESPACE_VAR) { + varPtr->flags &= ~VAR_NAMESPACE_VAR; + varPtr->refCount--; } /* - * Return the element's value unless it was changed in some gross way by - * a trace (e.g. it was unset and then recreated as an array). If it was - * changed is a gross way, just return an empty string object. + * It's an error to unset an undefined variable. */ - - if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) { - return varPtr->value.objPtr; + + if (result != TCL_OK) { + if (flags & TCL_LEAVE_ERR_MSG) { + VarErrMsg(interp, part1, part2, "unset", + ((arrayPtr == NULL) ? noSuchVar : noSuchElement)); + } } - - resultPtr = Tcl_NewObj(); /* - * An error. If the variable doesn't exist anymore and no-one's using - * it, then free up the relevant structures and hash table entries. + * Finally, if the variable is truly not in use then free up its Var + * structure and remove it from its hash table, if any. The ref count of + * its value object, if any, was decremented above. */ - errorReturn: - if ((varPtr != NULL) && TclIsVarUndefined(varPtr)) { - CleanupVar(varPtr, NULL); /* note: array isn't in hashtable */ - } - return resultPtr; + CleanupVar(varPtr, arrayPtr); + return result; } /* *---------------------------------------------------------------------- * - * TclIncrVar2 -- + * Tcl_TraceVar -- * - * Given a two-part variable name, which may refer either to a scalar - * variable or an element of an array, increment the Tcl object value - * of the variable by a specified amount. + * Arrange for reads and/or writes to a variable to cause a + * procedure to be invoked, which can monitor the operations + * and/or change their actions. * * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * variable. If the specified variable doesn't exist, or there is a - * clash in array usage, or an error occurs while executing variable - * traces, then NULL is returned and a message will be left in - * the interpreter's result. + * A standard Tcl return value. * * Side effects: - * The value of the given variable is incremented by the specified - * amount. If either the array or the entry didn't exist then a new - * variable is created. The ref count for the returned object is _not_ - * incremented to reflect the returned reference; if you want to keep a - * reference to the object you must increment its ref count yourself. + * A trace is set up on the variable given by varName, such that + * future references to the variable will be intermediated by + * proc. See the manual entry for complete details on the calling + * sequence for proc. * *---------------------------------------------------------------------- */ -Tcl_Obj * -TclIncrVar2(interp, part1Ptr, part2Ptr, incrAmount, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be found. */ - Tcl_Obj *part1Ptr; /* Points to an object holding the name of - * an array (if part2 is non-NULL) or the - * name of a variable. */ - Tcl_Obj *part2Ptr; /* If non-null, points to an object holding - * the name of an element in the array - * part1Ptr. */ - long incrAmount; /* Amount to be added to variable. */ - int flags; /* Various flags that tell how to incr value: - * any of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG. */ +int +Tcl_TraceVar(interp, varName, flags, proc, clientData) + Tcl_Interp *interp; /* Interpreter in which variable is + * to be traced. */ + char *varName; /* Name of variable; may end with "(index)" + * to signify an array reference. */ + int flags; /* OR-ed collection of bits, including any + * of TCL_TRACE_READS, TCL_TRACE_WRITES, + * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY, and + * TCL_NAMESPACE_ONLY. */ + Tcl_VarTraceProc *proc; /* Procedure to call when specified ops are + * invoked upon varName. */ + ClientData clientData; /* Arbitrary argument to pass to proc. */ { - Var *varPtr, *arrayPtr; - char *part1, *part2; - - part1 = TclGetString(part1Ptr); - part2 = ((part2Ptr == NULL)? NULL : TclGetString(part2Ptr)); - - varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, "read", - 0, 1, &arrayPtr); - if (varPtr == NULL) { - Tcl_AddObjErrorInfo(interp, - "\n (reading value of variable to increment)", -1); - return NULL; - } - return TclPtrIncrVar(interp, varPtr, arrayPtr, part1, part2, - incrAmount, flags); + return Tcl_TraceVar2(interp, varName, (char *) NULL, + flags, proc, clientData); } /* *---------------------------------------------------------------------- * - * TclPtrIncrVar -- + * Tcl_TraceVar2 -- * - * Given the pointers to a variable and possible containing array, - * increment the Tcl object value of the variable by a specified - * amount. + * Arrange for reads and/or writes to a variable to cause a + * procedure to be invoked, which can monitor the operations + * and/or change their actions. * * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * variable. If the specified variable doesn't exist, or there is a - * clash in array usage, or an error occurs while executing variable - * traces, then NULL is returned and a message will be left in - * the interpreter's result. + * A standard Tcl return value. * * Side effects: - * The value of the given variable is incremented by the specified - * amount. If either the array or the entry didn't exist then a new - * variable is created. The ref count for the returned object is _not_ - * incremented to reflect the returned reference; if you want to keep a - * reference to the object you must increment its ref count yourself. + * A trace is set up on the variable given by part1 and part2, such + * that future references to the variable will be intermediated by + * proc. See the manual entry for complete details on the calling + * sequence for proc. * *---------------------------------------------------------------------- */ -Tcl_Obj * -TclPtrIncrVar(interp, varPtr, arrayPtr, part1, part2, incrAmount, flags) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be found. */ - Var *varPtr; - Var *arrayPtr; - char *part1; /* Points to an object holding the name of - * an array (if part2 is non-NULL) or the - * name of a variable. */ - CONST char *part2; /* If non-null, points to an object holding - * the name of an element in the array - * part1Ptr. */ - long incrAmount; /* Amount to be added to variable. */ - int flags; /* Various flags that tell how to incr value: - * any of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE, - * TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG. */ +int +Tcl_TraceVar2(interp, part1, part2, flags, proc, clientData) + Tcl_Interp *interp; /* Interpreter in which variable is + * to be traced. */ + char *part1; /* Name of scalar variable or array. */ + CONST char *part2; /* Name of element within array; NULL means + * trace applies to scalar variable or array + * as-a-whole. */ + int flags; /* OR-ed collection of bits, including any + * of TCL_TRACE_READS, TCL_TRACE_WRITES, + * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY, + * and TCL_NAMESPACE_ONLY. */ + Tcl_VarTraceProc *proc; /* Procedure to call when specified ops are + * invoked upon varName. */ + ClientData clientData; /* Arbitrary argument to pass to proc. */ { - register Tcl_Obj *varValuePtr; - int createdNewObj; /* Set 1 if var's value object is shared - * so we must increment a copy (i.e. copy - * on write). */ - long i; - - varValuePtr = TclPtrGetVar(interp, varPtr, arrayPtr, part1, part2, flags); - - if (varValuePtr == NULL) { - Tcl_AddObjErrorInfo(interp, - "\n (reading value of variable to increment)", -1); - return NULL; + Var *varPtr, *arrayPtr; + register VarTrace *tracePtr; + int flagMask; + + /* + * We strip 'flags' down to just the parts which are relevant to + * TclLookupVar, to avoid conflicts between trace flags and + * internal namespace flags such as 'FIND_ONLY_NS'. This can + * now occur since we have trace flags with values 0x1000 and higher. + */ + flagMask = TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY; + varPtr = TclLookupVar(interp, part1, part2, + (flags & flagMask) | TCL_LEAVE_ERR_MSG, + "trace", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); + if (varPtr == NULL) { + return TCL_ERROR; } /* - * Increment the variable's value. If the object is unshared we can - * modify it directly, otherwise we must create a new copy to modify: - * this is "copy on write". Then free the variable's old string - * representation, if any, since it will no longer be valid. + * Check for a nonsense flag combination. Note that this is a + * panic() because there should be no code path that ever sets + * both flags. */ - - createdNewObj = 0; - if (Tcl_IsShared(varValuePtr)) { - varValuePtr = Tcl_DuplicateObj(varValuePtr); - createdNewObj = 1; - } -#ifdef TCL_WIDE_INT_IS_LONG - if (Tcl_GetLongFromObj(interp, varValuePtr, &i) != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ - } - return NULL; - } - Tcl_SetLongObj(varValuePtr, (i + incrAmount)); -#else - if (varValuePtr->typePtr == &tclWideIntType) { - Tcl_WideInt wide = varValuePtr->internalRep.wideValue; - Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); - } else if (varValuePtr->typePtr == &tclIntType) { - i = varValuePtr->internalRep.longValue; - Tcl_SetIntObj(varValuePtr, i + incrAmount); - } else { - /* - * Not an integer or wide internal-rep... - */ - Tcl_WideInt wide; - if (Tcl_GetWideIntFromObj(interp, varValuePtr, &wide) != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ - } - return NULL; - } - if (wide <= Tcl_LongAsWide(LONG_MAX) - && wide >= Tcl_LongAsWide(LONG_MIN)) { - Tcl_SetLongObj(varValuePtr, Tcl_WideAsLong(wide) + incrAmount); - } else { - Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); - } + if ((flags&TCL_TRACE_RESULT_DYNAMIC) && (flags&TCL_TRACE_RESULT_OBJECT)) { + panic("bad result flag combination"); } -#endif /* - * Store the variable's new value and run any write traces. + * Set up trace information. */ - - return TclPtrSetVar(interp, varPtr, arrayPtr, part1, part2, - varValuePtr, flags); + + flagMask = TCL_TRACE_READS | TCL_TRACE_WRITES | TCL_TRACE_UNSETS | + TCL_TRACE_ARRAY | TCL_TRACE_RESULT_DYNAMIC | TCL_TRACE_RESULT_OBJECT; +#ifndef TCL_REMOVE_OBSOLETE_TRACES + flagMask |= TCL_TRACE_OLD_STYLE; +#endif + tracePtr = (VarTrace *) ckalloc(sizeof(VarTrace)); + tracePtr->traceProc = proc; + tracePtr->clientData = clientData; + tracePtr->flags = flags & flagMask; + tracePtr->nextPtr = varPtr->tracePtr; + varPtr->tracePtr = tracePtr; + return TCL_OK; } /* *---------------------------------------------------------------------- * - * TclIncrIndexedScalar -- + * Tcl_UntraceVar -- * - * Increments the Tcl object value of a local scalar variable in the - * active procedure, given its compile-time allocated index in the - * procedure's array of local variables. + * Remove a previously-created trace for a variable. * * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * variable given by localIndex. If the specified variable doesn't - * exist, or there is a clash in array usage, or an error occurs while - * executing variable traces, then NULL is returned and a message will - * be left in the interpreter's result. + * None. * * Side effects: - * The value of the given variable is incremented by the specified - * amount. The ref count for the returned object is _not_ incremented - * to reflect the returned reference; if you want to keep a reference - * to the object you must increment its ref count yourself. + * If there exists a trace for the variable given by varName + * with the given flags, proc, and clientData, then that trace + * is removed. * *---------------------------------------------------------------------- */ -Tcl_Obj * -TclIncrIndexedScalar(interp, localIndex, incrAmount) - Tcl_Interp *interp; /* Command interpreter in which variable is - * to be found. */ - int localIndex; /* Index of variable in procedure's array - * of local variables. */ - long incrAmount; /* Amount to be added to variable. */ +void +Tcl_UntraceVar(interp, varName, flags, proc, clientData) + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *varName; /* Name of variable; may end with "(index)" + * to signify an array reference. */ + int flags; /* OR-ed collection of bits describing + * current trace, including any of + * TCL_TRACE_READS, TCL_TRACE_WRITES, + * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY + * and TCL_NAMESPACE_ONLY. */ + Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ + ClientData clientData; /* Arbitrary argument to pass to proc. */ { - register Tcl_Obj *varValuePtr; - int createdNewObj; /* Set 1 if var's value object is shared - * so we must increment a copy (i.e. copy - * on write). */ - long i; - - varValuePtr = TclGetIndexedScalar(interp, localIndex, TCL_LEAVE_ERR_MSG); - if (varValuePtr == NULL) { - Tcl_AddObjErrorInfo(interp, - "\n (reading value of variable to increment)", -1); - return NULL; - } - - /* - * Reach into the object's representation to extract and increment the - * variable's value. If the object is unshared we can modify it - * directly, otherwise we must create a new copy to modify: this is - * "copy on write". Then free the variable's old string representation, - * if any, since it will no longer be valid. - */ - - createdNewObj = 0; - if (Tcl_IsShared(varValuePtr)) { - createdNewObj = 1; - varValuePtr = Tcl_DuplicateObj(varValuePtr); - } -#ifdef TCL_WIDE_INT_IS_LONG - if (Tcl_GetLongFromObj(interp, varValuePtr, &i) != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ - } - return NULL; - } - Tcl_SetLongObj(varValuePtr, (i + incrAmount)); -#else - if (varValuePtr->typePtr == &tclWideIntType) { - Tcl_WideInt wide = varValuePtr->internalRep.wideValue; - Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); - } else if (varValuePtr->typePtr == &tclIntType) { - i = varValuePtr->internalRep.longValue; - Tcl_SetIntObj(varValuePtr, i + incrAmount); - } else { - /* - * Not an integer or wide internal-rep... - */ - Tcl_WideInt wide; - if (Tcl_GetWideIntFromObj(interp, varValuePtr, &wide) != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ - } - return NULL; - } - if (wide <= Tcl_LongAsWide(LONG_MAX) - && wide >= Tcl_LongAsWide(LONG_MIN)) { - Tcl_SetLongObj(varValuePtr, Tcl_WideAsLong(wide) + incrAmount); - } else { - Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); - } - } -#endif - - /* - * Store the variable's new value and run any write traces. - */ - - return TclSetIndexedScalar(interp, localIndex, varValuePtr, - TCL_LEAVE_ERR_MSG); + Tcl_UntraceVar2(interp, varName, (char *) NULL, flags, proc, clientData); } /* *---------------------------------------------------------------------- * - * TclIncrElementOfIndexedArray -- + * Tcl_UntraceVar2 -- * - * Increments the Tcl object value of an element in a local array - * variable. The element is named by the object elemPtr while the array - * is specified by its index in the active procedure's array of - * compiler allocated local variables. + * Remove a previously-created trace for a variable. * * Results: - * Returns a pointer to the Tcl_Obj holding the new value of the - * element. If the specified array or element doesn't exist, or there - * is a clash in array usage, or an error occurs while executing - * variable traces, then NULL is returned and a message will be left in - * the interpreter's result. + * None. * * Side effects: - * The value of the given array element is incremented by the specified - * amount. The ref count for the returned object is _not_ incremented - * to reflect the returned reference; if you want to keep a reference - * to the object you must increment its ref count yourself. If the - * entry doesn't exist then a new variable is created. + * If there exists a trace for the variable given by part1 + * and part2 with the given flags, proc, and clientData, then + * that trace is removed. * *---------------------------------------------------------------------- */ -Tcl_Obj * -TclIncrElementOfIndexedArray(interp, localIndex, elemPtr, incrAmount) - Tcl_Interp *interp; /* Command interpreter in which the array is - * to be found. */ - int localIndex; /* Index of array variable in procedure's - * array of local variables. */ - Tcl_Obj *elemPtr; /* Points to an object holding the name of - * an element to increment in the array. */ - long incrAmount; /* Amount to be added to variable. */ +void +Tcl_UntraceVar2(interp, part1, part2, flags, proc, clientData) + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *part1; /* Name of variable or array. */ + CONST char *part2; /* Name of element within array; NULL means + * trace applies to scalar variable or array + * as-a-whole. */ + int flags; /* OR-ed collection of bits describing + * current trace, including any of + * TCL_TRACE_READS, TCL_TRACE_WRITES, + * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY, + * and TCL_NAMESPACE_ONLY. */ + Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ + ClientData clientData; /* Arbitrary argument to pass to proc. */ { - register Tcl_Obj *varValuePtr; - int createdNewObj; /* Set 1 if var's value object is shared - * so we must increment a copy (i.e. copy - * on write). */ - long i; + register VarTrace *tracePtr; + VarTrace *prevPtr; + Var *varPtr, *arrayPtr; + Interp *iPtr = (Interp *) interp; + ActiveVarTrace *activePtr; + int flagMask; + + /* + * Set up a mask to mask out the parts of the flags that we are not + * interested in now. + */ + flagMask = TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY; + varPtr = TclLookupVar(interp, part1, part2, flags & flagMask, + /*msg*/ (char *) NULL, + /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); + if (varPtr == NULL) { + return; + } - varValuePtr = TclGetElementOfIndexedArray(interp, localIndex, elemPtr, - TCL_LEAVE_ERR_MSG); - if (varValuePtr == NULL) { - Tcl_AddObjErrorInfo(interp, - "\n (reading value of variable to increment)", -1); - return NULL; + + /* + * Set up a mask to mask out the parts of the flags that we are not + * interested in now. + */ + flagMask = TCL_TRACE_READS | TCL_TRACE_WRITES | TCL_TRACE_UNSETS | + TCL_TRACE_ARRAY | TCL_TRACE_RESULT_DYNAMIC | TCL_TRACE_RESULT_OBJECT; +#ifndef TCL_REMOVE_OBSOLETE_TRACES + flagMask |= TCL_TRACE_OLD_STYLE; +#endif + flags &= flagMask; + for (tracePtr = varPtr->tracePtr, prevPtr = NULL; ; + prevPtr = tracePtr, tracePtr = tracePtr->nextPtr) { + if (tracePtr == NULL) { + return; + } + if ((tracePtr->traceProc == proc) && (tracePtr->flags == flags) + && (tracePtr->clientData == clientData)) { + break; + } } /* - * Reach into the object's representation to extract and increment the - * variable's value. If the object is unshared we can modify it - * directly, otherwise we must create a new copy to modify: this is - * "copy on write". Then free the variable's old string representation, - * if any, since it will no longer be valid. + * The code below makes it possible to delete traces while traces + * are active: it makes sure that the deleted trace won't be + * processed by CallVarTraces. */ - createdNewObj = 0; - if (Tcl_IsShared(varValuePtr)) { - createdNewObj = 1; - varValuePtr = Tcl_DuplicateObj(varValuePtr); - } -#ifdef TCL_WIDE_INT_IS_LONG - if (Tcl_GetLongFromObj(interp, varValuePtr, &i) != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ + for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; + activePtr = activePtr->nextPtr) { + if (activePtr->nextTracePtr == tracePtr) { + activePtr->nextTracePtr = tracePtr->nextPtr; } - return NULL; } - Tcl_SetLongObj(varValuePtr, (i + incrAmount)); -#else - if (varValuePtr->typePtr == &tclWideIntType) { - Tcl_WideInt wide = varValuePtr->internalRep.wideValue; - Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); - } else if (varValuePtr->typePtr == &tclIntType) { - i = varValuePtr->internalRep.longValue; - Tcl_SetIntObj(varValuePtr, i + incrAmount); + if (prevPtr == NULL) { + varPtr->tracePtr = tracePtr->nextPtr; } else { - /* - * Not an integer or wide internal-rep... - */ - Tcl_WideInt wide; - if (Tcl_GetWideIntFromObj(interp, varValuePtr, &wide) != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ - } - return NULL; - } - if (wide <= Tcl_LongAsWide(LONG_MAX) - && wide >= Tcl_LongAsWide(LONG_MIN)) { - Tcl_SetLongObj(varValuePtr, Tcl_WideAsLong(wide) + incrAmount); - } else { - Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); - } + prevPtr->nextPtr = tracePtr->nextPtr; } -#endif + Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); /* - * Store the variable's new value and run any write traces. + * If this is the last trace on the variable, and the variable is + * unset and unused, then free up the variable. */ - - return TclSetElementOfIndexedArray(interp, localIndex, elemPtr, - varValuePtr, TCL_LEAVE_ERR_MSG); + + if (TclIsVarUndefined(varPtr)) { + CleanupVar(varPtr, (Var *) NULL); + } } /* *---------------------------------------------------------------------- * - * Tcl_UnsetVar -- + * Tcl_VarTraceInfo -- * - * Delete a variable, so that it may not be accessed anymore. + * Return the clientData value associated with a trace on a + * variable. This procedure can also be used to step through + * all of the traces on a particular variable that have the + * same trace procedure. * * Results: - * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR - * if the variable can't be unset. In the event of an error, - * if the TCL_LEAVE_ERR_MSG flag is set then an error message - * is left in the interp's result. + * The return value is the clientData value associated with + * a trace on the given variable. Information will only be + * returned for a trace with proc as trace procedure. If + * the clientData argument is NULL then the first such trace is + * returned; otherwise, the next relevant one after the one + * given by clientData will be returned. If the variable + * doesn't exist, or if there are no (more) traces for it, + * then NULL is returned. * * Side effects: - * If varName is defined as a local or global variable in interp, - * it is deleted. + * None. * *---------------------------------------------------------------------- */ -int -Tcl_UnsetVar(interp, varName, flags) - Tcl_Interp *interp; /* Command interpreter in which varName is - * to be looked up. */ - char *varName; /* Name of a variable in interp. May be - * either a scalar name or an array name - * or an element in an array. */ - int flags; /* OR-ed combination of any of - * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY or - * TCL_LEAVE_ERR_MSG. */ +ClientData +Tcl_VarTraceInfo(interp, varName, flags, proc, prevClientData) + Tcl_Interp *interp; /* Interpreter containing variable. */ + char *varName; /* Name of variable; may end with "(index)" + * to signify an array reference. */ + int flags; /* OR-ed combo or TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY (can be 0). */ + Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ + ClientData prevClientData; /* If non-NULL, gives last value returned + * by this procedure, so this call will + * return the next trace after that one. + * If NULL, this call will return the + * first trace. */ { - return Tcl_UnsetVar2(interp, varName, (char *) NULL, flags); + return Tcl_VarTraceInfo2(interp, varName, (char *) NULL, + flags, proc, prevClientData); } /* *---------------------------------------------------------------------- * - * Tcl_UnsetVar2 -- + * Tcl_VarTraceInfo2 -- * - * Delete a variable, given a 2-part name. + * Same as Tcl_VarTraceInfo, except takes name in two pieces + * instead of one. * * Results: - * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR - * if the variable can't be unset. In the event of an error, - * if the TCL_LEAVE_ERR_MSG flag is set then an error message - * is left in the interp's result. + * Same as Tcl_VarTraceInfo. * * Side effects: - * If part1 and part2 indicate a local or global variable in interp, - * it is deleted. If part1 is an array name and part2 is NULL, then - * the whole array is deleted. + * None. * *---------------------------------------------------------------------- */ -int -Tcl_UnsetVar2(interp, part1, part2, flags) - Tcl_Interp *interp; /* Command interpreter in which varName is - * to be looked up. */ +ClientData +Tcl_VarTraceInfo2(interp, part1, part2, flags, proc, prevClientData) + Tcl_Interp *interp; /* Interpreter containing variable. */ char *part1; /* Name of variable or array. */ - CONST char *part2; /* Name of element within array or NULL. */ - int flags; /* OR-ed combination of any of - * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, - * TCL_LEAVE_ERR_MSG. */ + CONST char *part2; /* Name of element within array; NULL means + * trace applies to scalar variable or array + * as-a-whole. */ + int flags; /* OR-ed combination of TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY. */ + Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ + ClientData prevClientData; /* If non-NULL, gives last value returned + * by this procedure, so this call will + * return the next trace after that one. + * If NULL, this call will return the + * first trace. */ { - int result; - Tcl_Obj *part1Ptr; + register VarTrace *tracePtr; + Var *varPtr, *arrayPtr; - part1Ptr = Tcl_NewStringObj(part1, -1); - Tcl_IncrRefCount(part1Ptr); - result = TclObjUnsetVar2(interp, part1Ptr, part2, flags); - TclDecrRefCount(part1Ptr); + varPtr = TclLookupVar(interp, part1, part2, + flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY), + /*msg*/ (char *) NULL, + /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); + if (varPtr == NULL) { + return NULL; + } - return result; -} + /* + * Find the relevant trace, if any, and return its clientData. + */ - -/* - *---------------------------------------------------------------------- - * - * TclObjUnsetVar2 -- - * - * Delete a variable, given a 2-object name. - * - * Results: - * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR - * if the variable can't be unset. In the event of an error, - * if the TCL_LEAVE_ERR_MSG flag is set then an error message - * is left in the interp's result. + tracePtr = varPtr->tracePtr; + if (prevClientData != NULL) { + for ( ; tracePtr != NULL; tracePtr = tracePtr->nextPtr) { + if ((tracePtr->clientData == prevClientData) + && (tracePtr->traceProc == proc)) { + tracePtr = tracePtr->nextPtr; + break; + } + } + } + for ( ; tracePtr != NULL; tracePtr = tracePtr->nextPtr) { + if (tracePtr->traceProc == proc) { + return tracePtr->clientData; + } + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_UnsetObjCmd -- + * + * This object-based procedure is invoked to process the "unset" Tcl + * command. See the user documentation for details on what it does. + * + * Results: + * A standard Tcl object result value. * * Side effects: - * If part1ptr and part2Ptr indicate a local or global variable in interp, - * it is deleted. If part1Ptr is an array name and part2Ptr is NULL, then - * the whole array is deleted. + * See the user documentation. * *---------------------------------------------------------------------- */ + /* ARGSUSED */ int -TclObjUnsetVar2(interp, part1Ptr, part2, flags) - Tcl_Interp *interp; /* Command interpreter in which varName is - * to be looked up. */ - Tcl_Obj *part1Ptr; /* Name of variable or array. */ - CONST char *part2; /* Name of element within array or NULL. */ - int flags; /* OR-ed combination of any of - * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, - * TCL_LEAVE_ERR_MSG. */ +Tcl_UnsetObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { - Var dummyVar; - Var *varPtr, *dummyVarPtr; - Interp *iPtr = (Interp *) interp; - Var *arrayPtr; - ActiveVarTrace *activePtr; - Tcl_Obj *objPtr; - int result; - char *part1; + register int i, flags = TCL_LEAVE_ERR_MSG; + register char *name; - part1 = TclGetString(part1Ptr); - varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, "unset", - /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); - if (varPtr == NULL) { + if (objc < 1) { + Tcl_WrongNumArgs(interp, 1, objv, + "?-nocomplain? ?--? ?varName varName ...?"); return TCL_ERROR; - } - - result = (TclIsVarUndefined(varPtr)? TCL_ERROR : TCL_OK); - - if ((arrayPtr != NULL) && (arrayPtr->searchPtr != NULL)) { - DeleteSearches(arrayPtr); - } - - /* - * The code below is tricky, because of the possibility that - * a trace procedure might try to access a variable being - * deleted. To handle this situation gracefully, do things - * in three steps: - * 1. Copy the contents of the variable to a dummy variable - * structure, and mark the original Var structure as undefined. - * 2. Invoke traces and clean up the variable, using the dummy copy. - * 3. If at the end of this the original variable is still - * undefined and has no outstanding references, then delete - * it (but it could have gotten recreated by a trace). - */ - - dummyVar = *varPtr; - TclSetVarUndefined(varPtr); - TclSetVarScalar(varPtr); - varPtr->value.objPtr = NULL; /* dummyVar points to any value object */ - varPtr->tracePtr = NULL; - varPtr->searchPtr = NULL; - - /* - * Call trace procedures for the variable being deleted. Then delete - * its traces. Be sure to abort any other traces for the variable - * that are still pending. Special tricks: - * 1. We need to increment varPtr's refCount around this: CallVarTraces - * will use dummyVar so it won't increment varPtr's refCount itself. - * 2. Turn off the VAR_TRACE_ACTIVE flag in dummyVar: we want to - * call unset traces even if other traces are pending. - */ - - if ((dummyVar.tracePtr != NULL) - || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { - varPtr->refCount++; - dummyVar.flags &= ~VAR_TRACE_ACTIVE; - CallVarTraces(iPtr, arrayPtr, &dummyVar, part1, part2, - (flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY)) - | TCL_TRACE_UNSETS, /* leaveErrMsg */ 0); - while (dummyVar.tracePtr != NULL) { - VarTrace *tracePtr = dummyVar.tracePtr; - dummyVar.tracePtr = tracePtr->nextPtr; - Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); - } - for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; - activePtr = activePtr->nextPtr) { - if (activePtr->varPtr == varPtr) { - activePtr->nextTracePtr = NULL; - } - } - varPtr->refCount--; - } - - /* - * If the variable is an array, delete all of its elements. This must be - * done after calling the traces on the array, above (that's the way - * traces are defined). If it is a scalar, "discard" its object - * (decrement the ref count of its object, if any). - */ - - dummyVarPtr = &dummyVar; - if (TclIsVarArray(dummyVarPtr) && !TclIsVarUndefined(dummyVarPtr)) { + } else if (objc == 1) { /* - * Deleting the elements of the array may cause traces to be fired - * on those elements. Before deleting them, bump the reference count - * of the array, so that if those trace procs make a global or upvar - * link to the array, the array is not deleted when the call stack - * gets popped (we will delete the array ourselves later in this - * function). - * - * Bumping the count can lead to the odd situation that elements of the - * array are being deleted when the array still exists, but since the - * array is about to be removed anyway, that shouldn't really matter. + * Do nothing if no arguments supplied, so as to match + * command documentation. */ - varPtr->refCount++; - DeleteArray(iPtr, part1, dummyVarPtr, - (flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY)) - | TCL_TRACE_UNSETS); - /* Decr ref count */ - varPtr->refCount--; - } - if (TclIsVarScalar(dummyVarPtr) - && (dummyVarPtr->value.objPtr != NULL)) { - objPtr = dummyVarPtr->value.objPtr; - TclDecrRefCount(objPtr); - dummyVarPtr->value.objPtr = NULL; + return TCL_OK; } /* - * If the variable was a namespace variable, decrement its reference count. + * Simple, restrictive argument parsing. The only options are -- + * and -nocomplain (which must come first and be given exactly to + * be an option). */ - - if (varPtr->flags & VAR_NAMESPACE_VAR) { - varPtr->flags &= ~VAR_NAMESPACE_VAR; - varPtr->refCount--; + i = 1; + name = TclGetString(objv[i]); + if (name[0] == '-') { + if (strcmp("-nocomplain", name) == 0) { + i++; + if (i == objc) { + return TCL_OK; + } + flags = 0; + name = TclGetString(objv[i]); + } + if (strcmp("--", name) == 0) { + i++; + } } - /* - * It's an error to unset an undefined variable. - */ - - if (result != TCL_OK) { - if (flags & TCL_LEAVE_ERR_MSG) { - VarErrMsg(interp, part1, part2, "unset", - ((arrayPtr == NULL) ? noSuchVar : noSuchElement)); + for (; i < objc; i++) { + if ((TclObjUnsetVar2(interp, objv[i], NULL, flags) != TCL_OK) + && (flags == TCL_LEAVE_ERR_MSG)) { + return TCL_ERROR; } } - - /* - * Finally, if the variable is truly not in use then free up its Var - * structure and remove it from its hash table, if any. The ref count of - * its value object, if any, was decremented above. - */ - - CleanupVar(varPtr, arrayPtr); - return result; + return TCL_OK; } /* *---------------------------------------------------------------------- * - * Tcl_TraceVar -- + * Tcl_AppendObjCmd -- * - * Arrange for reads and/or writes to a variable to cause a - * procedure to be invoked, which can monitor the operations - * and/or change their actions. + * This object-based procedure is invoked to process the "append" + * Tcl command. See the user documentation for details on what it does. * * Results: - * A standard Tcl return value. + * A standard Tcl object result value. * * Side effects: - * A trace is set up on the variable given by varName, such that - * future references to the variable will be intermediated by - * proc. See the manual entry for complete details on the calling - * sequence for proc. + * A variable's value may be changed. * *---------------------------------------------------------------------- */ + /* ARGSUSED */ int -Tcl_TraceVar(interp, varName, flags, proc, clientData) - Tcl_Interp *interp; /* Interpreter in which variable is - * to be traced. */ - char *varName; /* Name of variable; may end with "(index)" - * to signify an array reference. */ - int flags; /* OR-ed collection of bits, including any - * of TCL_TRACE_READS, TCL_TRACE_WRITES, - * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY, and - * TCL_NAMESPACE_ONLY. */ - Tcl_VarTraceProc *proc; /* Procedure to call when specified ops are - * invoked upon varName. */ - ClientData clientData; /* Arbitrary argument to pass to proc. */ -{ - return Tcl_TraceVar2(interp, varName, (char *) NULL, - flags, proc, clientData); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_TraceVar2 -- - * - * Arrange for reads and/or writes to a variable to cause a - * procedure to be invoked, which can monitor the operations - * and/or change their actions. - * - * Results: - * A standard Tcl return value. - * - * Side effects: - * A trace is set up on the variable given by part1 and part2, such - * that future references to the variable will be intermediated by - * proc. See the manual entry for complete details on the calling - * sequence for proc. - * - *---------------------------------------------------------------------- - */ - -int -Tcl_TraceVar2(interp, part1, part2, flags, proc, clientData) - Tcl_Interp *interp; /* Interpreter in which variable is - * to be traced. */ - char *part1; /* Name of scalar variable or array. */ - CONST char *part2; /* Name of element within array; NULL means - * trace applies to scalar variable or array - * as-a-whole. */ - int flags; /* OR-ed collection of bits, including any - * of TCL_TRACE_READS, TCL_TRACE_WRITES, - * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY, - * and TCL_NAMESPACE_ONLY. */ - Tcl_VarTraceProc *proc; /* Procedure to call when specified ops are - * invoked upon varName. */ - ClientData clientData; /* Arbitrary argument to pass to proc. */ +Tcl_AppendObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { Var *varPtr, *arrayPtr; - register VarTrace *tracePtr; - int flagMask; - - /* - * We strip 'flags' down to just the parts which are relevant to - * TclLookupVar, to avoid conflicts between trace flags and - * internal namespace flags such as 'FIND_ONLY_NS'. This can - * now occur since we have trace flags with values 0x1000 and higher. - */ - flagMask = TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY; - varPtr = TclLookupVar(interp, part1, part2, - (flags & flagMask) | TCL_LEAVE_ERR_MSG, - "trace", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); - if (varPtr == NULL) { - return TCL_ERROR; - } + char *part1; - /* - * Check for a nonsense flag combination. Note that this is a - * panic() because there should be no code path that ever sets - * both flags. - */ - if ((flags&TCL_TRACE_RESULT_DYNAMIC) && (flags&TCL_TRACE_RESULT_OBJECT)) { - panic("bad result flag combination"); + register Tcl_Obj *varValuePtr = NULL; + /* Initialized to avoid compiler + * warning. */ + int i; + + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "varName ?value value ...?"); + return TCL_ERROR; } - /* - * Set up trace information. - */ + if (objc == 2) { + varValuePtr = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); + if (varValuePtr == NULL) { + return TCL_ERROR; + } + } else { + varPtr = TclObjLookupVar(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG, + "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); + part1 = TclGetString(objv[1]); + if (varPtr == NULL) { + return TCL_ERROR; + } + for (i = 2; i < objc; i++) { + /* + * Note that we do not need to increase the refCount of + * the Var pointers: should a trace delete the variable, + * the return value of TclPtrSetVar will be NULL, and we + * will not access the variable again. + */ - flagMask = TCL_TRACE_READS | TCL_TRACE_WRITES | TCL_TRACE_UNSETS | - TCL_TRACE_ARRAY | TCL_TRACE_RESULT_DYNAMIC | TCL_TRACE_RESULT_OBJECT; -#ifndef TCL_REMOVE_OBSOLETE_TRACES - flagMask |= TCL_TRACE_OLD_STYLE; -#endif - tracePtr = (VarTrace *) ckalloc(sizeof(VarTrace)); - tracePtr->traceProc = proc; - tracePtr->clientData = clientData; - tracePtr->flags = flags & flagMask; - tracePtr->nextPtr = varPtr->tracePtr; - varPtr->tracePtr = tracePtr; + varValuePtr = TclPtrSetVar(interp, varPtr, arrayPtr, part1, NULL, + objv[i], (TCL_APPEND_VALUE | TCL_LEAVE_ERR_MSG)); + if (varValuePtr == NULL) { + return TCL_ERROR; + } + } + } + Tcl_SetObjResult(interp, varValuePtr); return TCL_OK; } /* *---------------------------------------------------------------------- * - * Tcl_UntraceVar -- - * - * Remove a previously-created trace for a variable. - * - * Results: - * None. - * - * Side effects: - * If there exists a trace for the variable given by varName - * with the given flags, proc, and clientData, then that trace - * is removed. - * - *---------------------------------------------------------------------- - */ - -void -Tcl_UntraceVar(interp, varName, flags, proc, clientData) - Tcl_Interp *interp; /* Interpreter containing variable. */ - char *varName; /* Name of variable; may end with "(index)" - * to signify an array reference. */ - int flags; /* OR-ed collection of bits describing - * current trace, including any of - * TCL_TRACE_READS, TCL_TRACE_WRITES, - * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY - * and TCL_NAMESPACE_ONLY. */ - Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ - ClientData clientData; /* Arbitrary argument to pass to proc. */ -{ - Tcl_UntraceVar2(interp, varName, (char *) NULL, flags, proc, clientData); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_UntraceVar2 -- + * Tcl_LappendObjCmd -- * - * Remove a previously-created trace for a variable. + * This object-based procedure is invoked to process the "lappend" + * Tcl command. See the user documentation for details on what it does. * * Results: - * None. + * A standard Tcl object result value. * * Side effects: - * If there exists a trace for the variable given by part1 - * and part2 with the given flags, proc, and clientData, then - * that trace is removed. + * A variable's value may be changed. * *---------------------------------------------------------------------- */ -void -Tcl_UntraceVar2(interp, part1, part2, flags, proc, clientData) - Tcl_Interp *interp; /* Interpreter containing variable. */ - char *part1; /* Name of variable or array. */ - CONST char *part2; /* Name of element within array; NULL means - * trace applies to scalar variable or array - * as-a-whole. */ - int flags; /* OR-ed collection of bits describing - * current trace, including any of - * TCL_TRACE_READS, TCL_TRACE_WRITES, - * TCL_TRACE_UNSETS, TCL_GLOBAL_ONLY, - * and TCL_NAMESPACE_ONLY. */ - Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ - ClientData clientData; /* Arbitrary argument to pass to proc. */ + /* ARGSUSED */ +int +Tcl_LappendObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { - register VarTrace *tracePtr; - VarTrace *prevPtr; + Tcl_Obj *varValuePtr, *newValuePtr; + register List *listRepPtr; + register Tcl_Obj **elemPtrs; + int numElems, numRequired, createdNewObj, createVar, i, j; Var *varPtr, *arrayPtr; - Interp *iPtr = (Interp *) interp; - ActiveVarTrace *activePtr; - int flagMask; - - /* - * Set up a mask to mask out the parts of the flags that we are not - * interested in now. - */ - flagMask = TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY; - varPtr = TclLookupVar(interp, part1, part2, flags & flagMask, - /*msg*/ (char *) NULL, - /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); - if (varPtr == NULL) { - return; - } - + char *part1; - /* - * Set up a mask to mask out the parts of the flags that we are not - * interested in now. - */ - flagMask = TCL_TRACE_READS | TCL_TRACE_WRITES | TCL_TRACE_UNSETS | - TCL_TRACE_ARRAY | TCL_TRACE_RESULT_DYNAMIC | TCL_TRACE_RESULT_OBJECT; -#ifndef TCL_REMOVE_OBSOLETE_TRACES - flagMask |= TCL_TRACE_OLD_STYLE; -#endif - flags &= flagMask; - for (tracePtr = varPtr->tracePtr, prevPtr = NULL; ; - prevPtr = tracePtr, tracePtr = tracePtr->nextPtr) { - if (tracePtr == NULL) { - return; - } - if ((tracePtr->traceProc == proc) && (tracePtr->flags == flags) - && (tracePtr->clientData == clientData)) { - break; - } + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "varName ?value value ...?"); + return TCL_ERROR; } - - /* - * The code below makes it possible to delete traces while traces - * are active: it makes sure that the deleted trace won't be - * processed by CallVarTraces. - */ - - for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; - activePtr = activePtr->nextPtr) { - if (activePtr->nextTracePtr == tracePtr) { - activePtr->nextTracePtr = tracePtr->nextPtr; + if (objc == 2) { + newValuePtr = Tcl_ObjGetVar2(interp, objv[1], (Tcl_Obj *) NULL, 0); + if (newValuePtr == NULL) { + /* + * The variable doesn't exist yet. Just create it with an empty + * initial value. + */ + + varValuePtr = Tcl_NewObj(); + newValuePtr = Tcl_ObjSetVar2(interp, objv[1], NULL, varValuePtr, + TCL_LEAVE_ERR_MSG); + if (newValuePtr == NULL) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded object */ + return TCL_ERROR; + } } - } - if (prevPtr == NULL) { - varPtr->tracePtr = tracePtr->nextPtr; } else { - prevPtr->nextPtr = tracePtr->nextPtr; - } - Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); + /* + * We have arguments to append. We used to call Tcl_SetVar2 to + * append each argument one at a time to ensure that traces were run + * for each append step. We now append the arguments all at once + * because it's faster. Note that a read trace and a write trace for + * the variable will now each only be called once. Also, if the + * variable's old value is unshared we modify it directly, otherwise + * we create a new copy to modify: this is "copy on write". + */ - /* - * If this is the last trace on the variable, and the variable is - * unset and unused, then free up the variable. - */ + createdNewObj = 0; + createVar = 1; - if (TclIsVarUndefined(varPtr)) { - CleanupVar(varPtr, (Var *) NULL); - } -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_VarTraceInfo -- - * - * Return the clientData value associated with a trace on a - * variable. This procedure can also be used to step through - * all of the traces on a particular variable that have the - * same trace procedure. - * - * Results: - * The return value is the clientData value associated with - * a trace on the given variable. Information will only be - * returned for a trace with proc as trace procedure. If - * the clientData argument is NULL then the first such trace is - * returned; otherwise, the next relevant one after the one - * given by clientData will be returned. If the variable - * doesn't exist, or if there are no (more) traces for it, - * then NULL is returned. - * - * Side effects: - * None. - * - *---------------------------------------------------------------------- - */ - -ClientData -Tcl_VarTraceInfo(interp, varName, flags, proc, prevClientData) - Tcl_Interp *interp; /* Interpreter containing variable. */ - char *varName; /* Name of variable; may end with "(index)" - * to signify an array reference. */ - int flags; /* OR-ed combo or TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY (can be 0). */ - Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ - ClientData prevClientData; /* If non-NULL, gives last value returned - * by this procedure, so this call will - * return the next trace after that one. - * If NULL, this call will return the - * first trace. */ -{ - return Tcl_VarTraceInfo2(interp, varName, (char *) NULL, - flags, proc, prevClientData); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_VarTraceInfo2 -- - * - * Same as Tcl_VarTraceInfo, except takes name in two pieces - * instead of one. - * - * Results: - * Same as Tcl_VarTraceInfo. - * - * Side effects: - * None. - * - *---------------------------------------------------------------------- - */ + /* + * Use the TCL_TRACE_READS flag to ensure that if we have an + * array with no elements set yet, but with a read trace on it, + * we will create the variable and get read traces triggered. + * Note that you have to protect the variable pointers around + * the TclPtrGetVar call to insure that they remain valid + * even if the variable was undefined and unused. + */ -ClientData -Tcl_VarTraceInfo2(interp, part1, part2, flags, proc, prevClientData) - Tcl_Interp *interp; /* Interpreter containing variable. */ - char *part1; /* Name of variable or array. */ - CONST char *part2; /* Name of element within array; NULL means - * trace applies to scalar variable or array - * as-a-whole. */ - int flags; /* OR-ed combination of TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY. */ - Tcl_VarTraceProc *proc; /* Procedure assocated with trace. */ - ClientData prevClientData; /* If non-NULL, gives last value returned - * by this procedure, so this call will - * return the next trace after that one. - * If NULL, this call will return the - * first trace. */ -{ - register VarTrace *tracePtr; - Var *varPtr, *arrayPtr; + varPtr = TclObjLookupVar(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG, + "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); + if (varPtr == NULL) { + return TCL_ERROR; + } + varPtr->refCount++; + if (arrayPtr != NULL) { + arrayPtr->refCount++; + } + part1 = TclGetString(objv[1]); + varValuePtr = TclPtrGetVar(interp, varPtr, arrayPtr, part1, NULL, + (TCL_TRACE_READS | TCL_LEAVE_ERR_MSG)); + varPtr->refCount--; + if (arrayPtr != NULL) { + arrayPtr->refCount--; + } - varPtr = TclLookupVar(interp, part1, part2, - flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY), - /*msg*/ (char *) NULL, - /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); - if (varPtr == NULL) { - return NULL; - } + if (varValuePtr == NULL) { + /* + * We couldn't read the old value: either the var doesn't yet + * exist or it's an array element. If it's new, we will try to + * create it with Tcl_ObjSetVar2 below. + */ + + createVar = (TclIsVarUndefined(varPtr)); + varValuePtr = Tcl_NewObj(); + createdNewObj = 1; + } else if (Tcl_IsShared(varValuePtr)) { + varValuePtr = Tcl_DuplicateObj(varValuePtr); + createdNewObj = 1; + } - /* - * Find the relevant trace, if any, and return its clientData. - */ + /* + * Convert the variable's old value to a list object if necessary. + */ - tracePtr = varPtr->tracePtr; - if (prevClientData != NULL) { - for ( ; tracePtr != NULL; tracePtr = tracePtr->nextPtr) { - if ((tracePtr->clientData == prevClientData) - && (tracePtr->traceProc == proc)) { - tracePtr = tracePtr->nextPtr; - break; + if (varValuePtr->typePtr != &tclListType) { + int result = tclListType.setFromAnyProc(interp, varValuePtr); + if (result != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded obj. */ + } + return result; } } - } - for ( ; tracePtr != NULL; tracePtr = tracePtr->nextPtr) { - if (tracePtr->traceProc == proc) { - return tracePtr->clientData; + listRepPtr = (List *) varValuePtr->internalRep.twoPtrValue.ptr1; + elemPtrs = listRepPtr->elements; + numElems = listRepPtr->elemCount; + + /* + * If there is no room in the current array of element pointers, + * allocate a new, larger array and copy the pointers to it. + */ + + numRequired = numElems + (objc-2); + if (numRequired > listRepPtr->maxElemCount) { + int newMax = (2 * numRequired); + Tcl_Obj **newElemPtrs = (Tcl_Obj **) + ckalloc((unsigned) (newMax * sizeof(Tcl_Obj *))); + + memcpy((VOID *) newElemPtrs, (VOID *) elemPtrs, + (size_t) (numElems * sizeof(Tcl_Obj *))); + listRepPtr->maxElemCount = newMax; + listRepPtr->elements = newElemPtrs; + ckfree((char *) elemPtrs); + elemPtrs = newElemPtrs; + } + + /* + * Insert the new elements at the end of the list. + */ + + for (i = 2, j = numElems; i < objc; i++, j++) { + elemPtrs[j] = objv[i]; + Tcl_IncrRefCount(objv[i]); + } + listRepPtr->elemCount = numRequired; + + /* + * Invalidate and free any old string representation since it no + * longer reflects the list's internal representation. + */ + + Tcl_InvalidateStringRep(varValuePtr); + + /* + * Now store the list object back into the variable. If there is an + * error setting the new value, decrement its ref count if it + * was new and we didn't create the variable. + */ + + newValuePtr = TclPtrSetVar(interp, varPtr, arrayPtr, part1, NULL, + varValuePtr, TCL_LEAVE_ERR_MSG); + if (newValuePtr == NULL) { + if (createdNewObj && !createVar) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded obj */ + } + return TCL_ERROR; } } - return NULL; + + /* + * Set the interpreter's object result to refer to the variable's value + * object. + */ + + Tcl_SetObjResult(interp, newValuePtr); + return TCL_OK; } /* *---------------------------------------------------------------------- * - * Tcl_UnsetObjCmd -- + * Tcl_ArrayObjCmd -- * - * This object-based procedure is invoked to process the "unset" Tcl + * This object-based procedure is invoked to process the "array" Tcl * command. See the user documentation for details on what it does. * * Results: - * A standard Tcl object result value. + * A standard Tcl result object. * * Side effects: * See the user documentation. @@ -3492,446 +2807,122 @@ Tcl_VarTraceInfo2(interp, part1, part2, flags, proc, prevClientData) /* ARGSUSED */ int -Tcl_UnsetObjCmd(dummy, interp, objc, objv) +Tcl_ArrayObjCmd(dummy, interp, objc, objv) ClientData dummy; /* Not used. */ Tcl_Interp *interp; /* Current interpreter. */ int objc; /* Number of arguments. */ Tcl_Obj *CONST objv[]; /* Argument objects. */ { - register int i, flags = TCL_LEAVE_ERR_MSG; - register char *name; + /* + * The list of constants below should match the arrayOptions string array + * below. + */ - if (objc < 1) { - Tcl_WrongNumArgs(interp, 1, objv, - "?-nocomplain? ?--? ?varName varName ...?"); + enum {ARRAY_ANYMORE, ARRAY_DONESEARCH, ARRAY_EXISTS, ARRAY_GET, + ARRAY_NAMES, ARRAY_NEXTELEMENT, ARRAY_SET, ARRAY_SIZE, + ARRAY_STARTSEARCH, ARRAY_STATISTICS, ARRAY_UNSET}; + static CONST char *arrayOptions[] = { + "anymore", "donesearch", "exists", "get", "names", "nextelement", + "set", "size", "startsearch", "statistics", "unset", (char *) NULL + }; + + Interp *iPtr = (Interp *) interp; + Var *varPtr, *arrayPtr; + Tcl_HashEntry *hPtr; + Tcl_Obj *resultPtr, *varNamePtr; + int notArray; + char *varName; + int index, result; + + + if (objc < 3) { + Tcl_WrongNumArgs(interp, 1, objv, "option arrayName ?arg ...?"); return TCL_ERROR; - } else if (objc == 1) { - /* - * Do nothing if no arguments supplied, so as to match - * command documentation. - */ - return TCL_OK; } - /* - * Simple, restrictive argument parsing. The only options are -- - * and -nocomplain (which must come first and be given exactly to - * be an option). - */ - i = 1; - name = TclGetString(objv[i]); - if (name[0] == '-') { - if (strcmp("-nocomplain", name) == 0) { - i++; - if (i == objc) { - return TCL_OK; - } - flags = 0; - name = TclGetString(objv[i]); - } - if (strcmp("--", name) == 0) { - i++; - } + if (Tcl_GetIndexFromObj(interp, objv[1], arrayOptions, "option", + 0, &index) != TCL_OK) { + return TCL_ERROR; } - for (; i < objc; i++) { - if ((TclObjUnsetVar2(interp, objv[i], NULL, flags) != TCL_OK) - && (flags == TCL_LEAVE_ERR_MSG)) { + /* + * Locate the array variable + */ + + varNamePtr = objv[2]; + varName = TclGetString(varNamePtr); + varPtr = TclObjLookupVar(interp, varNamePtr, NULL, /*flags*/ 0, + /*msg*/ 0, /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); + + /* + * Special array trace used to keep the env array in sync for + * array names, array get, etc. + */ + + if (varPtr != NULL && varPtr->tracePtr != NULL + && (TclIsVarArray(varPtr) || TclIsVarUndefined(varPtr))) { + if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, varName, NULL, + (TCL_LEAVE_ERR_MSG|TCL_NAMESPACE_ONLY|TCL_GLOBAL_ONLY| + TCL_TRACE_ARRAY), /* leaveErrMsg */ 1)) { return TCL_ERROR; } } - return TCL_OK; -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_AppendObjCmd -- - * - * This object-based procedure is invoked to process the "append" - * Tcl command. See the user documentation for details on what it does. - * - * Results: - * A standard Tcl object result value. - * - * Side effects: - * A variable's value may be changed. - * - *---------------------------------------------------------------------- - */ - - /* ARGSUSED */ -int -Tcl_AppendObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ -{ - Var *varPtr, *arrayPtr; - char *part1; - register Tcl_Obj *varValuePtr = NULL; - /* Initialized to avoid compiler - * warning. */ - int i; + /* + * Verify that it is indeed an array variable. This test comes after + * the traces - the variable may actually become an array as an effect + * of said traces. + */ - if (objc < 2) { - Tcl_WrongNumArgs(interp, 1, objv, "varName ?value value ...?"); - return TCL_ERROR; + notArray = 0; + if ((varPtr == NULL) || !TclIsVarArray(varPtr) + || TclIsVarUndefined(varPtr)) { + notArray = 1; } - if (objc == 2) { - varValuePtr = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG); - if (varValuePtr == NULL) { - return TCL_ERROR; - } - } else { - varPtr = TclObjLookupVar(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG, - "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); - part1 = TclGetString(objv[1]); - if (varPtr == NULL) { - return TCL_ERROR; - } - for (i = 2; i < objc; i++) { - /* - * Note that we do not need to increase the refCount of - * the Var pointers: should a trace delete the variable, - * the return value of TclPtrSetVar will be NULL, and we - * will not access the variable again. - */ - - varValuePtr = TclPtrSetVar(interp, varPtr, arrayPtr, part1, NULL, - objv[i], (TCL_APPEND_VALUE | TCL_LEAVE_ERR_MSG)); - if (varValuePtr == NULL) { - return TCL_ERROR; - } - } - } - Tcl_SetObjResult(interp, varValuePtr); - return TCL_OK; -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_LappendObjCmd -- - * - * This object-based procedure is invoked to process the "lappend" - * Tcl command. See the user documentation for details on what it does. - * - * Results: - * A standard Tcl object result value. - * - * Side effects: - * A variable's value may be changed. - * - *---------------------------------------------------------------------- - */ + /* + * We have to wait to get the resultPtr until here because + * CallVarTraces can affect the result. + */ - /* ARGSUSED */ -int -Tcl_LappendObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ -{ - Tcl_Obj *varValuePtr, *newValuePtr; - register List *listRepPtr; - register Tcl_Obj **elemPtrs; - int numElems, numRequired, createdNewObj, createVar, i, j; - Var *varPtr, *arrayPtr; - char *part1; + resultPtr = Tcl_GetObjResult(interp); - if (objc < 2) { - Tcl_WrongNumArgs(interp, 1, objv, "varName ?value value ...?"); - return TCL_ERROR; - } - if (objc == 2) { - newValuePtr = Tcl_ObjGetVar2(interp, objv[1], (Tcl_Obj *) NULL, 0); - if (newValuePtr == NULL) { - /* - * The variable doesn't exist yet. Just create it with an empty - * initial value. - */ + switch (index) { + case ARRAY_ANYMORE: { + ArraySearch *searchPtr; - varValuePtr = Tcl_NewObj(); - newValuePtr = Tcl_ObjSetVar2(interp, objv[1], NULL, varValuePtr, - TCL_LEAVE_ERR_MSG); - if (newValuePtr == NULL) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded object */ + if (objc != 4) { + Tcl_WrongNumArgs(interp, 2, objv, + "arrayName searchId"); return TCL_ERROR; } - } - } else { - /* - * We have arguments to append. We used to call Tcl_SetVar2 to - * append each argument one at a time to ensure that traces were run - * for each append step. We now append the arguments all at once - * because it's faster. Note that a read trace and a write trace for - * the variable will now each only be called once. Also, if the - * variable's old value is unshared we modify it directly, otherwise - * we create a new copy to modify: this is "copy on write". - */ - - createdNewObj = 0; - createVar = 1; - - /* - * Use the TCL_TRACE_READS flag to ensure that if we have an - * array with no elements set yet, but with a read trace on it, - * we will create the variable and get read traces triggered. - * Note that you have to protect the variable pointers around - * the TclPtrGetVar call to insure that they remain valid - * even if the variable was undefined and unused. - */ - - varPtr = TclObjLookupVar(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG, - "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); - if (varPtr == NULL) { - return TCL_ERROR; - } - varPtr->refCount++; - if (arrayPtr != NULL) { - arrayPtr->refCount++; - } - part1 = TclGetString(objv[1]); - varValuePtr = TclPtrGetVar(interp, varPtr, arrayPtr, part1, NULL, - (TCL_TRACE_READS | TCL_LEAVE_ERR_MSG)); - varPtr->refCount--; - if (arrayPtr != NULL) { - arrayPtr->refCount--; - } + if (notArray) { + goto error; + } + searchPtr = ParseSearchId(interp, varPtr, varName, objv[3]); + if (searchPtr == NULL) { + return TCL_ERROR; + } + while (1) { + Var *varPtr2; - if (varValuePtr == NULL) { - /* - * We couldn't read the old value: either the var doesn't yet - * exist or it's an array element. If it's new, we will try to - * create it with Tcl_ObjSetVar2 below. - */ - - createVar = (TclIsVarUndefined(varPtr)); - varValuePtr = Tcl_NewObj(); - createdNewObj = 1; - } else if (Tcl_IsShared(varValuePtr)) { - varValuePtr = Tcl_DuplicateObj(varValuePtr); - createdNewObj = 1; + if (searchPtr->nextEntry != NULL) { + varPtr2 = (Var *) Tcl_GetHashValue(searchPtr->nextEntry); + if (!TclIsVarUndefined(varPtr2)) { + break; + } + } + searchPtr->nextEntry = Tcl_NextHashEntry(&searchPtr->search); + if (searchPtr->nextEntry == NULL) { + Tcl_SetIntObj(resultPtr, 0); + return TCL_OK; + } + } + Tcl_SetIntObj(resultPtr, 1); + break; } - - /* - * Convert the variable's old value to a list object if necessary. - */ - - if (varValuePtr->typePtr != &tclListType) { - int result = tclListType.setFromAnyProc(interp, varValuePtr); - if (result != TCL_OK) { - if (createdNewObj) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded obj. */ - } - return result; - } - } - listRepPtr = (List *) varValuePtr->internalRep.twoPtrValue.ptr1; - elemPtrs = listRepPtr->elements; - numElems = listRepPtr->elemCount; - - /* - * If there is no room in the current array of element pointers, - * allocate a new, larger array and copy the pointers to it. - */ - - numRequired = numElems + (objc-2); - if (numRequired > listRepPtr->maxElemCount) { - int newMax = (2 * numRequired); - Tcl_Obj **newElemPtrs = (Tcl_Obj **) - ckalloc((unsigned) (newMax * sizeof(Tcl_Obj *))); - - memcpy((VOID *) newElemPtrs, (VOID *) elemPtrs, - (size_t) (numElems * sizeof(Tcl_Obj *))); - listRepPtr->maxElemCount = newMax; - listRepPtr->elements = newElemPtrs; - ckfree((char *) elemPtrs); - elemPtrs = newElemPtrs; - } - - /* - * Insert the new elements at the end of the list. - */ - - for (i = 2, j = numElems; i < objc; i++, j++) { - elemPtrs[j] = objv[i]; - Tcl_IncrRefCount(objv[i]); - } - listRepPtr->elemCount = numRequired; - - /* - * Invalidate and free any old string representation since it no - * longer reflects the list's internal representation. - */ - - Tcl_InvalidateStringRep(varValuePtr); - - /* - * Now store the list object back into the variable. If there is an - * error setting the new value, decrement its ref count if it - * was new and we didn't create the variable. - */ - - newValuePtr = TclPtrSetVar(interp, varPtr, arrayPtr, part1, NULL, - varValuePtr, TCL_LEAVE_ERR_MSG); - if (newValuePtr == NULL) { - if (createdNewObj && !createVar) { - Tcl_DecrRefCount(varValuePtr); /* free unneeded obj */ - } - return TCL_ERROR; - } - } - - /* - * Set the interpreter's object result to refer to the variable's value - * object. - */ - - Tcl_SetObjResult(interp, newValuePtr); - return TCL_OK; -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_ArrayObjCmd -- - * - * This object-based procedure is invoked to process the "array" Tcl - * command. See the user documentation for details on what it does. - * - * Results: - * A standard Tcl result object. - * - * Side effects: - * See the user documentation. - * - *---------------------------------------------------------------------- - */ - - /* ARGSUSED */ -int -Tcl_ArrayObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ -{ - /* - * The list of constants below should match the arrayOptions string array - * below. - */ - - enum {ARRAY_ANYMORE, ARRAY_DONESEARCH, ARRAY_EXISTS, ARRAY_GET, - ARRAY_NAMES, ARRAY_NEXTELEMENT, ARRAY_SET, ARRAY_SIZE, - ARRAY_STARTSEARCH, ARRAY_STATISTICS, ARRAY_UNSET}; - static CONST char *arrayOptions[] = { - "anymore", "donesearch", "exists", "get", "names", "nextelement", - "set", "size", "startsearch", "statistics", "unset", (char *) NULL - }; - - Interp *iPtr = (Interp *) interp; - Var *varPtr, *arrayPtr; - Tcl_HashEntry *hPtr; - Tcl_Obj *resultPtr, *varNamePtr; - int notArray; - char *varName; - int index, result; - - - if (objc < 3) { - Tcl_WrongNumArgs(interp, 1, objv, "option arrayName ?arg ...?"); - return TCL_ERROR; - } - - if (Tcl_GetIndexFromObj(interp, objv[1], arrayOptions, "option", - 0, &index) != TCL_OK) { - return TCL_ERROR; - } - - /* - * Locate the array variable - */ - - varNamePtr = objv[2]; - varName = TclGetString(varNamePtr); - varPtr = TclObjLookupVar(interp, varNamePtr, NULL, /*flags*/ 0, - /*msg*/ 0, /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr); - - /* - * Special array trace used to keep the env array in sync for - * array names, array get, etc. - */ - - if (varPtr != NULL && varPtr->tracePtr != NULL - && (TclIsVarArray(varPtr) || TclIsVarUndefined(varPtr))) { - if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, varName, NULL, - (TCL_LEAVE_ERR_MSG|TCL_NAMESPACE_ONLY|TCL_GLOBAL_ONLY| - TCL_TRACE_ARRAY), /* leaveErrMsg */ 1)) { - return TCL_ERROR; - } - } - - /* - * Verify that it is indeed an array variable. This test comes after - * the traces - the variable may actually become an array as an effect - * of said traces. - */ - - notArray = 0; - if ((varPtr == NULL) || !TclIsVarArray(varPtr) - || TclIsVarUndefined(varPtr)) { - notArray = 1; - } - - /* - * We have to wait to get the resultPtr until here because - * CallVarTraces can affect the result. - */ - - resultPtr = Tcl_GetObjResult(interp); - - switch (index) { - case ARRAY_ANYMORE: { - ArraySearch *searchPtr; - - if (objc != 4) { - Tcl_WrongNumArgs(interp, 2, objv, - "arrayName searchId"); - return TCL_ERROR; - } - if (notArray) { - goto error; - } - searchPtr = ParseSearchId(interp, varPtr, varName, objv[3]); - if (searchPtr == NULL) { - return TCL_ERROR; - } - while (1) { - Var *varPtr2; - - if (searchPtr->nextEntry != NULL) { - varPtr2 = (Var *) Tcl_GetHashValue(searchPtr->nextEntry); - if (!TclIsVarUndefined(varPtr2)) { - break; - } - } - searchPtr->nextEntry = Tcl_NextHashEntry(&searchPtr->search); - if (searchPtr->nextEntry == NULL) { - Tcl_SetIntObj(resultPtr, 0); - return TCL_OK; - } - } - Tcl_SetIntObj(resultPtr, 1); - break; - } - case ARRAY_DONESEARCH: { - ArraySearch *searchPtr, *prevPtr; + case ARRAY_DONESEARCH: { + ArraySearch *searchPtr, *prevPtr; if (objc != 4) { Tcl_WrongNumArgs(interp, 2, objv, @@ -4242,1888 +3233,2889 @@ Tcl_ArrayObjCmd(dummy, interp, objc, objv) break; } - case ARRAY_STATISTICS: { - CONST char *stats; + case ARRAY_STATISTICS: { + CONST char *stats; + + if (notArray) { + goto error; + } + + stats = Tcl_HashStats(varPtr->value.tablePtr); + if (stats != NULL) { + Tcl_SetStringObj(Tcl_GetObjResult(interp), stats, -1); + ckfree((void *)stats); + } else { + Tcl_SetResult(interp, "error reading array statistics", + TCL_STATIC); + return TCL_ERROR; + } + break; + } + + case ARRAY_UNSET: { + Tcl_HashSearch search; + Var *varPtr2; + char *pattern = NULL; + char *name; + + if ((objc != 3) && (objc != 4)) { + Tcl_WrongNumArgs(interp, 2, objv, "arrayName ?pattern?"); + return TCL_ERROR; + } + if (notArray) { + return TCL_OK; + } + if (objc == 3) { + /* + * When no pattern is given, just unset the whole array + */ + if (TclObjUnsetVar2(interp, varNamePtr, NULL, 0) + != TCL_OK) { + return TCL_ERROR; + } + } else { + pattern = Tcl_GetString(objv[3]); + for (hPtr = Tcl_FirstHashEntry(varPtr->value.tablePtr, + &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + varPtr2 = (Var *) Tcl_GetHashValue(hPtr); + if (TclIsVarUndefined(varPtr2)) { + continue; + } + name = Tcl_GetHashKey(varPtr->value.tablePtr, hPtr); + if (Tcl_StringMatch(name, pattern) && + (TclObjUnsetVar2(interp, varNamePtr, name, 0) + != TCL_OK)) { + return TCL_ERROR; + } + } + } + break; + } + } + return TCL_OK; + + error: + Tcl_AppendStringsToObj(resultPtr, "\"", varName, "\" isn't an array", + (char *) NULL); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * TclArraySet -- + * + * Set the elements of an array. If there are no elements to + * set, create an empty array. This routine is used by the + * Tcl_ArrayObjCmd and by the TclSetupEnv routine. + * + * Results: + * A standard Tcl result object. + * + * Side effects: + * A variable will be created if one does not already exist. + * + *---------------------------------------------------------------------- + */ + +int +TclArraySet(interp, arrayNameObj, arrayElemObj) + Tcl_Interp *interp; /* Current interpreter. */ + Tcl_Obj *arrayNameObj; /* The array name. */ + Tcl_Obj *arrayElemObj; /* The array elements list. If this is + * NULL, create an empty array. */ +{ + Var *varPtr, *arrayPtr; + Tcl_Obj **elemPtrs; + int result, elemLen, i, nameLen; + char *varName, *p; + + varName = Tcl_GetStringFromObj(arrayNameObj, &nameLen); + p = varName + nameLen - 1; + if (*p == ')') { + while (--p >= varName) { + if (*p == '(') { + VarErrMsg(interp, varName, NULL, "set", needArray); + return TCL_ERROR; + } + } + } + + varPtr = TclObjLookupVar(interp, arrayNameObj, NULL, + /*flags*/ TCL_LEAVE_ERR_MSG, /*msg*/ "set", /*createPart1*/ 1, + /*createPart2*/ 0, &arrayPtr); + if (varPtr == NULL) { + return TCL_ERROR; + } + + if (arrayElemObj != NULL) { + result = Tcl_ListObjGetElements(interp, arrayElemObj, + &elemLen, &elemPtrs); + if (result != TCL_OK) { + return result; + } + if (elemLen & 1) { + Tcl_ResetResult(interp); + Tcl_AppendToObj(Tcl_GetObjResult(interp), + "list must have an even number of elements", -1); + return TCL_ERROR; + } + if (elemLen > 0) { + /* + * We needn't worry about traces invalidating arrayPtr: + * should that be the case, TclPtrSetVar will return NULL + * so that we break out of the loop and return an error. + */ + + for (i = 0; i < elemLen; i += 2) { + char *part2 = TclGetString(elemPtrs[i]); + Var *elemVarPtr = TclLookupArrayElement(interp, varName, + part2, TCL_LEAVE_ERR_MSG, "set", 1, 1, varPtr); + if ((elemVarPtr == NULL) || + (TclPtrSetVar(interp, elemVarPtr, varPtr, varName, + part2, elemPtrs[i+1], TCL_LEAVE_ERR_MSG) == NULL)) { + result = TCL_ERROR; + break; + } + } + return result; + } + } + + /* + * The list is empty make sure we have an array, or create + * one if necessary. + */ + + if (varPtr != NULL) { + if (!TclIsVarUndefined(varPtr) && TclIsVarArray(varPtr)) { + /* + * Already an array, done. + */ + + return TCL_OK; + } + if (TclIsVarArrayElement(varPtr) || !TclIsVarUndefined(varPtr)) { + /* + * Either an array element, or a scalar: lose! + */ + + VarErrMsg(interp, varName, (char *)NULL, "array set", needArray); + return TCL_ERROR; + } + } + TclSetVarArray(varPtr); + TclClearVarUndefined(varPtr); + varPtr->value.tablePtr = + (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable)); + Tcl_InitHashTable(varPtr->value.tablePtr, TCL_STRING_KEYS); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * ObjMakeUpvar -- + * + * This procedure does all of the work of the "global" and "upvar" + * commands. + * + * Results: + * A standard Tcl completion code. If an error occurs then an + * error message is left in iPtr->result. + * + * Side effects: + * The variable given by myName is linked to the variable in framePtr + * given by otherP1 and otherP2, so that references to myName are + * redirected to the other variable like a symbolic link. + * + *---------------------------------------------------------------------- + */ + +static int +ObjMakeUpvar(interp, framePtr, otherP1Ptr, otherP2, otherFlags, myName, myFlags, index) + Tcl_Interp *interp; /* Interpreter containing variables. Used + * for error messages, too. */ + CallFrame *framePtr; /* Call frame containing "other" variable. + * NULL means use global :: context. */ + Tcl_Obj *otherP1Ptr; + CONST char *otherP2; /* Two-part name of variable in framePtr. */ + CONST int otherFlags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: + * indicates scope of "other" variable. */ + CONST char *myName; /* Name of variable which will refer to + * otherP1/otherP2. Must be a scalar. */ + CONST int myFlags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: + * indicates scope of myName. */ + int index; /* If the variable to be linked is an indexed + * scalar, this is its index. Otherwise, -1. */ +{ + Interp *iPtr = (Interp *) interp; + Var *otherPtr, *varPtr, *arrayPtr; + CallFrame *varFramePtr; + CONST char *errMsg; + + /* + * Find "other" in "framePtr". If not looking up other in just the + * current namespace, temporarily replace the current var frame + * pointer in the interpreter in order to use TclObjLookupVar. + */ + + varFramePtr = iPtr->varFramePtr; + if (!(otherFlags & TCL_NAMESPACE_ONLY)) { + iPtr->varFramePtr = framePtr; + } + otherPtr = TclObjLookupVar(interp, otherP1Ptr, otherP2, + (otherFlags | TCL_LEAVE_ERR_MSG), "access", + /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); + if (!(otherFlags & TCL_NAMESPACE_ONLY)) { + iPtr->varFramePtr = varFramePtr; + } + if (otherPtr == NULL) { + return TCL_ERROR; + } + + if (index >= 0) { + if (!varFramePtr->isProcCallFrame) { + panic("ObjMakeUpVar called with an index outside from a proc.\n"); + } + varPtr = &(varFramePtr->compiledLocals[index]); + } else { + /* + * Check that we are not trying to create a namespace var linked to + * a local variable in a procedure. If we allowed this, the local + * variable in the shorter-lived procedure frame could go away + * leaving the namespace var's reference invalid. + */ + + if (((otherP2 ? arrayPtr->nsPtr : otherPtr->nsPtr) == NULL) + && ((myFlags & (TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY)) + || (varFramePtr == NULL) + || !varFramePtr->isProcCallFrame + || (strstr(myName, "::") != NULL))) { + Tcl_AppendResult((Tcl_Interp *) iPtr, "bad variable name \"", + myName, "\": upvar won't create namespace variable that ", + "refers to procedure variable", (char *) NULL); + return TCL_ERROR; + } + + /* + * Lookup and eventually create the new variable. + */ + + varPtr = TclLookupSimpleVar(interp, myName, myFlags, /*create*/ 1, + &errMsg, &index); + if (varPtr == NULL) { + VarErrMsg(interp, myName, NULL, "create", errMsg); + return TCL_ERROR; + } + } + + if (varPtr == otherPtr) { + Tcl_SetResult((Tcl_Interp *) iPtr, + "can't upvar from variable to itself", TCL_STATIC); + return TCL_ERROR; + } - if (notArray) { - goto error; - } + if (varPtr->tracePtr != NULL) { + Tcl_AppendResult((Tcl_Interp *) iPtr, "variable \"", myName, + "\" has traces: can't use for upvar", (char *) NULL); + return TCL_ERROR; + } else if (!TclIsVarUndefined(varPtr)) { + /* + * The variable already existed. Make sure this variable "varPtr" + * isn't the same as "otherPtr" (avoid circular links). Also, if + * it's not an upvar then it's an error. If it is an upvar, then + * just disconnect it from the thing it currently refers to. + */ - stats = Tcl_HashStats(varPtr->value.tablePtr); - if (stats != NULL) { - Tcl_SetStringObj(Tcl_GetObjResult(interp), stats, -1); - ckfree((void *)stats); - } else { - Tcl_SetResult(interp, "error reading array statistics", - TCL_STATIC); - return TCL_ERROR; - } - break; - } - - case ARRAY_UNSET: { - Tcl_HashSearch search; - Var *varPtr2; - char *pattern = NULL; - char *name; - - if ((objc != 3) && (objc != 4)) { - Tcl_WrongNumArgs(interp, 2, objv, "arrayName ?pattern?"); - return TCL_ERROR; - } - if (notArray) { + if (TclIsVarLink(varPtr)) { + Var *linkPtr = varPtr->value.linkPtr; + if (linkPtr == otherPtr) { return TCL_OK; } - if (objc == 3) { - /* - * When no pattern is given, just unset the whole array - */ - if (TclObjUnsetVar2(interp, varNamePtr, NULL, 0) - != TCL_OK) { - return TCL_ERROR; - } - } else { - pattern = Tcl_GetString(objv[3]); - for (hPtr = Tcl_FirstHashEntry(varPtr->value.tablePtr, - &search); - hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { - varPtr2 = (Var *) Tcl_GetHashValue(hPtr); - if (TclIsVarUndefined(varPtr2)) { - continue; - } - name = Tcl_GetHashKey(varPtr->value.tablePtr, hPtr); - if (Tcl_StringMatch(name, pattern) && - (TclObjUnsetVar2(interp, varNamePtr, name, 0) - != TCL_OK)) { - return TCL_ERROR; - } - } + linkPtr->refCount--; + if (TclIsVarUndefined(linkPtr)) { + CleanupVar(linkPtr, (Var *) NULL); } - break; + } else { + Tcl_AppendResult((Tcl_Interp *) iPtr, "variable \"", myName, + "\" already exists", (char *) NULL); + return TCL_ERROR; } } + TclSetVarLink(varPtr); + TclClearVarUndefined(varPtr); + varPtr->value.linkPtr = otherPtr; + otherPtr->refCount++; return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_UpVar -- + * + * This procedure links one variable to another, just like + * the "upvar" command. + * + * Results: + * A standard Tcl completion code. If an error occurs then + * an error message is left in the interp's result. + * + * Side effects: + * The variable in frameName whose name is given by varName becomes + * accessible under the name localName, so that references to + * localName are redirected to the other variable like a symbolic + * link. + * + *---------------------------------------------------------------------- + */ - error: - Tcl_AppendStringsToObj(resultPtr, "\"", varName, "\" isn't an array", - (char *) NULL); - return TCL_ERROR; +int +Tcl_UpVar(interp, frameName, varName, localName, flags) + Tcl_Interp *interp; /* Command interpreter in which varName is + * to be looked up. */ + CONST char *frameName; /* Name of the frame containing the source + * variable, such as "1" or "#0". */ + char *varName; /* Name of a variable in interp to link to. + * May be either a scalar name or an + * element in an array. */ + CONST char *localName; /* Name of link variable. */ + int flags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: + * indicates scope of localName. */ +{ + return Tcl_UpVar2(interp, frameName, varName, NULL, localName, flags); } /* *---------------------------------------------------------------------- * - * TclArraySet -- + * Tcl_UpVar2 -- * - * Set the elements of an array. If there are no elements to - * set, create an empty array. This routine is used by the - * Tcl_ArrayObjCmd and by the TclSetupEnv routine. + * This procedure links one variable to another, just like + * the "upvar" command. * * Results: - * A standard Tcl result object. + * A standard Tcl completion code. If an error occurs then + * an error message is left in the interp's result. * * Side effects: - * A variable will be created if one does not already exist. + * The variable in frameName whose name is given by part1 and + * part2 becomes accessible under the name localName, so that + * references to localName are redirected to the other variable + * like a symbolic link. + * + *---------------------------------------------------------------------- + */ + +int +Tcl_UpVar2(interp, frameName, part1, part2, localName, flags) + Tcl_Interp *interp; /* Interpreter containing variables. Used + * for error messages too. */ + CONST char *frameName; /* Name of the frame containing the source + * variable, such as "1" or "#0". */ + char *part1; + CONST char *part2; /* Two parts of source variable name to + * link to. */ + CONST char *localName; /* Name of link variable. */ + int flags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: + * indicates scope of localName. */ +{ + int result; + CallFrame *framePtr; + Tcl_Obj *part1Ptr; + + part1Ptr = Tcl_NewStringObj(part1, -1); + Tcl_IncrRefCount(part1Ptr); + + result = TclGetFrame(interp, frameName, &framePtr); + if (result == -1) { + return TCL_ERROR; + } + result = ObjMakeUpvar(interp, framePtr, part1Ptr, part2, 0, + localName, flags, -1); + + TclDecrRefCount(part1Ptr); + return result; +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_GetVariableFullName -- + * + * Given a Tcl_Var token returned by Tcl_FindNamespaceVar, this + * procedure appends to an object the namespace variable's full + * name, qualified by a sequence of parent namespace names. + * + * Results: + * None. + * + * Side effects: + * The variable's fully-qualified name is appended to the string + * representation of objPtr. + * + *---------------------------------------------------------------------- + */ + +void +Tcl_GetVariableFullName(interp, variable, objPtr) + Tcl_Interp *interp; /* Interpreter containing the variable. */ + Tcl_Var variable; /* Token for the variable returned by a + * previous call to Tcl_FindNamespaceVar. */ + Tcl_Obj *objPtr; /* Points to the object onto which the + * variable's full name is appended. */ +{ + Interp *iPtr = (Interp *) interp; + register Var *varPtr = (Var *) variable; + char *name; + + /* + * Add the full name of the containing namespace (if any), followed by + * the "::" separator, then the variable name. + */ + + if (varPtr != NULL) { + if (!TclIsVarArrayElement(varPtr)) { + if (varPtr->nsPtr != NULL) { + Tcl_AppendToObj(objPtr, varPtr->nsPtr->fullName, -1); + if (varPtr->nsPtr != iPtr->globalNsPtr) { + Tcl_AppendToObj(objPtr, "::", 2); + } + } + if (varPtr->name != NULL) { + Tcl_AppendToObj(objPtr, varPtr->name, -1); + } else if (varPtr->hPtr != NULL) { + name = Tcl_GetHashKey(varPtr->hPtr->tablePtr, varPtr->hPtr); + Tcl_AppendToObj(objPtr, name, -1); + } + } + } +} + +/* + *---------------------------------------------------------------------- + * + * Tcl_GlobalObjCmd -- + * + * This object-based procedure is invoked to process the "global" Tcl + * command. See the user documentation for details on what it does. + * + * Results: + * A standard Tcl object result value. + * + * Side effects: + * See the user documentation. * *---------------------------------------------------------------------- */ int -TclArraySet(interp, arrayNameObj, arrayElemObj) +Tcl_GlobalObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ Tcl_Interp *interp; /* Current interpreter. */ - Tcl_Obj *arrayNameObj; /* The array name. */ - Tcl_Obj *arrayElemObj; /* The array elements list. If this is - * NULL, create an empty array. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { - Var *varPtr, *arrayPtr; - Tcl_Obj **elemPtrs; - int result, elemLen, i, nameLen; - char *varName, *p; - - varName = Tcl_GetStringFromObj(arrayNameObj, &nameLen); - p = varName + nameLen - 1; - if (*p == ')') { - while (--p >= varName) { - if (*p == '(') { - VarErrMsg(interp, varName, NULL, "set", needArray); - return TCL_ERROR; - } - } - } + Interp *iPtr = (Interp *) interp; + register Tcl_Obj *objPtr; + char *varName; + register char *tail; + int result, i; - varPtr = TclObjLookupVar(interp, arrayNameObj, NULL, - /*flags*/ TCL_LEAVE_ERR_MSG, /*msg*/ "set", /*createPart1*/ 1, - /*createPart2*/ 0, &arrayPtr); - if (varPtr == NULL) { + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "varName ?varName ...?"); return TCL_ERROR; } - if (arrayElemObj != NULL) { - result = Tcl_ListObjGetElements(interp, arrayElemObj, - &elemLen, &elemPtrs); - if (result != TCL_OK) { - return result; - } - if (elemLen & 1) { - Tcl_ResetResult(interp); - Tcl_AppendToObj(Tcl_GetObjResult(interp), - "list must have an even number of elements", -1); - return TCL_ERROR; - } - if (elemLen > 0) { - /* - * We needn't worry about traces invalidating arrayPtr: - * should that be the case, TclPtrSetVar will return NULL - * so that we break out of the loop and return an error. - */ - - for (i = 0; i < elemLen; i += 2) { - char *part2 = TclGetString(elemPtrs[i]); - Var *elemVarPtr = TclLookupArrayElement(interp, varName, - part2, TCL_LEAVE_ERR_MSG, "set", 1, 1, varPtr); - if ((elemVarPtr == NULL) || - (TclPtrSetVar(interp, elemVarPtr, varPtr, varName, - part2, elemPtrs[i+1], TCL_LEAVE_ERR_MSG) == NULL)) { - result = TCL_ERROR; - break; - } - } - return result; - } - } - /* - * The list is empty make sure we have an array, or create - * one if necessary. + * If we are not executing inside a Tcl procedure, just return. */ - if (varPtr != NULL) { - if (!TclIsVarUndefined(varPtr) && TclIsVarArray(varPtr)) { - /* - * Already an array, done. - */ - - return TCL_OK; + if ((iPtr->varFramePtr == NULL) + || !iPtr->varFramePtr->isProcCallFrame) { + return TCL_OK; + } + + for (i = 1; i < objc; i++) { + /* + * Make a local variable linked to its counterpart in the global :: + * namespace. + */ + + objPtr = objv[i]; + varName = TclGetString(objPtr); + + /* + * The variable name might have a scope qualifier, but the name for + * the local "link" variable must be the simple name at the tail. + */ + + for (tail = varName; *tail != '\0'; tail++) { + /* empty body */ } - if (TclIsVarArrayElement(varPtr) || !TclIsVarUndefined(varPtr)) { - /* - * Either an array element, or a scalar: lose! - */ - - VarErrMsg(interp, varName, (char *)NULL, "array set", needArray); - return TCL_ERROR; + while ((tail > varName) && ((*tail != ':') || (*(tail-1) != ':'))) { + tail--; + } + if ((*tail == ':') && (tail > varName)) { + tail++; + } + + /* + * Link to the variable "varName" in the global :: namespace. + */ + + result = ObjMakeUpvar(interp, (CallFrame *) NULL, + objPtr, NULL, /*otherFlags*/ TCL_GLOBAL_ONLY, + /*myName*/ tail, /*myFlags*/ 0, -1); + if (result != TCL_OK) { + return result; } } - TclSetVarArray(varPtr); - TclClearVarUndefined(varPtr); - varPtr->value.tablePtr = - (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable)); - Tcl_InitHashTable(varPtr->value.tablePtr, TCL_STRING_KEYS); return TCL_OK; } /* *---------------------------------------------------------------------- * - * ObjMakeUpvar -- + * Tcl_VariableObjCmd -- * - * This procedure does all of the work of the "global" and "upvar" - * commands. + * Invoked to implement the "variable" command that creates one or more + * global variables. Handles the following syntax: + * + * variable ?name value...? name ?value? + * + * One or more variables can be created. The variables are initialized + * with the specified values. The value for the last variable is + * optional. + * + * If the variable does not exist, it is created and given the optional + * value. If it already exists, it is simply set to the optional + * value. Normally, "name" is an unqualified name, so it is created in + * the current namespace. If it includes namespace qualifiers, it can + * be created in another namespace. + * + * If the variable command is executed inside a Tcl procedure, it + * creates a local variable linked to the newly-created namespace + * variable. * * Results: - * A standard Tcl completion code. If an error occurs then an - * error message is left in iPtr->result. + * Returns TCL_OK if the variable is found or created. Returns + * TCL_ERROR if anything goes wrong. * * Side effects: - * The variable given by myName is linked to the variable in framePtr - * given by otherP1 and otherP2, so that references to myName are - * redirected to the other variable like a symbolic link. + * If anything goes wrong, this procedure returns an error message + * as the result in the interpreter's result object. * *---------------------------------------------------------------------- */ -static int -ObjMakeUpvar(interp, framePtr, otherP1Ptr, otherP2, otherFlags, myName, myFlags, index) - Tcl_Interp *interp; /* Interpreter containing variables. Used - * for error messages, too. */ - CallFrame *framePtr; /* Call frame containing "other" variable. - * NULL means use global :: context. */ - Tcl_Obj *otherP1Ptr; - CONST char *otherP2; /* Two-part name of variable in framePtr. */ - CONST int otherFlags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: - * indicates scope of "other" variable. */ - CONST char *myName; /* Name of variable which will refer to - * otherP1/otherP2. Must be a scalar. */ - CONST int myFlags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: - * indicates scope of myName. */ - int index; /* If the variable to be linked is an indexed - * scalar, this is its index. Otherwise, -1. */ +int +Tcl_VariableObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { Interp *iPtr = (Interp *) interp; - Var *otherPtr, *varPtr, *arrayPtr; - CallFrame *varFramePtr; - CONST char *errMsg; - - /* - * Find "other" in "framePtr". If not looking up other in just the - * current namespace, temporarily replace the current var frame - * pointer in the interpreter in order to use TclObjLookupVar. - */ + char *varName, *tail, *cp; + Var *varPtr, *arrayPtr; + Tcl_Obj *varValuePtr; + int i, result; + Tcl_Obj *varNamePtr; - varFramePtr = iPtr->varFramePtr; - if (!(otherFlags & TCL_NAMESPACE_ONLY)) { - iPtr->varFramePtr = framePtr; - } - otherPtr = TclObjLookupVar(interp, otherP1Ptr, otherP2, - (otherFlags | TCL_LEAVE_ERR_MSG), "access", - /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr); - if (!(otherFlags & TCL_NAMESPACE_ONLY)) { - iPtr->varFramePtr = varFramePtr; - } - if (otherPtr == NULL) { + if (objc < 2) { + Tcl_WrongNumArgs(interp, 1, objv, "?name value...? name ?value?"); return TCL_ERROR; } - if (index >= 0) { - if (!varFramePtr->isProcCallFrame) { - panic("ObjMakeUpVar called with an index outside from a proc.\n"); - } - varPtr = &(varFramePtr->compiledLocals[index]); - } else { + for (i = 1; i < objc; i = i+2) { /* - * Check that we are not trying to create a namespace var linked to - * a local variable in a procedure. If we allowed this, the local - * variable in the shorter-lived procedure frame could go away - * leaving the namespace var's reference invalid. + * Look up each variable in the current namespace context, creating + * it if necessary. */ - if (((otherP2 ? arrayPtr->nsPtr : otherPtr->nsPtr) == NULL) - && ((myFlags & (TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY)) - || (varFramePtr == NULL) - || !varFramePtr->isProcCallFrame - || (strstr(myName, "::") != NULL))) { - Tcl_AppendResult((Tcl_Interp *) iPtr, "bad variable name \"", - myName, "\": upvar won't create namespace variable that ", - "refers to procedure variable", (char *) NULL); + varNamePtr = objv[i]; + varName = TclGetString(varNamePtr); + varPtr = TclObjLookupVar(interp, varNamePtr, NULL, + (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG), "define", + /*createPart1*/ 1, /*createPart2*/ 0, &arrayPtr); + + if (arrayPtr != NULL) { + /* + * Variable cannot be an element in an array. If arrayPtr is + * non-null, it is, so throw up an error and return. + */ + VarErrMsg(interp, varName, NULL, "define", isArrayElement); + return TCL_ERROR; + } + + if (varPtr == NULL) { return TCL_ERROR; } - + + /* + * Mark the variable as a namespace variable and increment its + * reference count so that it will persist until its namespace is + * destroyed or until the variable is unset. + */ + + if (!(varPtr->flags & VAR_NAMESPACE_VAR)) { + varPtr->flags |= VAR_NAMESPACE_VAR; + varPtr->refCount++; + } + /* - * Lookup and eventually create the new variable. + * If a value was specified, set the variable to that value. + * Otherwise, if the variable is new, leave it undefined. + * (If the variable already exists and no value was specified, + * leave its value unchanged; just create the local link if + * we're in a Tcl procedure). */ - - varPtr = TclLookupSimpleVar(interp, myName, myFlags, /*create*/ 1, - &errMsg, &index); - if (varPtr == NULL) { - VarErrMsg(interp, myName, NULL, "create", errMsg); - return TCL_ERROR; - } - } - if (varPtr == otherPtr) { - Tcl_SetResult((Tcl_Interp *) iPtr, - "can't upvar from variable to itself", TCL_STATIC); - return TCL_ERROR; - } + if (i+1 < objc) { /* a value was specified */ + varValuePtr = TclPtrSetVar(interp, varPtr, arrayPtr, varName, NULL, + objv[i+1], (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG)); + if (varValuePtr == NULL) { + return TCL_ERROR; + } + } - if (varPtr->tracePtr != NULL) { - Tcl_AppendResult((Tcl_Interp *) iPtr, "variable \"", myName, - "\" has traces: can't use for upvar", (char *) NULL); - return TCL_ERROR; - } else if (!TclIsVarUndefined(varPtr)) { /* - * The variable already existed. Make sure this variable "varPtr" - * isn't the same as "otherPtr" (avoid circular links). Also, if - * it's not an upvar then it's an error. If it is an upvar, then - * just disconnect it from the thing it currently refers to. + * If we are executing inside a Tcl procedure, create a local + * variable linked to the new namespace variable "varName". */ - if (TclIsVarLink(varPtr)) { - Var *linkPtr = varPtr->value.linkPtr; - if (linkPtr == otherPtr) { - return TCL_OK; + if ((iPtr->varFramePtr != NULL) + && iPtr->varFramePtr->isProcCallFrame) { + /* + * varName might have a scope qualifier, but the name for the + * local "link" variable must be the simple name at the tail. + * + * Locate tail in one pass: drop any prefix after two *or more* + * consecutive ":" characters). + */ + + for (tail = cp = varName; *cp != '\0'; ) { + if (*cp++ == ':') { + while (*cp == ':') { + tail = ++cp; + } + } } - linkPtr->refCount--; - if (TclIsVarUndefined(linkPtr)) { - CleanupVar(linkPtr, (Var *) NULL); + + /* + * Create a local link "tail" to the variable "varName" in the + * current namespace. + */ + + result = ObjMakeUpvar(interp, (CallFrame *) NULL, + /*otherP1*/ varNamePtr, /*otherP2*/ NULL, + /*otherFlags*/ TCL_NAMESPACE_ONLY, + /*myName*/ tail, /*myFlags*/ 0, -1); + if (result != TCL_OK) { + return result; } - } else { - Tcl_AppendResult((Tcl_Interp *) iPtr, "variable \"", myName, - "\" already exists", (char *) NULL); - return TCL_ERROR; } } - TclSetVarLink(varPtr); - TclClearVarUndefined(varPtr); - varPtr->value.linkPtr = otherPtr; - otherPtr->refCount++; return TCL_OK; } /* *---------------------------------------------------------------------- * - * Tcl_UpVar -- - * - * This procedure links one variable to another, just like - * the "upvar" command. - * - * Results: - * A standard Tcl completion code. If an error occurs then - * an error message is left in the interp's result. - * - * Side effects: - * The variable in frameName whose name is given by varName becomes - * accessible under the name localName, so that references to - * localName are redirected to the other variable like a symbolic - * link. - * - *---------------------------------------------------------------------- - */ - -int -Tcl_UpVar(interp, frameName, varName, localName, flags) - Tcl_Interp *interp; /* Command interpreter in which varName is - * to be looked up. */ - CONST char *frameName; /* Name of the frame containing the source - * variable, such as "1" or "#0". */ - char *varName; /* Name of a variable in interp to link to. - * May be either a scalar name or an - * element in an array. */ - CONST char *localName; /* Name of link variable. */ - int flags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: - * indicates scope of localName. */ -{ - return Tcl_UpVar2(interp, frameName, varName, NULL, localName, flags); -} - -/* - *---------------------------------------------------------------------- - * - * Tcl_UpVar2 -- + * Tcl_UpvarObjCmd -- * - * This procedure links one variable to another, just like - * the "upvar" command. + * This object-based procedure is invoked to process the "upvar" + * Tcl command. See the user documentation for details on what it does. * * Results: - * A standard Tcl completion code. If an error occurs then - * an error message is left in the interp's result. + * A standard Tcl object result value. * * Side effects: - * The variable in frameName whose name is given by part1 and - * part2 becomes accessible under the name localName, so that - * references to localName are redirected to the other variable - * like a symbolic link. + * See the user documentation. * *---------------------------------------------------------------------- */ + /* ARGSUSED */ int -Tcl_UpVar2(interp, frameName, part1, part2, localName, flags) - Tcl_Interp *interp; /* Interpreter containing variables. Used - * for error messages too. */ - CONST char *frameName; /* Name of the frame containing the source - * variable, such as "1" or "#0". */ - char *part1; - CONST char *part2; /* Two parts of source variable name to - * link to. */ - CONST char *localName; /* Name of link variable. */ - int flags; /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY: - * indicates scope of localName. */ +Tcl_UpvarObjCmd(dummy, interp, objc, objv) + ClientData dummy; /* Not used. */ + Tcl_Interp *interp; /* Current interpreter. */ + int objc; /* Number of arguments. */ + Tcl_Obj *CONST objv[]; /* Argument objects. */ { - int result; CallFrame *framePtr; - Tcl_Obj *part1Ptr; + char *frameSpec, *localName; + int result; - part1Ptr = Tcl_NewStringObj(part1, -1); - Tcl_IncrRefCount(part1Ptr); + if (objc < 3) { + upvarSyntax: + Tcl_WrongNumArgs(interp, 1, objv, + "?level? otherVar localVar ?otherVar localVar ...?"); + return TCL_ERROR; + } - result = TclGetFrame(interp, frameName, &framePtr); + /* + * Find the call frame containing each of the "other variables" to be + * linked to. + */ + + frameSpec = TclGetString(objv[1]); + result = TclGetFrame(interp, frameSpec, &framePtr); if (result == -1) { return TCL_ERROR; } - result = ObjMakeUpvar(interp, framePtr, part1Ptr, part2, 0, - localName, flags, -1); + objc -= result+1; + if ((objc & 1) != 0) { + goto upvarSyntax; + } + objv += result+1; - TclDecrRefCount(part1Ptr); - return result; + /* + * Iterate over each (other variable, local variable) pair. + * Divide the other variable name into two parts, then call + * MakeUpvar to do all the work of linking it to the local variable. + */ + + for ( ; objc > 0; objc -= 2, objv += 2) { + localName = TclGetString(objv[1]); + result = ObjMakeUpvar(interp, framePtr, /* othervarName */ objv[0], + NULL, 0, /* myVarName */ localName, /*flags*/ 0, -1); + if (result != TCL_OK) { + return TCL_ERROR; + } + } + return TCL_OK; } /* *---------------------------------------------------------------------- * - * Tcl_GetVariableFullName -- + * DisposeTraceResult-- * - * Given a Tcl_Var token returned by Tcl_FindNamespaceVar, this - * procedure appends to an object the namespace variable's full - * name, qualified by a sequence of parent namespace names. + * This procedure is called to dispose of the result returned from + * a trace procedure. The disposal method appropriate to the type + * of result is determined by flags. * * Results: - * None. + * None. * * Side effects: - * The variable's fully-qualified name is appended to the string - * representation of objPtr. + * The memory allocated for the trace result may be freed. * *---------------------------------------------------------------------- */ void -Tcl_GetVariableFullName(interp, variable, objPtr) - Tcl_Interp *interp; /* Interpreter containing the variable. */ - Tcl_Var variable; /* Token for the variable returned by a - * previous call to Tcl_FindNamespaceVar. */ - Tcl_Obj *objPtr; /* Points to the object onto which the - * variable's full name is appended. */ +DisposeTraceResult(flags, result) + int flags; /* Indicates type of result to determine + * proper disposal method */ + char *result; /* The result returned from a trace + * procedure to be disposed */ { - Interp *iPtr = (Interp *) interp; - register Var *varPtr = (Var *) variable; - char *name; - - /* - * Add the full name of the containing namespace (if any), followed by - * the "::" separator, then the variable name. - */ - - if (varPtr != NULL) { - if (!TclIsVarArrayElement(varPtr)) { - if (varPtr->nsPtr != NULL) { - Tcl_AppendToObj(objPtr, varPtr->nsPtr->fullName, -1); - if (varPtr->nsPtr != iPtr->globalNsPtr) { - Tcl_AppendToObj(objPtr, "::", 2); - } - } - if (varPtr->name != NULL) { - Tcl_AppendToObj(objPtr, varPtr->name, -1); - } else if (varPtr->hPtr != NULL) { - name = Tcl_GetHashKey(varPtr->hPtr->tablePtr, varPtr->hPtr); - Tcl_AppendToObj(objPtr, name, -1); - } - } + if (flags & TCL_TRACE_RESULT_DYNAMIC) { + ckfree(result); + } else if (flags & TCL_TRACE_RESULT_OBJECT) { + Tcl_DecrRefCount((Tcl_Obj *) result); } } /* *---------------------------------------------------------------------- * - * Tcl_GlobalObjCmd -- + * CallVarTraces -- * - * This object-based procedure is invoked to process the "global" Tcl - * command. See the user documentation for details on what it does. + * This procedure is invoked to find and invoke relevant + * trace procedures associated with a particular operation on + * a variable. This procedure invokes traces both on the + * variable and on its containing array (where relevant). * * Results: - * A standard Tcl object result value. + * Returns TCL_OK to indicate normal operation. Returns TCL_ERROR + * if invocation of a trace procedure indicated an error. When + * TCL_ERROR is returned and leaveErrMsg is true, then the + * ::errorInfo variable of iPtr has information about the error + * appended to it. * * Side effects: - * See the user documentation. + * Almost anything can happen, depending on trace; this procedure + * itself doesn't have any side effects. * *---------------------------------------------------------------------- */ -int -Tcl_GlobalObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ +int +CallVarTraces(iPtr, arrayPtr, varPtr, part1, part2, flags, leaveErrMsg) + Interp *iPtr; /* Interpreter containing variable. */ + register Var *arrayPtr; /* Pointer to array variable that contains + * the variable, or NULL if the variable + * isn't an element of an array. */ + Var *varPtr; /* Variable whose traces are to be + * invoked. */ + char *part1; + CONST char *part2; /* Variable's two-part name. */ + int flags; /* Flags passed to trace procedures: + * indicates what's happening to variable, + * plus other stuff like TCL_GLOBAL_ONLY, + * TCL_NAMESPACE_ONLY, and + * TCL_INTERP_DESTROYED. */ + CONST int leaveErrMsg; /* If true, and one of the traces indicates an + * error, then leave an error message and stack + * trace information in *iPTr. */ { - Interp *iPtr = (Interp *) interp; - register Tcl_Obj *objPtr; - char *varName; - register char *tail; - int result, i; + register VarTrace *tracePtr; + ActiveVarTrace active; + char *result, *openParen, *p; + Tcl_DString nameCopy; + int copiedName; + int code = TCL_OK; + int disposeFlags = 0; - if (objc < 2) { - Tcl_WrongNumArgs(interp, 1, objv, "varName ?varName ...?"); - return TCL_ERROR; + /* + * If there are already similar trace procedures active for the + * variable, don't call them again. + */ + + if (varPtr->flags & VAR_TRACE_ACTIVE) { + return code; + } + varPtr->flags |= VAR_TRACE_ACTIVE; + varPtr->refCount++; + if (arrayPtr != NULL) { + arrayPtr->refCount++; } /* - * If we are not executing inside a Tcl procedure, just return. + * If the variable name hasn't been parsed into array name and + * element, do it here. If there really is an array element, + * make a copy of the original name so that NULLs can be + * inserted into it to separate the names (can't modify the name + * string in place, because the string might get used by the + * callbacks we invoke). */ - - if ((iPtr->varFramePtr == NULL) - || !iPtr->varFramePtr->isProcCallFrame) { - return TCL_OK; + + copiedName = 0; + if (part2 == NULL) { + for (p = part1; *p ; p++) { + if (*p == '(') { + openParen = p; + do { + p++; + } while (*p != '\0'); + p--; + if (*p == ')') { + int offset = (openParen - part1); + Tcl_DStringInit(&nameCopy); + Tcl_DStringAppend(&nameCopy, part1, (p-part1)); + part2 = Tcl_DStringValue(&nameCopy) + offset + 1; + part1 = Tcl_DStringValue(&nameCopy); + part1[offset] = 0; + copiedName = 1; + } + break; + } + } } - for (i = 1; i < objc; i++) { - /* - * Make a local variable linked to its counterpart in the global :: - * namespace. - */ - - objPtr = objv[i]; - varName = TclGetString(objPtr); + /* + * Invoke traces on the array containing the variable, if relevant. + */ - /* - * The variable name might have a scope qualifier, but the name for - * the local "link" variable must be the simple name at the tail. - */ + result = NULL; + active.nextPtr = iPtr->activeVarTracePtr; + iPtr->activeVarTracePtr = &active; + Tcl_Preserve((ClientData) iPtr); + if (arrayPtr != NULL && !(arrayPtr->flags & VAR_TRACE_ACTIVE)) { + active.varPtr = arrayPtr; + for (tracePtr = arrayPtr->tracePtr; tracePtr != NULL; + tracePtr = active.nextTracePtr) { + active.nextTracePtr = tracePtr->nextPtr; + if (!(tracePtr->flags & flags)) { + continue; + } + Tcl_Preserve((ClientData) tracePtr); + result = (*tracePtr->traceProc)(tracePtr->clientData, + (Tcl_Interp *) iPtr, part1, part2, flags); + if (result != NULL) { + if (flags & TCL_TRACE_UNSETS) { + /* Ignore errors in unset traces */ + DisposeTraceResult(tracePtr->flags, result); + } else { + disposeFlags = tracePtr->flags; + code = TCL_ERROR; + } + } + Tcl_Release((ClientData) tracePtr); + if (code == TCL_ERROR) { + goto done; + } + } + } - for (tail = varName; *tail != '\0'; tail++) { - /* empty body */ + /* + * Invoke traces on the variable itself. + */ + + if (flags & TCL_TRACE_UNSETS) { + flags |= TCL_TRACE_DESTROYED; + } + active.varPtr = varPtr; + for (tracePtr = varPtr->tracePtr; tracePtr != NULL; + tracePtr = active.nextTracePtr) { + active.nextTracePtr = tracePtr->nextPtr; + if (!(tracePtr->flags & flags)) { + continue; } - while ((tail > varName) && ((*tail != ':') || (*(tail-1) != ':'))) { - tail--; + Tcl_Preserve((ClientData) tracePtr); + result = (*tracePtr->traceProc)(tracePtr->clientData, + (Tcl_Interp *) iPtr, part1, part2, flags); + if (result != NULL) { + if (flags & TCL_TRACE_UNSETS) { + /* Ignore errors in unset traces */ + DisposeTraceResult(tracePtr->flags, result); + } else { + disposeFlags = tracePtr->flags; + code = TCL_ERROR; + } } - if ((*tail == ':') && (tail > varName)) { - tail++; + Tcl_Release((ClientData) tracePtr); + if (code == TCL_ERROR) { + goto done; } + } - /* - * Link to the variable "varName" in the global :: namespace. - */ - - result = ObjMakeUpvar(interp, (CallFrame *) NULL, - objPtr, NULL, /*otherFlags*/ TCL_GLOBAL_ONLY, - /*myName*/ tail, /*myFlags*/ 0, -1); - if (result != TCL_OK) { - return result; + /* + * Restore the variable's flags, remove the record of our active + * traces, and then return. + */ + + done: + if (code == TCL_ERROR) { + if (leaveErrMsg) { + CONST char *type = ""; + switch (flags&(TCL_TRACE_READS|TCL_TRACE_WRITES|TCL_TRACE_ARRAY)) { + case TCL_TRACE_READS: { + type = "read"; + break; + } + case TCL_TRACE_WRITES: { + type = "set"; + break; + } + case TCL_TRACE_ARRAY: { + type = "trace array"; + break; + } + } + if (disposeFlags & TCL_TRACE_RESULT_OBJECT) { + VarErrMsg((Tcl_Interp *) iPtr, part1, part2, type, + Tcl_GetString((Tcl_Obj *) result)); + } else { + VarErrMsg((Tcl_Interp *) iPtr, part1, part2, type, result); + } } + DisposeTraceResult(disposeFlags,result); } - return TCL_OK; + + if (arrayPtr != NULL) { + arrayPtr->refCount--; + } + if (copiedName) { + Tcl_DStringFree(&nameCopy); + } + varPtr->flags &= ~VAR_TRACE_ACTIVE; + varPtr->refCount--; + iPtr->activeVarTracePtr = active.nextPtr; + Tcl_Release((ClientData) iPtr); + return code; } /* *---------------------------------------------------------------------- * - * Tcl_VariableObjCmd -- + * NewVar -- * - * Invoked to implement the "variable" command that creates one or more - * global variables. Handles the following syntax: + * Create a new heap-allocated variable that will eventually be + * entered into a hashtable. * - * variable ?name value...? name ?value? + * Results: + * The return value is a pointer to the new variable structure. It is + * marked as a scalar variable (and not a link or array variable). Its + * value initially is NULL. The variable is not part of any hash table + * yet. Since it will be in a hashtable and not in a call frame, its + * name field is set NULL. It is initially marked as undefined. * - * One or more variables can be created. The variables are initialized - * with the specified values. The value for the last variable is - * optional. + * Side effects: + * Storage gets allocated. + * + *---------------------------------------------------------------------- + */ + +static Var * +NewVar() +{ + register Var *varPtr; + + varPtr = (Var *) ckalloc(sizeof(Var)); + varPtr->value.objPtr = NULL; + varPtr->name = NULL; + varPtr->nsPtr = NULL; + varPtr->hPtr = NULL; + varPtr->refCount = 0; + varPtr->tracePtr = NULL; + varPtr->searchPtr = NULL; + varPtr->flags = (VAR_SCALAR | VAR_UNDEFINED | VAR_IN_HASHTABLE); + return varPtr; +} + +/* + *---------------------------------------------------------------------- * - * If the variable does not exist, it is created and given the optional - * value. If it already exists, it is simply set to the optional - * value. Normally, "name" is an unqualified name, so it is created in - * the current namespace. If it includes namespace qualifiers, it can - * be created in another namespace. + * SetArraySearchObj -- * - * If the variable command is executed inside a Tcl procedure, it - * creates a local variable linked to the newly-created namespace - * variable. + * This function converts the given tcl object into one that + * has the "array search" internal type. * * Results: - * Returns TCL_OK if the variable is found or created. Returns - * TCL_ERROR if anything goes wrong. + * TCL_OK if the conversion succeeded, and TCL_ERROR if it failed + * (when an error message will be placed in the interpreter's + * result.) * * Side effects: - * If anything goes wrong, this procedure returns an error message - * as the result in the interpreter's result object. + * Updates the internal type and representation of the object to + * make this an array-search object. See the tclArraySearchType + * declaration above for details of the internal representation. * *---------------------------------------------------------------------- */ -int -Tcl_VariableObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ +static int +SetArraySearchObj(interp, objPtr) + Tcl_Interp *interp; + Tcl_Obj *objPtr; { - Interp *iPtr = (Interp *) interp; - char *varName, *tail, *cp; - Var *varPtr, *arrayPtr; - Tcl_Obj *varValuePtr; - int i, result; - Tcl_Obj *varNamePtr; - - if (objc < 2) { - Tcl_WrongNumArgs(interp, 1, objv, "?name value...? name ?value?"); - return TCL_ERROR; - } - - for (i = 1; i < objc; i = i+2) { - /* - * Look up each variable in the current namespace context, creating - * it if necessary. - */ - - varNamePtr = objv[i]; - varName = TclGetString(varNamePtr); - varPtr = TclObjLookupVar(interp, varNamePtr, NULL, - (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG), "define", - /*createPart1*/ 1, /*createPart2*/ 0, &arrayPtr); - - if (arrayPtr != NULL) { - /* - * Variable cannot be an element in an array. If arrayPtr is - * non-null, it is, so throw up an error and return. - */ - VarErrMsg(interp, varName, NULL, "define", isArrayElement); - return TCL_ERROR; - } - - if (varPtr == NULL) { - return TCL_ERROR; - } - - /* - * Mark the variable as a namespace variable and increment its - * reference count so that it will persist until its namespace is - * destroyed or until the variable is unset. - */ - - if (!(varPtr->flags & VAR_NAMESPACE_VAR)) { - varPtr->flags |= VAR_NAMESPACE_VAR; - varPtr->refCount++; - } - - /* - * If a value was specified, set the variable to that value. - * Otherwise, if the variable is new, leave it undefined. - * (If the variable already exists and no value was specified, - * leave its value unchanged; just create the local link if - * we're in a Tcl procedure). - */ + char *string; + char *end; + int id; + size_t offset; - if (i+1 < objc) { /* a value was specified */ - varValuePtr = TclPtrSetVar(interp, varPtr, arrayPtr, varName, NULL, - objv[i+1], (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG)); - if (varValuePtr == NULL) { - return TCL_ERROR; - } - } + /* + * Get the string representation. Make it up-to-date if necessary. + */ - /* - * If we are executing inside a Tcl procedure, create a local - * variable linked to the new namespace variable "varName". - */ + string = Tcl_GetString(objPtr); - if ((iPtr->varFramePtr != NULL) - && iPtr->varFramePtr->isProcCallFrame) { - /* - * varName might have a scope qualifier, but the name for the - * local "link" variable must be the simple name at the tail. - * - * Locate tail in one pass: drop any prefix after two *or more* - * consecutive ":" characters). - */ + /* + * Parse the id into the three parts separated by dashes. + */ + if ((string[0] != 's') || (string[1] != '-')) { + syntax: + Tcl_AppendResult(interp, "illegal search identifier \"", string, + "\"", (char *) NULL); + return TCL_ERROR; + } + id = strtoul(string+2, &end, 10); + if ((end == (string+2)) || (*end != '-')) { + goto syntax; + } + /* + * Can't perform value check in this context, so place reference + * to place in string to use for the check in the object instead. + */ + end++; + offset = end - string; - for (tail = cp = varName; *cp != '\0'; ) { - if (*cp++ == ':') { - while (*cp == ':') { - tail = ++cp; - } - } - } - - /* - * Create a local link "tail" to the variable "varName" in the - * current namespace. - */ - - result = ObjMakeUpvar(interp, (CallFrame *) NULL, - /*otherP1*/ varNamePtr, /*otherP2*/ NULL, - /*otherFlags*/ TCL_NAMESPACE_ONLY, - /*myName*/ tail, /*myFlags*/ 0, -1); - if (result != TCL_OK) { - return result; - } - } + if (objPtr->typePtr != NULL && objPtr->typePtr->freeIntRepProc != NULL) { + objPtr->typePtr->freeIntRepProc(objPtr); } + objPtr->typePtr = &tclArraySearchType; + objPtr->internalRep.twoPtrValue.ptr1 = (VOID *)(((char *)NULL)+id); + objPtr->internalRep.twoPtrValue.ptr2 = (VOID *)(((char *)NULL)+offset); return TCL_OK; } /* *---------------------------------------------------------------------- * - * Tcl_UpvarObjCmd -- + * ParseSearchId -- * - * This object-based procedure is invoked to process the "upvar" - * Tcl command. See the user documentation for details on what it does. + * This procedure translates from a tcl object to a pointer to an + * active array search (if there is one that matches the string). * * Results: - * A standard Tcl object result value. + * The return value is a pointer to the array search indicated + * by string, or NULL if there isn't one. If NULL is returned, + * the interp's result contains an error message. * * Side effects: - * See the user documentation. + * The tcl object might have its internal type and representation + * modified. * *---------------------------------------------------------------------- */ - /* ARGSUSED */ -int -Tcl_UpvarObjCmd(dummy, interp, objc, objv) - ClientData dummy; /* Not used. */ - Tcl_Interp *interp; /* Current interpreter. */ - int objc; /* Number of arguments. */ - Tcl_Obj *CONST objv[]; /* Argument objects. */ +static ArraySearch * +ParseSearchId(interp, varPtr, varName, handleObj) + Tcl_Interp *interp; /* Interpreter containing variable. */ + CONST Var *varPtr; /* Array variable search is for. */ + CONST char *varName; /* Name of array variable that search is + * supposed to be for. */ + Tcl_Obj *handleObj; /* Object containing id of search. Must have + * form "search-num-var" where "num" is a + * decimal number and "var" is a variable + * name. */ { - CallFrame *framePtr; - char *frameSpec, *localName; - int result; - - if (objc < 3) { - upvarSyntax: - Tcl_WrongNumArgs(interp, 1, objv, - "?level? otherVar localVar ?otherVar localVar ...?"); - return TCL_ERROR; - } + register char *string; + register size_t offset; + int id; + ArraySearch *searchPtr; /* - * Find the call frame containing each of the "other variables" to be - * linked to. + * Parse the id. */ - - frameSpec = TclGetString(objv[1]); - result = TclGetFrame(interp, frameSpec, &framePtr); - if (result == -1) { - return TCL_ERROR; + if (Tcl_ConvertToType(interp, handleObj, &tclArraySearchType) != TCL_OK) { + return NULL; } - objc -= result+1; - if ((objc & 1) != 0) { - goto upvarSyntax; + /* + * Cast is safe, since always came from an int in the first place. + */ + id = (int)(((char*)handleObj->internalRep.twoPtrValue.ptr1) - + ((char*)NULL)); + string = Tcl_GetString(handleObj); + offset = (((char*)handleObj->internalRep.twoPtrValue.ptr2) - + ((char*)NULL)); + /* + * This test cannot be placed inside the Tcl_Obj machinery, since + * it is dependent on the variable context. + */ + if (strcmp(string+offset, varName) != 0) { + Tcl_AppendResult(interp, "search identifier \"", string, + "\" isn't for variable \"", varName, "\"", (char *) NULL); + return NULL; } - objv += result+1; /* - * Iterate over each (other variable, local variable) pair. - * Divide the other variable name into two parts, then call - * MakeUpvar to do all the work of linking it to the local variable. + * Search through the list of active searches on the interpreter + * to see if the desired one exists. + * + * Note that we cannot store the searchPtr directly in the Tcl_Obj + * as that would run into trouble when DeleteSearches() was called + * so we must scan this list every time. */ - for ( ; objc > 0; objc -= 2, objv += 2) { - localName = TclGetString(objv[1]); - result = ObjMakeUpvar(interp, framePtr, /* othervarName */ objv[0], - NULL, 0, /* myVarName */ localName, /*flags*/ 0, -1); - if (result != TCL_OK) { - return TCL_ERROR; + for (searchPtr = varPtr->searchPtr; searchPtr != NULL; + searchPtr = searchPtr->nextPtr) { + if (searchPtr->id == id) { + return searchPtr; } } - return TCL_OK; + Tcl_AppendResult(interp, "couldn't find search \"", string, "\"", + (char *) NULL); + return NULL; } /* *---------------------------------------------------------------------- * - * DisposeTraceResult-- + * DeleteSearches -- * - * This procedure is called to dispose of the result returned from - * a trace procedure. The disposal method appropriate to the type - * of result is determined by flags. + * This procedure is called to free up all of the searches + * associated with an array variable. * * Results: * None. * * Side effects: - * The memory allocated for the trace result may be freed. + * Memory is released to the storage allocator. * *---------------------------------------------------------------------- */ -void -DisposeTraceResult(flags, result) - int flags; /* Indicates type of result to determine - * proper disposal method */ - char *result; /* The result returned from a trace - * procedure to be disposed */ +static void +DeleteSearches(arrayVarPtr) + register Var *arrayVarPtr; /* Variable whose searches are + * to be deleted. */ { - if (flags & TCL_TRACE_RESULT_DYNAMIC) { - ckfree(result); - } else if (flags & TCL_TRACE_RESULT_OBJECT) { - Tcl_DecrRefCount((Tcl_Obj *) result); + ArraySearch *searchPtr; + + while (arrayVarPtr->searchPtr != NULL) { + searchPtr = arrayVarPtr->searchPtr; + arrayVarPtr->searchPtr = searchPtr->nextPtr; + ckfree((char *) searchPtr); } } /* *---------------------------------------------------------------------- * - * CallVarTraces -- + * TclDeleteVars -- * - * This procedure is invoked to find and invoke relevant - * trace procedures associated with a particular operation on - * a variable. This procedure invokes traces both on the - * variable and on its containing array (where relevant). + * This procedure is called to recycle all the storage space + * associated with a table of variables. For this procedure + * to work correctly, it must not be possible for any of the + * variables in the table to be accessed from Tcl commands + * (e.g. from trace procedures). * * Results: - * Returns TCL_OK to indicate normal operation. Returns TCL_ERROR - * if invocation of a trace procedure indicated an error. When - * TCL_ERROR is returned and leaveErrMsg is true, then the - * ::errorInfo variable of iPtr has information about the error - * appended to it. + * None. * * Side effects: - * Almost anything can happen, depending on trace; this procedure - * itself doesn't have any side effects. + * Variables are deleted and trace procedures are invoked, if + * any are declared. * *---------------------------------------------------------------------- */ -int -CallVarTraces(iPtr, arrayPtr, varPtr, part1, part2, flags, leaveErrMsg) - Interp *iPtr; /* Interpreter containing variable. */ - register Var *arrayPtr; /* Pointer to array variable that contains - * the variable, or NULL if the variable - * isn't an element of an array. */ - Var *varPtr; /* Variable whose traces are to be - * invoked. */ - char *part1; - CONST char *part2; /* Variable's two-part name. */ - int flags; /* Flags passed to trace procedures: - * indicates what's happening to variable, - * plus other stuff like TCL_GLOBAL_ONLY, - * TCL_NAMESPACE_ONLY, and - * TCL_INTERP_DESTROYED. */ - CONST int leaveErrMsg; /* If true, and one of the traces indicates an - * error, then leave an error message and stack - * trace information in *iPTr. */ +void +TclDeleteVars(iPtr, tablePtr) + Interp *iPtr; /* Interpreter to which variables belong. */ + Tcl_HashTable *tablePtr; /* Hash table containing variables to + * delete. */ { - register VarTrace *tracePtr; - ActiveVarTrace active; - char *result, *openParen, *p; - Tcl_DString nameCopy; - int copiedName; - int code = TCL_OK; - int disposeFlags = 0; + Tcl_Interp *interp = (Tcl_Interp *) iPtr; + Tcl_HashSearch search; + Tcl_HashEntry *hPtr; + register Var *varPtr; + Var *linkPtr; + int flags; + ActiveVarTrace *activePtr; + Tcl_Obj *objPtr; + Namespace *currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp); /* - * If there are already similar trace procedures active for the - * variable, don't call them again. + * Determine what flags to pass to the trace callback procedures. */ - if (varPtr->flags & VAR_TRACE_ACTIVE) { - return code; + flags = TCL_TRACE_UNSETS; + if (tablePtr == &iPtr->globalNsPtr->varTable) { + flags |= (TCL_INTERP_DESTROYED | TCL_GLOBAL_ONLY); + } else if (tablePtr == &currNsPtr->varTable) { + flags |= TCL_NAMESPACE_ONLY; } - varPtr->flags |= VAR_TRACE_ACTIVE; - varPtr->refCount++; - if (arrayPtr != NULL) { - arrayPtr->refCount++; + + for (hPtr = Tcl_FirstHashEntry(tablePtr, &search); hPtr != NULL; + hPtr = Tcl_NextHashEntry(&search)) { + varPtr = (Var *) Tcl_GetHashValue(hPtr); + + /* + * For global/upvar variables referenced in procedures, decrement + * the reference count on the variable referred to, and free + * the referenced variable if it's no longer needed. Don't delete + * the hash entry for the other variable if it's in the same table + * as us: this will happen automatically later on. + */ + + if (TclIsVarLink(varPtr)) { + linkPtr = varPtr->value.linkPtr; + linkPtr->refCount--; + if ((linkPtr->refCount == 0) && TclIsVarUndefined(linkPtr) + && (linkPtr->tracePtr == NULL) + && (linkPtr->flags & VAR_IN_HASHTABLE)) { + if (linkPtr->hPtr == NULL) { + ckfree((char *) linkPtr); + } else if (linkPtr->hPtr->tablePtr != tablePtr) { + Tcl_DeleteHashEntry(linkPtr->hPtr); + ckfree((char *) linkPtr); + } + } + } + + /* + * Invoke traces on the variable that is being deleted, then + * free up the variable's space (no need to free the hash entry + * here, unless we're dealing with a global variable: the + * hash entries will be deleted automatically when the whole + * table is deleted). Note that we give CallVarTraces the variable's + * fully-qualified name so that any called trace procedures can + * refer to these variables being deleted. + */ + + if (varPtr->tracePtr != NULL) { + objPtr = Tcl_NewObj(); + Tcl_IncrRefCount(objPtr); /* until done with traces */ + Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr, objPtr); + CallVarTraces(iPtr, (Var *) NULL, varPtr, Tcl_GetString(objPtr), + NULL, flags, /* leaveErrMsg */ 0); + Tcl_DecrRefCount(objPtr); /* free no longer needed obj */ + + while (varPtr->tracePtr != NULL) { + VarTrace *tracePtr = varPtr->tracePtr; + varPtr->tracePtr = tracePtr->nextPtr; + Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); + } + for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; + activePtr = activePtr->nextPtr) { + if (activePtr->varPtr == varPtr) { + activePtr->nextTracePtr = NULL; + } + } + } + + if (TclIsVarArray(varPtr)) { + DeleteArray(iPtr, Tcl_GetHashKey(tablePtr, hPtr), varPtr, + flags); + varPtr->value.tablePtr = NULL; + } + if (TclIsVarScalar(varPtr) && (varPtr->value.objPtr != NULL)) { + objPtr = varPtr->value.objPtr; + TclDecrRefCount(objPtr); + varPtr->value.objPtr = NULL; + } + varPtr->hPtr = NULL; + varPtr->tracePtr = NULL; + TclSetVarUndefined(varPtr); + TclSetVarScalar(varPtr); + + /* + * If the variable was a namespace variable, decrement its + * reference count. We are in the process of destroying its + * namespace so that namespace will no longer "refer" to the + * variable. + */ + + if (varPtr->flags & VAR_NAMESPACE_VAR) { + varPtr->flags &= ~VAR_NAMESPACE_VAR; + varPtr->refCount--; + } + + /* + * Recycle the variable's memory space if there aren't any upvar's + * pointing to it. If there are upvars to this variable, then the + * variable will get freed when the last upvar goes away. + */ + + if (varPtr->refCount == 0) { + ckfree((char *) varPtr); /* this Var must be VAR_IN_HASHTABLE */ + } } + Tcl_DeleteHashTable(tablePtr); +} + +/* + *---------------------------------------------------------------------- + * + * TclDeleteCompiledLocalVars -- + * + * This procedure is called to recycle storage space associated with + * the compiler-allocated array of local variables in a procedure call + * frame. This procedure resembles TclDeleteVars above except that each + * variable is stored in a call frame and not a hash table. For this + * procedure to work correctly, it must not be possible for any of the + * variable in the table to be accessed from Tcl commands (e.g. from + * trace procedures). + * + * Results: + * None. + * + * Side effects: + * Variables are deleted and trace procedures are invoked, if + * any are declared. + * + *---------------------------------------------------------------------- + */ - /* - * If the variable name hasn't been parsed into array name and - * element, do it here. If there really is an array element, - * make a copy of the original name so that NULLs can be - * inserted into it to separate the names (can't modify the name - * string in place, because the string might get used by the - * callbacks we invoke). - */ +void +TclDeleteCompiledLocalVars(iPtr, framePtr) + Interp *iPtr; /* Interpreter to which variables belong. */ + CallFrame *framePtr; /* Procedure call frame containing + * compiler-assigned local variables to + * delete. */ +{ + register Var *varPtr; + int flags; /* Flags passed to trace procedures. */ + Var *linkPtr; + ActiveVarTrace *activePtr; + int numLocals, i; + + flags = TCL_TRACE_UNSETS; + numLocals = framePtr->numCompiledLocals; + varPtr = framePtr->compiledLocals; + for (i = 0; i < numLocals; i++) { + /* + * For global/upvar variables referenced in procedures, decrement + * the reference count on the variable referred to, and free + * the referenced variable if it's no longer needed. Don't delete + * the hash entry for the other variable if it's in the same table + * as us: this will happen automatically later on. + */ - copiedName = 0; - if (part2 == NULL) { - for (p = part1; *p ; p++) { - if (*p == '(') { - openParen = p; - do { - p++; - } while (*p != '\0'); - p--; - if (*p == ')') { - int offset = (openParen - part1); - Tcl_DStringInit(&nameCopy); - Tcl_DStringAppend(&nameCopy, part1, (p-part1)); - part2 = Tcl_DStringValue(&nameCopy) + offset + 1; - part1 = Tcl_DStringValue(&nameCopy); - part1[offset] = 0; - copiedName = 1; + if (TclIsVarLink(varPtr)) { + linkPtr = varPtr->value.linkPtr; + linkPtr->refCount--; + if ((linkPtr->refCount == 0) && TclIsVarUndefined(linkPtr) + && (linkPtr->tracePtr == NULL) + && (linkPtr->flags & VAR_IN_HASHTABLE)) { + if (linkPtr->hPtr == NULL) { + ckfree((char *) linkPtr); + } else { + Tcl_DeleteHashEntry(linkPtr->hPtr); + ckfree((char *) linkPtr); } - break; } } - } - /* - * Invoke traces on the array containing the variable, if relevant. - */ + /* + * Invoke traces on the variable that is being deleted. Then delete + * the variable's trace records. + */ - result = NULL; - active.nextPtr = iPtr->activeVarTracePtr; - iPtr->activeVarTracePtr = &active; - Tcl_Preserve((ClientData) iPtr); - if (arrayPtr != NULL && !(arrayPtr->flags & VAR_TRACE_ACTIVE)) { - active.varPtr = arrayPtr; - for (tracePtr = arrayPtr->tracePtr; tracePtr != NULL; - tracePtr = active.nextTracePtr) { - active.nextTracePtr = tracePtr->nextPtr; - if (!(tracePtr->flags & flags)) { - continue; + if (varPtr->tracePtr != NULL) { + CallVarTraces(iPtr, (Var *) NULL, varPtr, varPtr->name, NULL, + flags, /* leaveErrMsg */ 0); + while (varPtr->tracePtr != NULL) { + VarTrace *tracePtr = varPtr->tracePtr; + varPtr->tracePtr = tracePtr->nextPtr; + Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); } - Tcl_Preserve((ClientData) tracePtr); - result = (*tracePtr->traceProc)(tracePtr->clientData, - (Tcl_Interp *) iPtr, part1, part2, flags); - if (result != NULL) { - if (flags & TCL_TRACE_UNSETS) { - /* Ignore errors in unset traces */ - DisposeTraceResult(tracePtr->flags, result); - } else { - disposeFlags = tracePtr->flags; - code = TCL_ERROR; + for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; + activePtr = activePtr->nextPtr) { + if (activePtr->varPtr == varPtr) { + activePtr->nextTracePtr = NULL; } } - Tcl_Release((ClientData) tracePtr); - if (code == TCL_ERROR) { - goto done; - } } + + /* + * Now if the variable is an array, delete its element hash table. + * Otherwise, if it's a scalar variable, decrement the ref count + * of its value. + */ + + if (TclIsVarArray(varPtr) && (varPtr->value.tablePtr != NULL)) { + DeleteArray(iPtr, varPtr->name, varPtr, flags); + } + if (TclIsVarScalar(varPtr) && (varPtr->value.objPtr != NULL)) { + TclDecrRefCount(varPtr->value.objPtr); + varPtr->value.objPtr = NULL; + } + varPtr->hPtr = NULL; + varPtr->tracePtr = NULL; + TclSetVarUndefined(varPtr); + TclSetVarScalar(varPtr); + varPtr++; } +} + +/* + *---------------------------------------------------------------------- + * + * DeleteArray -- + * + * This procedure is called to free up everything in an array + * variable. It's the caller's responsibility to make sure + * that the array is no longer accessible before this procedure + * is called. + * + * Results: + * None. + * + * Side effects: + * All storage associated with varPtr's array elements is deleted + * (including the array's hash table). Deletion trace procedures for + * array elements are invoked, then deleted. Any pending traces for + * array elements are also deleted. + * + *---------------------------------------------------------------------- + */ - /* - * Invoke traces on the variable itself. - */ +static void +DeleteArray(iPtr, arrayName, varPtr, flags) + Interp *iPtr; /* Interpreter containing array. */ + char *arrayName; /* Name of array (used for trace + * callbacks). */ + Var *varPtr; /* Pointer to variable structure. */ + int flags; /* Flags to pass to CallVarTraces: + * TCL_TRACE_UNSETS and sometimes + * TCL_INTERP_DESTROYED, + * TCL_NAMESPACE_ONLY, or + * TCL_GLOBAL_ONLY. */ +{ + Tcl_HashSearch search; + register Tcl_HashEntry *hPtr; + register Var *elPtr; + ActiveVarTrace *activePtr; + Tcl_Obj *objPtr; - if (flags & TCL_TRACE_UNSETS) { - flags |= TCL_TRACE_DESTROYED; - } - active.varPtr = varPtr; - for (tracePtr = varPtr->tracePtr; tracePtr != NULL; - tracePtr = active.nextTracePtr) { - active.nextTracePtr = tracePtr->nextPtr; - if (!(tracePtr->flags & flags)) { - continue; + DeleteSearches(varPtr); + for (hPtr = Tcl_FirstHashEntry(varPtr->value.tablePtr, &search); + hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { + elPtr = (Var *) Tcl_GetHashValue(hPtr); + if (TclIsVarScalar(elPtr) && (elPtr->value.objPtr != NULL)) { + objPtr = elPtr->value.objPtr; + TclDecrRefCount(objPtr); + elPtr->value.objPtr = NULL; } - Tcl_Preserve((ClientData) tracePtr); - result = (*tracePtr->traceProc)(tracePtr->clientData, - (Tcl_Interp *) iPtr, part1, part2, flags); - if (result != NULL) { - if (flags & TCL_TRACE_UNSETS) { - /* Ignore errors in unset traces */ - DisposeTraceResult(tracePtr->flags, result); - } else { - disposeFlags = tracePtr->flags; - code = TCL_ERROR; + elPtr->hPtr = NULL; + if (elPtr->tracePtr != NULL) { + elPtr->flags &= ~VAR_TRACE_ACTIVE; + CallVarTraces(iPtr, (Var *) NULL, elPtr, arrayName, + Tcl_GetHashKey(varPtr->value.tablePtr, hPtr), flags, + /* leaveErrMsg */ 0); + while (elPtr->tracePtr != NULL) { + VarTrace *tracePtr = elPtr->tracePtr; + elPtr->tracePtr = tracePtr->nextPtr; + Tcl_EventuallyFree((ClientData) tracePtr,TCL_DYNAMIC); + } + for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; + activePtr = activePtr->nextPtr) { + if (activePtr->varPtr == elPtr) { + activePtr->nextTracePtr = NULL; + } } } - Tcl_Release((ClientData) tracePtr); - if (code == TCL_ERROR) { - goto done; + TclSetVarUndefined(elPtr); + TclSetVarScalar(elPtr); + if (elPtr->refCount == 0) { + ckfree((char *) elPtr); /* element Vars are VAR_IN_HASHTABLE */ } } + Tcl_DeleteHashTable(varPtr->value.tablePtr); + ckfree((char *) varPtr->value.tablePtr); +} + +/* + *---------------------------------------------------------------------- + * + * CleanupVar -- + * + * This procedure is called when it looks like it may be OK to free up + * a variable's storage. If the variable is in a hashtable, its Var + * structure and hash table entry will be freed along with those of its + * containing array, if any. This procedure is called, for example, + * when a trace on a variable deletes a variable. + * + * Results: + * None. + * + * Side effects: + * If the variable (or its containing array) really is dead and in a + * hashtable, then its Var structure, and possibly its hash table + * entry, is freed up. + * + *---------------------------------------------------------------------- + */ - /* - * Restore the variable's flags, remove the record of our active - * traces, and then return. - */ - - done: - if (code == TCL_ERROR) { - if (leaveErrMsg) { - CONST char *type = ""; - switch (flags&(TCL_TRACE_READS|TCL_TRACE_WRITES|TCL_TRACE_ARRAY)) { - case TCL_TRACE_READS: { - type = "read"; - break; - } - case TCL_TRACE_WRITES: { - type = "set"; - break; - } - case TCL_TRACE_ARRAY: { - type = "trace array"; - break; - } - } - if (disposeFlags & TCL_TRACE_RESULT_OBJECT) { - VarErrMsg((Tcl_Interp *) iPtr, part1, part2, type, - Tcl_GetString((Tcl_Obj *) result)); - } else { - VarErrMsg((Tcl_Interp *) iPtr, part1, part2, type, result); - } +static void +CleanupVar(varPtr, arrayPtr) + Var *varPtr; /* Pointer to variable that may be a + * candidate for being expunged. */ + Var *arrayPtr; /* Array that contains the variable, or + * NULL if this variable isn't an array + * element. */ +{ + if (TclIsVarUndefined(varPtr) && (varPtr->refCount == 0) + && (varPtr->tracePtr == NULL) + && (varPtr->flags & VAR_IN_HASHTABLE)) { + if (varPtr->hPtr != NULL) { + Tcl_DeleteHashEntry(varPtr->hPtr); } - DisposeTraceResult(disposeFlags,result); + ckfree((char *) varPtr); } - if (arrayPtr != NULL) { - arrayPtr->refCount--; - } - if (copiedName) { - Tcl_DStringFree(&nameCopy); + if (TclIsVarUndefined(arrayPtr) && (arrayPtr->refCount == 0) + && (arrayPtr->tracePtr == NULL) + && (arrayPtr->flags & VAR_IN_HASHTABLE)) { + if (arrayPtr->hPtr != NULL) { + Tcl_DeleteHashEntry(arrayPtr->hPtr); + } + ckfree((char *) arrayPtr); + } } - varPtr->flags &= ~VAR_TRACE_ACTIVE; - varPtr->refCount--; - iPtr->activeVarTracePtr = active.nextPtr; - Tcl_Release((ClientData) iPtr); - return code; } - /* *---------------------------------------------------------------------- * - * NewVar -- + * VarErrMsg -- * - * Create a new heap-allocated variable that will eventually be - * entered into a hashtable. + * Generate a reasonable error message describing why a variable + * operation failed. * * Results: - * The return value is a pointer to the new variable structure. It is - * marked as a scalar variable (and not a link or array variable). Its - * value initially is NULL. The variable is not part of any hash table - * yet. Since it will be in a hashtable and not in a call frame, its - * name field is set NULL. It is initially marked as undefined. + * None. * * Side effects: - * Storage gets allocated. + * The interp's result is set to hold a message identifying the + * variable given by part1 and part2 and describing why the + * variable operation failed. * *---------------------------------------------------------------------- */ -static Var * -NewVar() +static void +VarErrMsg(interp, part1, part2, operation, reason) + Tcl_Interp *interp; /* Interpreter in which to record message. */ + CONST char *part1; + CONST char *part2; /* Variable's two-part name. */ + CONST char *operation; /* String describing operation that failed, + * e.g. "read", "set", or "unset". */ + CONST char *reason; /* String describing why operation failed. */ { - register Var *varPtr; - - varPtr = (Var *) ckalloc(sizeof(Var)); - varPtr->value.objPtr = NULL; - varPtr->name = NULL; - varPtr->nsPtr = NULL; - varPtr->hPtr = NULL; - varPtr->refCount = 0; - varPtr->tracePtr = NULL; - varPtr->searchPtr = NULL; - varPtr->flags = (VAR_SCALAR | VAR_UNDEFINED | VAR_IN_HASHTABLE); - return varPtr; + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "can't ", operation, " \"", part1, + (char *) NULL); + if (part2 != NULL) { + Tcl_AppendResult(interp, "(", part2, ")", (char *) NULL); + } + Tcl_AppendResult(interp, "\": ", reason, (char *) NULL); } /* *---------------------------------------------------------------------- * - * SetArraySearchObj -- + * TclTraceVarExists -- * - * This function converts the given tcl object into one that - * has the "array search" internal type. + * This is called from info exists. We need to trigger read + * and/or array traces because they may end up creating a + * variable that doesn't currently exist. * * Results: - * TCL_OK if the conversion succeeded, and TCL_ERROR if it failed - * (when an error message will be placed in the interpreter's - * result.) + * A pointer to the Var structure, or NULL. * * Side effects: - * Updates the internal type and representation of the object to - * make this an array-search object. See the tclArraySearchType - * declaration above for details of the internal representation. + * May fill in error messages in the interp. * *---------------------------------------------------------------------- */ -static int -SetArraySearchObj(interp, objPtr) - Tcl_Interp *interp; - Tcl_Obj *objPtr; +Var * +TclVarTraceExists(interp, varName) + Tcl_Interp *interp; /* The interpreter */ + char *varName; /* The variable name */ { - char *string; - char *end; - int id; - size_t offset; + Var *varPtr; + Var *arrayPtr; /* - * Get the string representation. Make it up-to-date if necessary. + * The choice of "create" flag values is delicate here, and + * matches the semantics of GetVar. Things are still not perfect, + * however, because if you do "info exists x" you get a varPtr + * and therefore trigger traces. However, if you do + * "info exists x(i)", then you only get a varPtr if x is already + * known to be an array. Otherwise you get NULL, and no trace + * is triggered. This matches Tcl 7.6 semantics. */ - string = Tcl_GetString(objPtr); + varPtr = TclLookupVar(interp, varName, (char *) NULL, + 0, "access", /*createPart1*/ 0, /*createPart2*/ 1, &arrayPtr); - /* - * Parse the id into the three parts separated by dashes. - */ - if ((string[0] != 's') || (string[1] != '-')) { - syntax: - Tcl_AppendResult(interp, "illegal search identifier \"", string, - "\"", (char *) NULL); - return TCL_ERROR; + if (varPtr == NULL) { + return NULL; } - id = strtoul(string+2, &end, 10); - if ((end == (string+2)) || (*end != '-')) { - goto syntax; + + if ((varPtr->tracePtr != NULL) + || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { + CallVarTraces((Interp *)interp, arrayPtr, varPtr, varName, NULL, + TCL_TRACE_READS, /* leaveErrMsg */ 0); } + /* - * Can't perform value check in this context, so place reference - * to place in string to use for the check in the object instead. + * If the variable doesn't exist anymore and no-one's using + * it, then free up the relevant structures and hash table entries. */ - end++; - offset = end - string; - if (objPtr->typePtr != NULL && objPtr->typePtr->freeIntRepProc != NULL) { - objPtr->typePtr->freeIntRepProc(objPtr); + if (TclIsVarUndefined(varPtr)) { + CleanupVar(varPtr, arrayPtr); + return NULL; } - objPtr->typePtr = &tclArraySearchType; - objPtr->internalRep.twoPtrValue.ptr1 = (VOID *)(((char *)NULL)+id); - objPtr->internalRep.twoPtrValue.ptr2 = (VOID *)(((char *)NULL)+offset); - return TCL_OK; + + return varPtr; } /* *---------------------------------------------------------------------- * - * ParseSearchId -- + * Internal functions for variable name object types -- * - * This procedure translates from a tcl object to a pointer to an - * active array search (if there is one that matches the string). + *---------------------------------------------------------------------- + */ + +/* + * localVarName - * - * Results: - * The return value is a pointer to the array search indicated - * by string, or NULL if there isn't one. If NULL is returned, - * the interp's result contains an error message. + * INTERNALREP DEFINITION: + * twoPtrValue.ptr1 = pointer to the corresponding Proc + * twoPtrValue.ptr2 = index into locals table +*/ + +static void +FreeLocalVarName(objPtr) + Tcl_Obj *objPtr; +{ + register Proc *procPtr = (Proc *) objPtr->internalRep.twoPtrValue.ptr1; + procPtr->refCount--; + if (procPtr->refCount <= 0) { + TclProcCleanupProc(procPtr); + } +} + +static void +DupLocalVarName(srcPtr, dupPtr) + Tcl_Obj *srcPtr; + Tcl_Obj *dupPtr; +{ + register Proc *procPtr = (Proc *) srcPtr->internalRep.twoPtrValue.ptr1; + + dupPtr->internalRep.twoPtrValue.ptr1 = (VOID *) procPtr; + dupPtr->internalRep.twoPtrValue.ptr2 = srcPtr->internalRep.twoPtrValue.ptr2; + procPtr->refCount++; + dupPtr->typePtr = &tclLocalVarNameType; +} + +static void +UpdateLocalVarName(objPtr) + Tcl_Obj *objPtr; +{ + Proc *procPtr = (Proc *) objPtr->internalRep.twoPtrValue.ptr1; + unsigned int index = (unsigned int) objPtr->internalRep.twoPtrValue.ptr2; + CompiledLocal *localPtr = procPtr->firstLocalPtr; + unsigned int nameLen; + + if (localPtr == NULL) { + goto emptyName; + } + while (index--) { + localPtr = localPtr->nextPtr; + if (localPtr == NULL) { + goto emptyName; + } + } + + nameLen = (unsigned int) localPtr->nameLength; + objPtr->bytes = ckalloc(nameLen + 1); + memcpy(objPtr->bytes, localPtr->name, nameLen + 1); + objPtr->length = nameLen; + return; + + emptyName: + objPtr->bytes = ckalloc(1); + *(objPtr->bytes) = '\0'; + objPtr->length = 0; +} + +/* + * nsVarName - * - * Side effects: - * The tcl object might have its internal type and representation - * modified. + * INTERNALREP DEFINITION: + * twoPtrValue.ptr1: pointer to the namespace containing the + * reference. + * twoPtrValue.ptr2: pointer to the corresponding Var +*/ + +static void +FreeNsVarName(objPtr) + Tcl_Obj *objPtr; +{ + register Var *varPtr = (Var *) objPtr->internalRep.twoPtrValue.ptr2; + + varPtr->refCount--; + if (TclIsVarUndefined(varPtr) && (varPtr->refCount <= 0)) { + if (TclIsVarLink(varPtr)) { + Var *linkPtr = varPtr->value.linkPtr; + linkPtr->refCount--; + if (TclIsVarUndefined(linkPtr) && (linkPtr->refCount <= 0)) { + CleanupVar(linkPtr, (Var *) NULL); + } + } + CleanupVar(varPtr, NULL); + } +} + +static void +DupNsVarName(srcPtr, dupPtr) + Tcl_Obj *srcPtr; + Tcl_Obj *dupPtr; +{ + Namespace *nsPtr = (Namespace *) srcPtr->internalRep.twoPtrValue.ptr1; + register Var *varPtr = (Var *) srcPtr->internalRep.twoPtrValue.ptr2; + + dupPtr->internalRep.twoPtrValue.ptr1 = (VOID *) nsPtr; + dupPtr->internalRep.twoPtrValue.ptr2 = (VOID *) varPtr; + varPtr->refCount++; + dupPtr->typePtr = &tclNsVarNameType; +} + +/* + * parsedVarName - * - *---------------------------------------------------------------------- + * INTERNALREP DEFINITION: + * twoPtrValue.ptr1 = pointer to the array name Tcl_Obj + * (NULL if scalar) + * twoPtrValue.ptr2 = pointer to the element name string + * (owned by this Tcl_Obj), or NULL if + * it is a scalar variable */ -static ArraySearch * -ParseSearchId(interp, varPtr, varName, handleObj) - Tcl_Interp *interp; /* Interpreter containing variable. */ - CONST Var *varPtr; /* Array variable search is for. */ - CONST char *varName; /* Name of array variable that search is - * supposed to be for. */ - Tcl_Obj *handleObj; /* Object containing id of search. Must have - * form "search-num-var" where "num" is a - * decimal number and "var" is a variable - * name. */ +static void +FreeParsedVarName(objPtr) + Tcl_Obj *objPtr; { - register char *string; - register size_t offset; - int id; - ArraySearch *searchPtr; - - /* - * Parse the id. - */ - if (Tcl_ConvertToType(interp, handleObj, &tclArraySearchType) != TCL_OK) { - return NULL; - } - /* - * Cast is safe, since always came from an int in the first place. - */ - id = (int)(((char*)handleObj->internalRep.twoPtrValue.ptr1) - - ((char*)NULL)); - string = Tcl_GetString(handleObj); - offset = (((char*)handleObj->internalRep.twoPtrValue.ptr2) - - ((char*)NULL)); - /* - * This test cannot be placed inside the Tcl_Obj machinery, since - * it is dependent on the variable context. - */ - if (strcmp(string+offset, varName) != 0) { - Tcl_AppendResult(interp, "search identifier \"", string, - "\" isn't for variable \"", varName, "\"", (char *) NULL); - return NULL; + register Tcl_Obj *arrayPtr = + (Tcl_Obj *) objPtr->internalRep.twoPtrValue.ptr1; + register char *elem = (char *) objPtr->internalRep.twoPtrValue.ptr2; + + if (arrayPtr != NULL) { + TclDecrRefCount(arrayPtr); + ckfree(elem); } +} - /* - * Search through the list of active searches on the interpreter - * to see if the desired one exists. - * - * Note that we cannot store the searchPtr directly in the Tcl_Obj - * as that would run into trouble when DeleteSearches() was called - * so we must scan this list every time. - */ +static void +DupParsedVarName(srcPtr, dupPtr) + Tcl_Obj *srcPtr; + Tcl_Obj *dupPtr; +{ + register Tcl_Obj *arrayPtr = + (Tcl_Obj *) srcPtr->internalRep.twoPtrValue.ptr1; + register char *elem = (char *) srcPtr->internalRep.twoPtrValue.ptr2; + char *elemCopy; + unsigned int elemLen; - for (searchPtr = varPtr->searchPtr; searchPtr != NULL; - searchPtr = searchPtr->nextPtr) { - if (searchPtr->id == id) { - return searchPtr; - } + if (arrayPtr != NULL) { + Tcl_IncrRefCount(arrayPtr); } - Tcl_AppendResult(interp, "couldn't find search \"", string, "\"", - (char *) NULL); - return NULL; + elemLen = strlen(elem); + elemCopy = ckalloc(elemLen+1); + memcpy(elemCopy, elem, elemLen); + *(elemCopy + elemLen) = '\0'; + + dupPtr->internalRep.twoPtrValue.ptr1 = (VOID *) arrayPtr; + dupPtr->internalRep.twoPtrValue.ptr2 = (VOID *) elemCopy; + dupPtr->typePtr = &tclParsedVarNameType; } - -/* - *---------------------------------------------------------------------- - * - * DeleteSearches -- - * - * This procedure is called to free up all of the searches - * associated with an array variable. - * - * Results: - * None. - * - * Side effects: - * Memory is released to the storage allocator. - * - *---------------------------------------------------------------------- - */ static void -DeleteSearches(arrayVarPtr) - register Var *arrayVarPtr; /* Variable whose searches are - * to be deleted. */ +UpdateParsedVarName(objPtr) + Tcl_Obj *objPtr; { - ArraySearch *searchPtr; + Tcl_Obj *arrayPtr = (Tcl_Obj *) objPtr->internalRep.twoPtrValue.ptr1; + char *part2 = (char *) objPtr->internalRep.twoPtrValue.ptr2; + char *part1, *p; + int len1, len2, totalLen; - while (arrayVarPtr->searchPtr != NULL) { - searchPtr = arrayVarPtr->searchPtr; - arrayVarPtr->searchPtr = searchPtr->nextPtr; - ckfree((char *) searchPtr); + if (arrayPtr == NULL) { + /* + * This is a parsed scalar name: what is it + * doing here? + */ + panic("ERROR: scalar parsedVarName without a string rep.\n"); } + part1 = Tcl_GetStringFromObj(arrayPtr, &len1); + len2 = strlen(part2); + + totalLen = len1 + len2 + 2; + p = ckalloc((unsigned int) totalLen + 1); + objPtr->bytes = p; + objPtr->length = totalLen; + + memcpy(p, part1, (unsigned int) len1); + p += len1; + *p++ = '('; + memcpy(p, part2, (unsigned int) len2); + p += len2; + *p++ = ')'; + *p = '\0'; } /* + * ****************************************************** + * Special functions for indexed variables + * + * These functions are not used any longer; as they were + * present in the internal stubs table, their removal has + * not been deemed safe at this time. + * + */ + +/* *---------------------------------------------------------------------- * - * TclDeleteVars -- + * TclGetIndexedScalar -- * - * This procedure is called to recycle all the storage space - * associated with a table of variables. For this procedure - * to work correctly, it must not be possible for any of the - * variables in the table to be accessed from Tcl commands - * (e.g. from trace procedures). + * Return the Tcl object value of a local scalar variable in the active + * procedure, given its index in the procedure's array of compiler + * allocated local variables. * * Results: - * None. + * The return value points to the current object value of the variable + * given by localIndex. If the specified variable doesn't exist, or + * there is a clash in array usage, or an error occurs while executing + * variable traces, then NULL is returned and a message will be left in + * the interpreter's result if TCL_LEAVE_ERR_MSG is set in flags. * * Side effects: - * Variables are deleted and trace procedures are invoked, if - * any are declared. + * The ref count for the returned object is _not_ incremented to + * reflect the returned reference; if you want to keep a reference to + * the object you must increment its ref count yourself. * *---------------------------------------------------------------------- */ -void -TclDeleteVars(iPtr, tablePtr) - Interp *iPtr; /* Interpreter to which variables belong. */ - Tcl_HashTable *tablePtr; /* Hash table containing variables to - * delete. */ +Tcl_Obj * +TclGetIndexedScalar(interp, localIndex, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be looked up. */ + register int localIndex; /* Index of variable in procedure's array + * of local variables. */ + int flags; /* TCL_LEAVE_ERR_MSG if to leave an error + * message in interpreter's result on an error. + * Otherwise no error message is left. */ { - Tcl_Interp *interp = (Tcl_Interp *) iPtr; - Tcl_HashSearch search; - Tcl_HashEntry *hPtr; - register Var *varPtr; - Var *linkPtr; - int flags; - ActiveVarTrace *activePtr; - Tcl_Obj *objPtr; - Namespace *currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp); - - /* - * Determine what flags to pass to the trace callback procedures. - */ - - flags = TCL_TRACE_UNSETS; - if (tablePtr == &iPtr->globalNsPtr->varTable) { - flags |= (TCL_INTERP_DESTROYED | TCL_GLOBAL_ONLY); - } else if (tablePtr == &currNsPtr->varTable) { - flags |= TCL_NAMESPACE_ONLY; - } - - for (hPtr = Tcl_FirstHashEntry(tablePtr, &search); hPtr != NULL; - hPtr = Tcl_NextHashEntry(&search)) { - varPtr = (Var *) Tcl_GetHashValue(hPtr); - - /* - * For global/upvar variables referenced in procedures, decrement - * the reference count on the variable referred to, and free - * the referenced variable if it's no longer needed. Don't delete - * the hash entry for the other variable if it's in the same table - * as us: this will happen automatically later on. - */ - - if (TclIsVarLink(varPtr)) { - linkPtr = varPtr->value.linkPtr; - linkPtr->refCount--; - if ((linkPtr->refCount == 0) && TclIsVarUndefined(linkPtr) - && (linkPtr->tracePtr == NULL) - && (linkPtr->flags & VAR_IN_HASHTABLE)) { - if (linkPtr->hPtr == NULL) { - ckfree((char *) linkPtr); - } else if (linkPtr->hPtr->tablePtr != tablePtr) { - Tcl_DeleteHashEntry(linkPtr->hPtr); - ckfree((char *) linkPtr); - } - } - } + Interp *iPtr = (Interp *) interp; + CallFrame *varFramePtr = iPtr->varFramePtr; + /* Points to the procedure call frame whose + * variables are currently in use. Same as + * the current procedure's frame, if any, + * unless an "uplevel" is executing. */ + Var *compiledLocals = varFramePtr->compiledLocals; + register Var *varPtr; /* Points to the variable's in-frame Var + * structure. */ + char *varName; /* Name of the local variable. */ + CONST char *msg; - /* - * Invoke traces on the variable that is being deleted, then - * free up the variable's space (no need to free the hash entry - * here, unless we're dealing with a global variable: the - * hash entries will be deleted automatically when the whole - * table is deleted). Note that we give CallVarTraces the variable's - * fully-qualified name so that any called trace procedures can - * refer to these variables being deleted. - */ +#ifdef TCL_COMPILE_DEBUG + int localCt = varFramePtr->procPtr->numCompiledLocals; - if (varPtr->tracePtr != NULL) { - objPtr = Tcl_NewObj(); - Tcl_IncrRefCount(objPtr); /* until done with traces */ - Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr, objPtr); - CallVarTraces(iPtr, (Var *) NULL, varPtr, Tcl_GetString(objPtr), - NULL, flags, /* leaveErrMsg */ 0); - Tcl_DecrRefCount(objPtr); /* free no longer needed obj */ + if (compiledLocals == NULL) { + fprintf(stderr, "\nTclGetIndexedScalar: can't get "); + fprintf(stderr, "local %i in frame 0x%x, ", localIndex, + (unsigned int) varFramePtr); + fprintf(stderr, "no compiled locals\n"); + panic("TclGetIndexedScalar: no compiled locals in frame 0x%x", + (unsigned int) varFramePtr); + } + if ((localIndex < 0) || (localIndex >= localCt)) { + fprintf(stderr, "\nTclGetIndexedScalar: can't get "); + fprintf(stderr, "local %i in frame 0x%x " localIndex, + (unsigned int) varFramePtr); + fprintf(stderr, "with %i locals\n", localCt); + panic("TclGetIndexedScalar: bad local index %i in frame 0x%x", + localIndex, (unsigned int) varFramePtr); + } +#endif /* TCL_COMPILE_DEBUG */ + + varPtr = &(compiledLocals[localIndex]); + varName = varPtr->name; - while (varPtr->tracePtr != NULL) { - VarTrace *tracePtr = varPtr->tracePtr; - varPtr->tracePtr = tracePtr->nextPtr; - Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); - } - for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; - activePtr = activePtr->nextPtr) { - if (activePtr->varPtr == varPtr) { - activePtr->nextTracePtr = NULL; - } - } - } - - if (TclIsVarArray(varPtr)) { - DeleteArray(iPtr, Tcl_GetHashKey(tablePtr, hPtr), varPtr, - flags); - varPtr->value.tablePtr = NULL; - } - if (TclIsVarScalar(varPtr) && (varPtr->value.objPtr != NULL)) { - objPtr = varPtr->value.objPtr; - TclDecrRefCount(objPtr); - varPtr->value.objPtr = NULL; - } - varPtr->hPtr = NULL; - varPtr->tracePtr = NULL; - TclSetVarUndefined(varPtr); - TclSetVarScalar(varPtr); + /* + * If varPtr is a link variable, we have a reference to some variable + * that was created through an "upvar" or "global" command, or we have a + * reference to a variable in an enclosing namespace. Traverse through + * any links until we find the referenced variable. + */ + + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; + } - /* - * If the variable was a namespace variable, decrement its - * reference count. We are in the process of destroying its - * namespace so that namespace will no longer "refer" to the - * variable. - */ + /* + * Invoke any traces that have been set for the variable. + */ - if (varPtr->flags & VAR_NAMESPACE_VAR) { - varPtr->flags &= ~VAR_NAMESPACE_VAR; - varPtr->refCount--; + if (varPtr->tracePtr != NULL) { + if (TCL_ERROR == CallVarTraces(iPtr, /*arrayPtr*/ NULL, varPtr, varName, + NULL, TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { + return NULL; } + } - /* - * Recycle the variable's memory space if there aren't any upvar's - * pointing to it. If there are upvars to this variable, then the - * variable will get freed when the last upvar goes away. - */ + /* + * Make sure we're dealing with a scalar variable and not an array, and + * that the variable exists (isn't undefined). + */ - if (varPtr->refCount == 0) { - ckfree((char *) varPtr); /* this Var must be VAR_IN_HASHTABLE */ + if (!TclIsVarScalar(varPtr) || TclIsVarUndefined(varPtr)) { + if (flags & TCL_LEAVE_ERR_MSG) { + if (TclIsVarArray(varPtr)) { + msg = isArray; + } else { + msg = noSuchVar; + } + VarErrMsg(interp, varName, NULL, "read", msg); } + return NULL; } - Tcl_DeleteHashTable(tablePtr); + return varPtr->value.objPtr; } /* *---------------------------------------------------------------------- * - * TclDeleteCompiledLocalVars -- + * TclGetElementOfIndexedArray -- * - * This procedure is called to recycle storage space associated with - * the compiler-allocated array of local variables in a procedure call - * frame. This procedure resembles TclDeleteVars above except that each - * variable is stored in a call frame and not a hash table. For this - * procedure to work correctly, it must not be possible for any of the - * variable in the table to be accessed from Tcl commands (e.g. from - * trace procedures). + * Return the Tcl object value for an element in a local array + * variable. The element is named by the object elemPtr while the + * array is specified by its index in the active procedure's array + * of compiler allocated local variables. * * Results: - * None. + * The return value points to the current object value of the + * element. If the specified array or element doesn't exist, or there + * is a clash in array usage, or an error occurs while executing + * variable traces, then NULL is returned and a message will be left in + * the interpreter's result if TCL_LEAVE_ERR_MSG is set in flags. * * Side effects: - * Variables are deleted and trace procedures are invoked, if - * any are declared. + * The ref count for the returned object is _not_ incremented to + * reflect the returned reference; if you want to keep a reference to + * the object you must increment its ref count yourself. * *---------------------------------------------------------------------- */ -void -TclDeleteCompiledLocalVars(iPtr, framePtr) - Interp *iPtr; /* Interpreter to which variables belong. */ - CallFrame *framePtr; /* Procedure call frame containing - * compiler-assigned local variables to - * delete. */ +Tcl_Obj * +TclGetElementOfIndexedArray(interp, localIndex, elemPtr, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be looked up. */ + int localIndex; /* Index of array variable in procedure's + * array of local variables. */ + Tcl_Obj *elemPtr; /* Points to an object holding the name of + * an element to get in the array. */ + int flags; /* TCL_LEAVE_ERR_MSG if to leave an error + * message in interpreter's result on an error. + * Otherwise no error message is left. */ { - register Var *varPtr; - int flags; /* Flags passed to trace procedures. */ - Var *linkPtr; - ActiveVarTrace *activePtr; - int numLocals, i; + Interp *iPtr = (Interp *) interp; + CallFrame *varFramePtr = iPtr->varFramePtr; + /* Points to the procedure call frame whose + * variables are currently in use. Same as + * the current procedure's frame, if any, + * unless an "uplevel" is executing. */ + Var *compiledLocals = varFramePtr->compiledLocals; + Var *arrayPtr; /* Points to the array's in-frame Var + * structure. */ + char *arrayName; /* Name of the local array. */ + Tcl_HashEntry *hPtr; + Var *varPtr = NULL; /* Points to the element's Var structure + * that we return. Initialized to avoid + * compiler warning. */ + CONST char *elem, *msg; + int new; - flags = TCL_TRACE_UNSETS; - numLocals = framePtr->numCompiledLocals; - varPtr = framePtr->compiledLocals; - for (i = 0; i < numLocals; i++) { - /* - * For global/upvar variables referenced in procedures, decrement - * the reference count on the variable referred to, and free - * the referenced variable if it's no longer needed. Don't delete - * the hash entry for the other variable if it's in the same table - * as us: this will happen automatically later on. - */ +#ifdef TCL_COMPILE_DEBUG + Proc *procPtr = varFramePtr->procPtr; + int localCt = procPtr->numCompiledLocals; - if (TclIsVarLink(varPtr)) { - linkPtr = varPtr->value.linkPtr; - linkPtr->refCount--; - if ((linkPtr->refCount == 0) && TclIsVarUndefined(linkPtr) - && (linkPtr->tracePtr == NULL) - && (linkPtr->flags & VAR_IN_HASHTABLE)) { - if (linkPtr->hPtr == NULL) { - ckfree((char *) linkPtr); - } else { - Tcl_DeleteHashEntry(linkPtr->hPtr); - ckfree((char *) linkPtr); - } - } + if (compiledLocals == NULL) { + fprintf(stderr, "\nTclGetElementOfIndexedArray: can't get element "); + fprintf(stderr, "of local %i in frame 0x%x, " localIndex, + (unsigned int) varFramePtr); + fprintf(stderr, "no compiled locals\n"); + panic("TclGetIndexedScalar: no compiled locals in frame 0x%x", + (unsigned int) varFramePtr); + } + if ((localIndex < 0) || (localIndex >= localCt)) { + fprintf(stderr, "\nTclGetIndexedScalar: can't get element of " + "local %i in frame 0x%x with %i locals\n", localIndex, + (unsigned int) varFramePtr, localCt); + panic("TclGetElementOfIndexedArray: bad local index %i in frame 0x%x", + localIndex, (unsigned int) varFramePtr); + } +#endif /* TCL_COMPILE_DEBUG */ + + elem = TclGetString(elemPtr); + arrayPtr = &(compiledLocals[localIndex]); + arrayName = arrayPtr->name; + + /* + * If arrayPtr is a link variable, we have a reference to some variable + * that was created through an "upvar" or "global" command, or we have a + * reference to a variable in an enclosing namespace. Traverse through + * any links until we find the referenced variable. + */ + + while (TclIsVarLink(arrayPtr)) { + arrayPtr = arrayPtr->value.linkPtr; + } + + /* + * Make sure we're dealing with an array and that the array variable + * exists (isn't undefined). + */ + + if (!TclIsVarArray(arrayPtr) || TclIsVarUndefined(arrayPtr)) { + if (flags & TCL_LEAVE_ERR_MSG) { + VarErrMsg(interp, arrayName, elem, "read", noSuchVar); + } + goto errorReturn; + } + + /* + * Look up the element. Note that we must create the element (but leave + * it marked undefined) if it does not already exist. This allows a + * trace to create new array elements "on the fly" that did not exist + * before. A trace is always passed a variable for the array element. If + * the trace does not define the variable, it will be deleted below (at + * errorReturn) and an error returned. + */ + + hPtr = Tcl_CreateHashEntry(arrayPtr->value.tablePtr, elem, &new); + if (new) { + if (arrayPtr->searchPtr != NULL) { + DeleteSearches(arrayPtr); } + varPtr = NewVar(); + Tcl_SetHashValue(hPtr, varPtr); + varPtr->hPtr = hPtr; + varPtr->nsPtr = varFramePtr->nsPtr; + TclSetVarArrayElement(varPtr); + } else { + varPtr = (Var *) Tcl_GetHashValue(hPtr); + } - /* - * Invoke traces on the variable that is being deleted. Then delete - * the variable's trace records. - */ + /* + * Invoke any traces that have been set for the element variable. + */ - if (varPtr->tracePtr != NULL) { - CallVarTraces(iPtr, (Var *) NULL, varPtr, varPtr->name, NULL, - flags, /* leaveErrMsg */ 0); - while (varPtr->tracePtr != NULL) { - VarTrace *tracePtr = varPtr->tracePtr; - varPtr->tracePtr = tracePtr->nextPtr; - Tcl_EventuallyFree((ClientData) tracePtr, TCL_DYNAMIC); - } - for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; - activePtr = activePtr->nextPtr) { - if (activePtr->varPtr == varPtr) { - activePtr->nextTracePtr = NULL; - } - } + if ((varPtr->tracePtr != NULL) + || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { + if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, arrayName, elem, + TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { + goto errorReturn; } + } - /* - * Now if the variable is an array, delete its element hash table. - * Otherwise, if it's a scalar variable, decrement the ref count - * of its value. - */ - - if (TclIsVarArray(varPtr) && (varPtr->value.tablePtr != NULL)) { - DeleteArray(iPtr, varPtr->name, varPtr, flags); - } - if (TclIsVarScalar(varPtr) && (varPtr->value.objPtr != NULL)) { - TclDecrRefCount(varPtr->value.objPtr); - varPtr->value.objPtr = NULL; + /* + * Return the element if it's an existing scalar variable. + */ + + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) { + return varPtr->value.objPtr; + } + + if (flags & TCL_LEAVE_ERR_MSG) { + if (TclIsVarArray(varPtr)) { + msg = isArray; + } else { + msg = noSuchVar; } - varPtr->hPtr = NULL; - varPtr->tracePtr = NULL; - TclSetVarUndefined(varPtr); - TclSetVarScalar(varPtr); - varPtr++; + VarErrMsg(interp, arrayName, elem, "read", msg); + } + + /* + * An error. If the variable doesn't exist anymore and no-one's using + * it, then free up the relevant structures and hash table entries. + */ + + errorReturn: + if ((varPtr != NULL) && TclIsVarUndefined(varPtr)) { + CleanupVar(varPtr, NULL); /* the array is not in a hashtable */ } + return NULL; } /* *---------------------------------------------------------------------- * - * DeleteArray -- + * TclSetIndexedScalar -- * - * This procedure is called to free up everything in an array - * variable. It's the caller's responsibility to make sure - * that the array is no longer accessible before this procedure - * is called. + * Change the Tcl object value of a local scalar variable in the active + * procedure, given its compile-time allocated index in the procedure's + * array of local variables. * * Results: - * None. + * Returns a pointer to the Tcl_Obj holding the new value of the + * variable given by localIndex. If the specified variable doesn't + * exist, or there is a clash in array usage, or an error occurs while + * executing variable traces, then NULL is returned and a message will + * be left in the interpreter's result if flags has TCL_LEAVE_ERR_MSG. + * Note that the returned object may not be the same one referenced by + * newValuePtr; this is because variable traces may modify the + * variable's value. * * Side effects: - * All storage associated with varPtr's array elements is deleted - * (including the array's hash table). Deletion trace procedures for - * array elements are invoked, then deleted. Any pending traces for - * array elements are also deleted. + * The value of the given variable is set. The reference count is + * decremented for any old value of the variable and incremented for + * its new value. If as a result of a variable trace the new value for + * the variable is not the same one referenced by newValuePtr, then + * newValuePtr's ref count is left unchanged. The ref count for the + * returned object is _not_ incremented to reflect the returned + * reference; if you want to keep a reference to the object you must + * increment its ref count yourself. This procedure does not create + * new variables, but only sets those recognized at compile time. * *---------------------------------------------------------------------- */ -static void -DeleteArray(iPtr, arrayName, varPtr, flags) - Interp *iPtr; /* Interpreter containing array. */ - char *arrayName; /* Name of array (used for trace - * callbacks). */ - Var *varPtr; /* Pointer to variable structure. */ - int flags; /* Flags to pass to CallVarTraces: - * TCL_TRACE_UNSETS and sometimes - * TCL_INTERP_DESTROYED, - * TCL_NAMESPACE_ONLY, or - * TCL_GLOBAL_ONLY. */ +Tcl_Obj * +TclSetIndexedScalar(interp, localIndex, newValuePtr, flags) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be found. */ + int localIndex; /* Index of variable in procedure's array + * of local variables. */ + Tcl_Obj *newValuePtr; /* New value for variable. */ + int flags; /* Various flags that tell how to set value: + * any of TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT or TCL_LEAVE_ERR_MSG. */ { - Tcl_HashSearch search; - register Tcl_HashEntry *hPtr; - register Var *elPtr; - ActiveVarTrace *activePtr; - Tcl_Obj *objPtr; + Interp *iPtr = (Interp *) interp; + CallFrame *varFramePtr = iPtr->varFramePtr; + /* Points to the procedure call frame whose + * variables are currently in use. Same as + * the current procedure's frame, if any, + * unless an "uplevel" is executing. */ + Var *compiledLocals = varFramePtr->compiledLocals; + register Var *varPtr; /* Points to the variable's in-frame Var + * structure. */ + char *varName; /* Name of the local variable. */ + Tcl_Obj *oldValuePtr; + Tcl_Obj *resultPtr = NULL; - DeleteSearches(varPtr); - for (hPtr = Tcl_FirstHashEntry(varPtr->value.tablePtr, &search); - hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { - elPtr = (Var *) Tcl_GetHashValue(hPtr); - if (TclIsVarScalar(elPtr) && (elPtr->value.objPtr != NULL)) { - objPtr = elPtr->value.objPtr; - TclDecrRefCount(objPtr); - elPtr->value.objPtr = NULL; +#ifdef TCL_COMPILE_DEBUG + Proc *procPtr = varFramePtr->procPtr; + int localCt = procPtr->numCompiledLocals; + + if (compiledLocals == NULL) { + fprintf(stderr, "\nTclSetIndexedScalar: can't set "); + fprintf(stderr, "local %i in ", localIndex); + fprintf(stderr, "frame 0x%x, no compiled locals\n", + (unsigned int) varFramePtr); + panic("TclSetIndexedScalar: no compiled locals in frame 0x%x", + (unsigned int) varFramePtr); + } + if ((localIndex < 0) || (localIndex >= localCt)) { + fprintf(stderr, "\nTclSetIndexedScalar: can't set "); + fprintf(stderr, "local %i in " localIndex); + fprintf(stderr, "frame 0x%x with %i locals\n", + (unsigned int) varFramePtr, localCt); + panic("TclSetIndexedScalar: bad local index %i in frame 0x%x", + localIndex, (unsigned int) varFramePtr); + } +#endif /* TCL_COMPILE_DEBUG */ + + varPtr = &(compiledLocals[localIndex]); + varName = varPtr->name; + + /* + * If varPtr is a link variable, we have a reference to some variable + * that was created through an "upvar" or "global" command, or we have a + * reference to a variable in an enclosing namespace. Traverse through + * any links until we find the referenced variable. + */ + + while (TclIsVarLink(varPtr)) { + varPtr = varPtr->value.linkPtr; + } + + /* + * Invoke any read traces that have been set for the variable if it + * is requested; this is only done in the core when lappending. + */ + + if ((flags & TCL_TRACE_READS) && (varPtr->tracePtr != NULL)) { + if (TCL_ERROR == CallVarTraces(iPtr, /*arrayPtr*/ NULL, varPtr, varName, + NULL, TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { + return NULL; } - elPtr->hPtr = NULL; - if (elPtr->tracePtr != NULL) { - elPtr->flags &= ~VAR_TRACE_ACTIVE; - CallVarTraces(iPtr, (Var *) NULL, elPtr, arrayName, - Tcl_GetHashKey(varPtr->value.tablePtr, hPtr), flags, - /* leaveErrMsg */ 0); - while (elPtr->tracePtr != NULL) { - VarTrace *tracePtr = elPtr->tracePtr; - elPtr->tracePtr = tracePtr->nextPtr; - Tcl_EventuallyFree((ClientData) tracePtr,TCL_DYNAMIC); + } + + /* + * If the variable is in a hashtable and its hPtr field is NULL, then we + * may have an upvar to an array element where the array was deleted + * or an upvar to a namespace variable whose namespace was deleted. + * Generate an error (allowing the variable to be reset would screw up + * our storage allocation and is meaningless anyway). + */ + + if ((varPtr->flags & VAR_IN_HASHTABLE) && (varPtr->hPtr == NULL)) { + if (flags & TCL_LEAVE_ERR_MSG) { + if (TclIsVarArrayElement(varPtr)) { + VarErrMsg(interp, varName, NULL, "set", danglingElement); + } else { + VarErrMsg(interp, varName, NULL, "set", danglingVar); + } + } + return NULL; + } + + /* + * It's an error to try to set an array variable itself. + */ + + if (TclIsVarArray(varPtr) && !TclIsVarUndefined(varPtr)) { + if (flags & TCL_LEAVE_ERR_MSG) { + VarErrMsg(interp, varName, NULL, "set", isArray); + } + return NULL; + } + + /* + * Set the variable's new value and discard its old value. + */ + + oldValuePtr = varPtr->value.objPtr; + if (flags & TCL_APPEND_VALUE) { + if (TclIsVarUndefined(varPtr) && (oldValuePtr != NULL)) { + Tcl_DecrRefCount(oldValuePtr); /* discard old value */ + varPtr->value.objPtr = NULL; + oldValuePtr = NULL; + } + if (flags & TCL_LIST_ELEMENT) { /* append list element */ + if (oldValuePtr == NULL) { + TclNewObj(oldValuePtr); + varPtr->value.objPtr = oldValuePtr; + Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ + } else if (Tcl_IsShared(oldValuePtr)) { + varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); + Tcl_DecrRefCount(oldValuePtr); + oldValuePtr = varPtr->value.objPtr; + Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ } - for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL; - activePtr = activePtr->nextPtr) { - if (activePtr->varPtr == elPtr) { - activePtr->nextTracePtr = NULL; + if (Tcl_ListObjAppendElement(interp, oldValuePtr, + newValuePtr) != TCL_OK) { + return NULL; + } + } else { /* append string */ + /* + * We append newValuePtr's bytes but don't change its ref count. + */ + + if (oldValuePtr == NULL) { + varPtr->value.objPtr = newValuePtr; + Tcl_IncrRefCount(newValuePtr); + } else { + if (Tcl_IsShared(oldValuePtr)) { /* append to copy */ + varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); + TclDecrRefCount(oldValuePtr); + oldValuePtr = varPtr->value.objPtr; + Tcl_IncrRefCount(oldValuePtr); /* since var is ref */ } + Tcl_AppendObjToObj(oldValuePtr, newValuePtr); } } - TclSetVarUndefined(elPtr); - TclSetVarScalar(elPtr); - if (elPtr->refCount == 0) { - ckfree((char *) elPtr); /* element Vars are VAR_IN_HASHTABLE */ + } else if (newValuePtr != oldValuePtr) { /* set new value */ + /* + * In this case we are replacing the value, so we don't need to + * do more than swap the objects. + */ + + varPtr->value.objPtr = newValuePtr; + Tcl_IncrRefCount(newValuePtr); /* var is another ref to obj */ + if (oldValuePtr != NULL) { + TclDecrRefCount(oldValuePtr); /* discard old value */ } } - Tcl_DeleteHashTable(varPtr->value.tablePtr); - ckfree((char *) varPtr->value.tablePtr); + TclSetVarScalar(varPtr); + TclClearVarUndefined(varPtr); + + /* + * Invoke any write traces for the variable. + */ + + if (varPtr->tracePtr != NULL) { + if (TCL_ERROR == CallVarTraces(iPtr, /*arrayPtr*/ NULL, varPtr, varName, + NULL, TCL_TRACE_WRITES, (flags & TCL_LEAVE_ERR_MSG))) { + goto cleanup; + } + } + + /* + * Return the variable's value unless the variable was changed in some + * gross way by a trace (e.g. it was unset and then recreated as an + * array). If it was changed is a gross way, just return an empty string + * object. + */ + + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) { + return varPtr->value.objPtr; + } + + resultPtr = Tcl_NewObj(); + + /* + * If the variable doesn't exist anymore and no-one's using it, then + * free up the relevant structures and hash table entries. + */ + + cleanup: + if (TclIsVarUndefined(varPtr)) { + CleanupVar(varPtr, NULL); + } + return resultPtr; } /* *---------------------------------------------------------------------- * - * CleanupVar -- + * TclSetElementOfIndexedArray -- * - * This procedure is called when it looks like it may be OK to free up - * a variable's storage. If the variable is in a hashtable, its Var - * structure and hash table entry will be freed along with those of its - * containing array, if any. This procedure is called, for example, - * when a trace on a variable deletes a variable. + * Change the Tcl object value of an element in a local array + * variable. The element is named by the object elemPtr while the array + * is specified by its index in the active procedure's array of + * compiler allocated local variables. * * Results: - * None. + * Returns a pointer to the Tcl_Obj holding the new value of the + * element. If the specified array or element doesn't exist, or there + * is a clash in array usage, or an error occurs while executing + * variable traces, then NULL is returned and a message will be left in + * the interpreter's result if flags has TCL_LEAVE_ERR_MSG. Note that the + * returned object may not be the same one referenced by newValuePtr; + * this is because variable traces may modify the variable's value. * * Side effects: - * If the variable (or its containing array) really is dead and in a - * hashtable, then its Var structure, and possibly its hash table - * entry, is freed up. + * The value of the given array element is set. The reference count is + * decremented for any old value of the element and incremented for its + * new value. If as a result of a variable trace the new value for the + * element is not the same one referenced by newValuePtr, then + * newValuePtr's ref count is left unchanged. The ref count for the + * returned object is _not_ incremented to reflect the returned + * reference; if you want to keep a reference to the object you must + * increment its ref count yourself. This procedure will not create new + * array variables, but only sets elements of those arrays recognized + * at compile time. However, if the entry doesn't exist then a new + * variable is created. * *---------------------------------------------------------------------- */ -static void -CleanupVar(varPtr, arrayPtr) - Var *varPtr; /* Pointer to variable that may be a - * candidate for being expunged. */ - Var *arrayPtr; /* Array that contains the variable, or - * NULL if this variable isn't an array - * element. */ +Tcl_Obj * +TclSetElementOfIndexedArray(interp, localIndex, elemPtr, newValuePtr, flags) + Tcl_Interp *interp; /* Command interpreter in which the array is + * to be found. */ + int localIndex; /* Index of array variable in procedure's + * array of local variables. */ + Tcl_Obj *elemPtr; /* Points to an object holding the name of + * an element to set in the array. */ + Tcl_Obj *newValuePtr; /* New value for variable. */ + int flags; /* Various flags that tell how to set value: + * any of TCL_APPEND_VALUE, + * TCL_LIST_ELEMENT or TCL_LEAVE_ERR_MSG. */ { - if (TclIsVarUndefined(varPtr) && (varPtr->refCount == 0) - && (varPtr->tracePtr == NULL) - && (varPtr->flags & VAR_IN_HASHTABLE)) { - if (varPtr->hPtr != NULL) { - Tcl_DeleteHashEntry(varPtr->hPtr); - } - ckfree((char *) varPtr); + Interp *iPtr = (Interp *) interp; + CallFrame *varFramePtr = iPtr->varFramePtr; + /* Points to the procedure call frame whose + * variables are currently in use. Same as + * the current procedure's frame, if any, + * unless an "uplevel" is executing. */ + Var *compiledLocals = varFramePtr->compiledLocals; + Var *arrayPtr; /* Points to the array's in-frame Var + * structure. */ + char *arrayName; /* Name of the local array. */ + char *elem; + Tcl_HashEntry *hPtr; + Var *varPtr = NULL; /* Points to the element's Var structure + * that we return. */ + Tcl_Obj *resultPtr = NULL; + Tcl_Obj *oldValuePtr; + int new; + +#ifdef TCL_COMPILE_DEBUG + Proc *procPtr = varFramePtr->procPtr; + int localCt = procPtr->numCompiledLocals; + + if (compiledLocals == NULL) { + fprintf(stderr, "\nTclSetElementOfIndexedArray: can't set element "); + fprintf(stderr, "of local %i in frame 0x%x, ", localIndex, + (unsigned int) varFramePtr); + fprintf(stderr, "no compiled locals\n"); + panic("TclSetIndexedScalar: no compiled locals in frame 0x%x", + (unsigned int) varFramePtr); } - if (arrayPtr != NULL) { - if (TclIsVarUndefined(arrayPtr) && (arrayPtr->refCount == 0) - && (arrayPtr->tracePtr == NULL) - && (arrayPtr->flags & VAR_IN_HASHTABLE)) { - if (arrayPtr->hPtr != NULL) { - Tcl_DeleteHashEntry(arrayPtr->hPtr); + if ((localIndex < 0) || (localIndex >= localCt)) { + fprintf(stderr, "\nTclSetIndexedScalar: can't set element of "); + fprintf(stderr, "local %i in frame 0x%x ", localIndex, + (unsigned int) varFramePtr); + fprintf(stderr, "with %i locals\n", localCt); + panic("TclSetElementOfIndexedArray: bad local index %i in frame 0x%x", + localIndex, (unsigned int) varFramePtr); + } +#endif /* TCL_COMPILE_DEBUG */ + + elem = TclGetString(elemPtr); + arrayPtr = &(compiledLocals[localIndex]); + arrayName = arrayPtr->name; + + /* + * If arrayPtr is a link variable, we have a reference to some variable + * that was created through an "upvar" or "global" command, or we have a + * reference to a variable in an enclosing namespace. Traverse through + * any links until we find the referenced variable. + */ + + while (TclIsVarLink(arrayPtr)) { + arrayPtr = arrayPtr->value.linkPtr; + } + + /* + * If the variable is in a hashtable and its hPtr field is NULL, then we + * may have an upvar to an array element where the array was deleted + * or an upvar to a namespace variable whose namespace was deleted. + * Generate an error (allowing the variable to be reset would screw up + * our storage allocation and is meaningless anyway). + */ + + if ((arrayPtr->flags & VAR_IN_HASHTABLE) && (arrayPtr->hPtr == NULL)) { + if (flags & TCL_LEAVE_ERR_MSG) { + if (TclIsVarArrayElement(arrayPtr)) { + VarErrMsg(interp, arrayName, elem, "set", danglingElement); + } else { + VarErrMsg(interp, arrayName, elem, "set", danglingVar); } - ckfree((char *) arrayPtr); } + goto errorReturn; } -} -/* - *---------------------------------------------------------------------- - * - * VarErrMsg -- - * - * Generate a reasonable error message describing why a variable - * operation failed. - * - * Results: - * None. - * - * Side effects: - * The interp's result is set to hold a message identifying the - * variable given by part1 and part2 and describing why the - * variable operation failed. - * - *---------------------------------------------------------------------- - */ -static void -VarErrMsg(interp, part1, part2, operation, reason) - Tcl_Interp *interp; /* Interpreter in which to record message. */ - CONST char *part1; - CONST char *part2; /* Variable's two-part name. */ - CONST char *operation; /* String describing operation that failed, - * e.g. "read", "set", or "unset". */ - CONST char *reason; /* String describing why operation failed. */ -{ - Tcl_ResetResult(interp); - Tcl_AppendResult(interp, "can't ", operation, " \"", part1, - (char *) NULL); - if (part2 != NULL) { - Tcl_AppendResult(interp, "(", part2, ")", (char *) NULL); + /* + * Make sure we're dealing with an array. + */ + + if (TclIsVarUndefined(arrayPtr) && !TclIsVarArrayElement(arrayPtr)) { + TclSetVarArray(arrayPtr); + arrayPtr->value.tablePtr = + (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable)); + Tcl_InitHashTable(arrayPtr->value.tablePtr, TCL_STRING_KEYS); + TclClearVarUndefined(arrayPtr); + } else if (!TclIsVarArray(arrayPtr)) { + if (flags & TCL_LEAVE_ERR_MSG) { + VarErrMsg(interp, arrayName, elem, "set", needArray); + } + goto errorReturn; + } + + /* + * Look up the element. + */ + + hPtr = Tcl_CreateHashEntry(arrayPtr->value.tablePtr, elem, &new); + if (new) { + if (arrayPtr->searchPtr != NULL) { + DeleteSearches(arrayPtr); + } + varPtr = NewVar(); + Tcl_SetHashValue(hPtr, varPtr); + varPtr->hPtr = hPtr; + varPtr->nsPtr = varFramePtr->nsPtr; + TclSetVarArrayElement(varPtr); + } + varPtr = (Var *) Tcl_GetHashValue(hPtr); + + /* + * It's an error to try to set an array variable itself. + */ + + if (TclIsVarArray(varPtr)) { + if (flags & TCL_LEAVE_ERR_MSG) { + VarErrMsg(interp, arrayName, elem, "set", isArray); + } + goto errorReturn; } - Tcl_AppendResult(interp, "\": ", reason, (char *) NULL); -} - -/* - *---------------------------------------------------------------------- - * - * TclTraceVarExists -- - * - * This is called from info exists. We need to trigger read - * and/or array traces because they may end up creating a - * variable that doesn't currently exist. - * - * Results: - * A pointer to the Var structure, or NULL. - * - * Side effects: - * May fill in error messages in the interp. - * - *---------------------------------------------------------------------- - */ -Var * -TclVarTraceExists(interp, varName) - Tcl_Interp *interp; /* The interpreter */ - char *varName; /* The variable name */ -{ - Var *varPtr; - Var *arrayPtr; + /* + * Invoke any read traces that have been set for the variable if it + * is requested; this is only done in the core when lappending. + */ + + if ((flags & TCL_TRACE_READS) && ((varPtr->tracePtr != NULL) + || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL)))) { + if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, arrayName, elem, + TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG))) { + goto errorReturn; + } + } /* - * The choice of "create" flag values is delicate here, and - * matches the semantics of GetVar. Things are still not perfect, - * however, because if you do "info exists x" you get a varPtr - * and therefore trigger traces. However, if you do - * "info exists x(i)", then you only get a varPtr if x is already - * known to be an array. Otherwise you get NULL, and no trace - * is triggered. This matches Tcl 7.6 semantics. + * Set the variable's new value and discard the old one. */ - varPtr = TclLookupVar(interp, varName, (char *) NULL, - 0, "access", /*createPart1*/ 0, /*createPart2*/ 1, &arrayPtr); + oldValuePtr = varPtr->value.objPtr; + if (flags & TCL_APPEND_VALUE) { + if (TclIsVarUndefined(varPtr) && (oldValuePtr != NULL)) { + Tcl_DecrRefCount(oldValuePtr); /* discard old value */ + varPtr->value.objPtr = NULL; + oldValuePtr = NULL; + } + if (flags & TCL_LIST_ELEMENT) { /* append list element */ + if (oldValuePtr == NULL) { + TclNewObj(oldValuePtr); + varPtr->value.objPtr = oldValuePtr; + Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ + } else if (Tcl_IsShared(oldValuePtr)) { + varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); + Tcl_DecrRefCount(oldValuePtr); + oldValuePtr = varPtr->value.objPtr; + Tcl_IncrRefCount(oldValuePtr); /* since var is referenced */ + } + if (Tcl_ListObjAppendElement(interp, oldValuePtr, + newValuePtr) != TCL_OK) { + return NULL; + } + } else { /* append string */ + /* + * We append newValuePtr's bytes but don't change its ref count. + */ - if (varPtr == NULL) { - return NULL; + if (oldValuePtr == NULL) { + varPtr->value.objPtr = newValuePtr; + Tcl_IncrRefCount(newValuePtr); + } else { + if (Tcl_IsShared(oldValuePtr)) { /* append to copy */ + varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr); + TclDecrRefCount(oldValuePtr); + oldValuePtr = varPtr->value.objPtr; + Tcl_IncrRefCount(oldValuePtr); /* since var is ref */ + } + Tcl_AppendObjToObj(oldValuePtr, newValuePtr); + } + } + } else if (newValuePtr != oldValuePtr) { /* set new value */ + /* + * In this case we are replacing the value, so we don't need to + * do more than swap the objects. + */ + + varPtr->value.objPtr = newValuePtr; + Tcl_IncrRefCount(newValuePtr); /* var is another ref to obj */ + if (oldValuePtr != NULL) { + TclDecrRefCount(oldValuePtr); /* discard old value */ + } } + TclSetVarScalar(varPtr); + TclClearVarUndefined(varPtr); + + /* + * Invoke any write traces for the element variable. + */ if ((varPtr->tracePtr != NULL) || ((arrayPtr != NULL) && (arrayPtr->tracePtr != NULL))) { - CallVarTraces((Interp *)interp, arrayPtr, varPtr, varName, NULL, - TCL_TRACE_READS, /* leaveErrMsg */ 0); + if (TCL_ERROR == CallVarTraces(iPtr, arrayPtr, varPtr, arrayName, elem, + TCL_TRACE_WRITES, (flags & TCL_LEAVE_ERR_MSG))) { + goto errorReturn; + } } /* - * If the variable doesn't exist anymore and no-one's using - * it, then free up the relevant structures and hash table entries. + * Return the element's value unless it was changed in some gross way by + * a trace (e.g. it was unset and then recreated as an array). If it was + * changed is a gross way, just return an empty string object. */ - if (TclIsVarUndefined(varPtr)) { - CleanupVar(varPtr, arrayPtr); - return NULL; + if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) { + return varPtr->value.objPtr; } + + resultPtr = Tcl_NewObj(); - return varPtr; + /* + * An error. If the variable doesn't exist anymore and no-one's using + * it, then free up the relevant structures and hash table entries. + */ + + errorReturn: + if ((varPtr != NULL) && TclIsVarUndefined(varPtr)) { + CleanupVar(varPtr, NULL); /* note: array isn't in hashtable */ + } + return resultPtr; } /* *---------------------------------------------------------------------- * - * Internal functions for variable name object types -- + * TclIncrIndexedScalar -- + * + * Increments the Tcl object value of a local scalar variable in the + * active procedure, given its compile-time allocated index in the + * procedure's array of local variables. + * + * Results: + * Returns a pointer to the Tcl_Obj holding the new value of the + * variable given by localIndex. If the specified variable doesn't + * exist, or there is a clash in array usage, or an error occurs while + * executing variable traces, then NULL is returned and a message will + * be left in the interpreter's result. + * + * Side effects: + * The value of the given variable is incremented by the specified + * amount. The ref count for the returned object is _not_ incremented + * to reflect the returned reference; if you want to keep a reference + * to the object you must increment its ref count yourself. * *---------------------------------------------------------------------- */ -/* - * localVarName - - * - * INTERNALREP DEFINITION: - * twoPtrValue.ptr1 = pointer to the corresponding Proc - * twoPtrValue.ptr2 = index into locals table -*/ - -static void -FreeLocalVarName(objPtr) - Tcl_Obj *objPtr; -{ - register Proc *procPtr = (Proc *) objPtr->internalRep.twoPtrValue.ptr1; - procPtr->refCount--; - if (procPtr->refCount <= 0) { - TclProcCleanupProc(procPtr); - } -} - -static void -DupLocalVarName(srcPtr, dupPtr) - Tcl_Obj *srcPtr; - Tcl_Obj *dupPtr; -{ - register Proc *procPtr = (Proc *) srcPtr->internalRep.twoPtrValue.ptr1; - - dupPtr->internalRep.twoPtrValue.ptr1 = (VOID *) procPtr; - dupPtr->internalRep.twoPtrValue.ptr2 = srcPtr->internalRep.twoPtrValue.ptr2; - procPtr->refCount++; - dupPtr->typePtr = &tclLocalVarNameType; -} - -static void -UpdateLocalVarName(objPtr) - Tcl_Obj *objPtr; +Tcl_Obj * +TclIncrIndexedScalar(interp, localIndex, incrAmount) + Tcl_Interp *interp; /* Command interpreter in which variable is + * to be found. */ + int localIndex; /* Index of variable in procedure's array + * of local variables. */ + long incrAmount; /* Amount to be added to variable. */ { - Proc *procPtr = (Proc *) objPtr->internalRep.twoPtrValue.ptr1; - unsigned int index = (unsigned int) objPtr->internalRep.twoPtrValue.ptr2; - CompiledLocal *localPtr = procPtr->firstLocalPtr; - unsigned int nameLen; - - if (localPtr == NULL) { - goto emptyName; - } - while (index--) { - localPtr = localPtr->nextPtr; - if (localPtr == NULL) { - goto emptyName; - } - } - - nameLen = (unsigned int) localPtr->nameLength; - objPtr->bytes = ckalloc(nameLen + 1); - memcpy(objPtr->bytes, localPtr->name, nameLen + 1); - objPtr->length = nameLen; - return; - - emptyName: - objPtr->bytes = ckalloc(1); - *(objPtr->bytes) = '\0'; - objPtr->length = 0; -} + register Tcl_Obj *varValuePtr; + int createdNewObj; /* Set 1 if var's value object is shared + * so we must increment a copy (i.e. copy + * on write). */ + long i; -/* - * nsVarName - - * - * INTERNALREP DEFINITION: - * twoPtrValue.ptr1: pointer to the namespace containing the - * reference. - * twoPtrValue.ptr2: pointer to the corresponding Var -*/ + varValuePtr = TclGetIndexedScalar(interp, localIndex, TCL_LEAVE_ERR_MSG); + if (varValuePtr == NULL) { + Tcl_AddObjErrorInfo(interp, + "\n (reading value of variable to increment)", -1); + return NULL; + } -static void -FreeNsVarName(objPtr) - Tcl_Obj *objPtr; -{ - register Var *varPtr = (Var *) objPtr->internalRep.twoPtrValue.ptr2; + /* + * Reach into the object's representation to extract and increment the + * variable's value. If the object is unshared we can modify it + * directly, otherwise we must create a new copy to modify: this is + * "copy on write". Then free the variable's old string representation, + * if any, since it will no longer be valid. + */ - varPtr->refCount--; - if (TclIsVarUndefined(varPtr) && (varPtr->refCount <= 0)) { - if (TclIsVarLink(varPtr)) { - Var *linkPtr = varPtr->value.linkPtr; - linkPtr->refCount--; - if (TclIsVarUndefined(linkPtr) && (linkPtr->refCount <= 0)) { - CleanupVar(linkPtr, (Var *) NULL); + createdNewObj = 0; + if (Tcl_IsShared(varValuePtr)) { + createdNewObj = 1; + varValuePtr = Tcl_DuplicateObj(varValuePtr); + } +#ifdef TCL_WIDE_INT_IS_LONG + if (Tcl_GetLongFromObj(interp, varValuePtr, &i) != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ + } + return NULL; + } + Tcl_SetLongObj(varValuePtr, (i + incrAmount)); +#else + if (varValuePtr->typePtr == &tclWideIntType) { + Tcl_WideInt wide = varValuePtr->internalRep.wideValue; + Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); + } else if (varValuePtr->typePtr == &tclIntType) { + i = varValuePtr->internalRep.longValue; + Tcl_SetIntObj(varValuePtr, i + incrAmount); + } else { + /* + * Not an integer or wide internal-rep... + */ + Tcl_WideInt wide; + if (Tcl_GetWideIntFromObj(interp, varValuePtr, &wide) != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ } + return NULL; + } + if (wide <= Tcl_LongAsWide(LONG_MAX) + && wide >= Tcl_LongAsWide(LONG_MIN)) { + Tcl_SetLongObj(varValuePtr, Tcl_WideAsLong(wide) + incrAmount); + } else { + Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); } - CleanupVar(varPtr, NULL); } -} - -static void -DupNsVarName(srcPtr, dupPtr) - Tcl_Obj *srcPtr; - Tcl_Obj *dupPtr; -{ - Namespace *nsPtr = (Namespace *) srcPtr->internalRep.twoPtrValue.ptr1; - register Var *varPtr = (Var *) srcPtr->internalRep.twoPtrValue.ptr2; +#endif - dupPtr->internalRep.twoPtrValue.ptr1 = (VOID *) nsPtr; - dupPtr->internalRep.twoPtrValue.ptr2 = (VOID *) varPtr; - varPtr->refCount++; - dupPtr->typePtr = &tclNsVarNameType; + /* + * Store the variable's new value and run any write traces. + */ + + return TclSetIndexedScalar(interp, localIndex, varValuePtr, + TCL_LEAVE_ERR_MSG); } - -/* - * parsedVarName - + +/* + *---------------------------------------------------------------------- * - * INTERNALREP DEFINITION: - * twoPtrValue.ptr1 = pointer to the array name Tcl_Obj - * (NULL if scalar) - * twoPtrValue.ptr2 = pointer to the element name string - * (owned by this Tcl_Obj), or NULL if - * it is a scalar variable + * TclIncrElementOfIndexedArray -- + * + * Increments the Tcl object value of an element in a local array + * variable. The element is named by the object elemPtr while the array + * is specified by its index in the active procedure's array of + * compiler allocated local variables. + * + * Results: + * Returns a pointer to the Tcl_Obj holding the new value of the + * element. If the specified array or element doesn't exist, or there + * is a clash in array usage, or an error occurs while executing + * variable traces, then NULL is returned and a message will be left in + * the interpreter's result. + * + * Side effects: + * The value of the given array element is incremented by the specified + * amount. The ref count for the returned object is _not_ incremented + * to reflect the returned reference; if you want to keep a reference + * to the object you must increment its ref count yourself. If the + * entry doesn't exist then a new variable is created. + * + *---------------------------------------------------------------------- */ -static void -FreeParsedVarName(objPtr) - Tcl_Obj *objPtr; -{ - register Tcl_Obj *arrayPtr = - (Tcl_Obj *) objPtr->internalRep.twoPtrValue.ptr1; - register char *elem = (char *) objPtr->internalRep.twoPtrValue.ptr2; - - if (arrayPtr != NULL) { - TclDecrRefCount(arrayPtr); - ckfree(elem); - } -} - -static void -DupParsedVarName(srcPtr, dupPtr) - Tcl_Obj *srcPtr; - Tcl_Obj *dupPtr; +Tcl_Obj * +TclIncrElementOfIndexedArray(interp, localIndex, elemPtr, incrAmount) + Tcl_Interp *interp; /* Command interpreter in which the array is + * to be found. */ + int localIndex; /* Index of array variable in procedure's + * array of local variables. */ + Tcl_Obj *elemPtr; /* Points to an object holding the name of + * an element to increment in the array. */ + long incrAmount; /* Amount to be added to variable. */ { - register Tcl_Obj *arrayPtr = - (Tcl_Obj *) srcPtr->internalRep.twoPtrValue.ptr1; - register char *elem = (char *) srcPtr->internalRep.twoPtrValue.ptr2; - char *elemCopy; - unsigned int elemLen; + register Tcl_Obj *varValuePtr; + int createdNewObj; /* Set 1 if var's value object is shared + * so we must increment a copy (i.e. copy + * on write). */ + long i; - if (arrayPtr != NULL) { - Tcl_IncrRefCount(arrayPtr); + varValuePtr = TclGetElementOfIndexedArray(interp, localIndex, elemPtr, + TCL_LEAVE_ERR_MSG); + if (varValuePtr == NULL) { + Tcl_AddObjErrorInfo(interp, + "\n (reading value of variable to increment)", -1); + return NULL; } - elemLen = strlen(elem); - elemCopy = ckalloc(elemLen+1); - memcpy(elemCopy, elem, elemLen); - *(elemCopy + elemLen) = '\0'; - dupPtr->internalRep.twoPtrValue.ptr1 = (VOID *) arrayPtr; - dupPtr->internalRep.twoPtrValue.ptr2 = (VOID *) elemCopy; - dupPtr->typePtr = &tclParsedVarNameType; -} - -static void -UpdateParsedVarName(objPtr) - Tcl_Obj *objPtr; -{ - Tcl_Obj *arrayPtr = (Tcl_Obj *) objPtr->internalRep.twoPtrValue.ptr1; - char *part2 = (char *) objPtr->internalRep.twoPtrValue.ptr2; - char *part1, *p; - int len1, len2, totalLen; + /* + * Reach into the object's representation to extract and increment the + * variable's value. If the object is unshared we can modify it + * directly, otherwise we must create a new copy to modify: this is + * "copy on write". Then free the variable's old string representation, + * if any, since it will no longer be valid. + */ - if (arrayPtr == NULL) { + createdNewObj = 0; + if (Tcl_IsShared(varValuePtr)) { + createdNewObj = 1; + varValuePtr = Tcl_DuplicateObj(varValuePtr); + } +#ifdef TCL_WIDE_INT_IS_LONG + if (Tcl_GetLongFromObj(interp, varValuePtr, &i) != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ + } + return NULL; + } + Tcl_SetLongObj(varValuePtr, (i + incrAmount)); +#else + if (varValuePtr->typePtr == &tclWideIntType) { + Tcl_WideInt wide = varValuePtr->internalRep.wideValue; + Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); + } else if (varValuePtr->typePtr == &tclIntType) { + i = varValuePtr->internalRep.longValue; + Tcl_SetIntObj(varValuePtr, i + incrAmount); + } else { /* - * This is a parsed scalar name: what is it - * doing here? + * Not an integer or wide internal-rep... */ - panic("ERROR: scalar parsedVarName without a string rep.\n"); + Tcl_WideInt wide; + if (Tcl_GetWideIntFromObj(interp, varValuePtr, &wide) != TCL_OK) { + if (createdNewObj) { + Tcl_DecrRefCount(varValuePtr); /* free unneeded copy */ + } + return NULL; + } + if (wide <= Tcl_LongAsWide(LONG_MAX) + && wide >= Tcl_LongAsWide(LONG_MIN)) { + Tcl_SetLongObj(varValuePtr, Tcl_WideAsLong(wide) + incrAmount); + } else { + Tcl_SetWideIntObj(varValuePtr, wide + Tcl_LongAsWide(incrAmount)); + } } - part1 = Tcl_GetStringFromObj(arrayPtr, &len1); - len2 = strlen(part2); - - totalLen = len1 + len2 + 2; - p = ckalloc((unsigned int) totalLen + 1); - objPtr->bytes = p; - objPtr->length = totalLen; +#endif - memcpy(p, part1, (unsigned int) len1); - p += len1; - *p++ = '('; - memcpy(p, part2, (unsigned int) len2); - p += len2; - *p++ = ')'; - *p = '\0'; + /* + * Store the variable's new value and run any write traces. + */ + + return TclSetElementOfIndexedArray(interp, localIndex, elemPtr, + varValuePtr, TCL_LEAVE_ERR_MSG); } -- cgit v0.12