Skip to content
Tcl Source Code Artifact [f5cb0df4ca]
Login

Artifact [f5cb0df4ca]

Artifact f5cb0df4ca7ed74c4b9fb869782dd29af671981bfdc81cc0c0d0e069d169d13e:


From 79e06ae89bbd3973b0384c82876a9fbf5af800f9 Mon Sep 17 00:00:00 2001
From: Florent Merlet <[email protected]>
Date: Thu, 29 Oct 2026 10:52:00 +0100
Subject: [PATCH 1/7] TIP 759 (1/7): expression substitution [(expr)]

In a word, "[(" starts an expression substitution: the expression runs
from that "(" to the ")" that balances it, directly followed by "]"
(")]" is one symbol). Its value replaces the substitution, as
[expr {...}] would. A command that is one expression substitution,
"[(...)]" alone, has the value of the expression as result (it is not
a command name).

- ParseTokens: TCL_TOKEN_SUB_EXPR token covering [(...)]; the end is
  found by the expression parser (TclParseExprSubst), so that strings,
  braces and nested substitutions are skipped correctly. The nesting
  depth is limited (interp recursionlimit).
- ParseExpr: [(...)] is also an operand of an expression.
- TclSubstTokens, TclCompileTokens (TclCompileSubExpr), [subst]
  compiler: evaluate/compile the text between the brackets as an
  expression.
- TclIsExprCommand: CompileCommandTokens and TclEvalEx take the value of
  a command "[(...)]" as its result.
- subst: new options -expr and -noexpr (TCL_SUBST_EXPR, in
  TCL_SUBST_ALL).
- Tests: exprSubst.test; subst.test messages. Docs: Tcl.n, expr.n,
  subst.n.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MrNWAEyXLqekovNBvbMZ4z
---
 doc/Tcl.n               | 177 +++++++++++++++++++++--
 doc/expr.n              |  18 +++
 doc/subst.n             |  23 +--
 generic/tcl.h           |   3 +-
 generic/tclBasic.c      |  15 +-
 generic/tclCmdMZ.c      |  10 +-
 generic/tclCompCmdsSZ.c |   7 +-
 generic/tclCompExpr.c   | 194 ++++++++++++++++++++++++-
 generic/tclCompile.c    |  67 +++++++++
 generic/tclInt.h        |  18 +++
 generic/tclParse.c      |  56 +++++++-
 tests/exprSubst.test    | 306 ++++++++++++++++++++++++++++++++++++++++
 tests/subst.test        |  10 +-
 13 files changed, 861 insertions(+), 43 deletions(-)
 create mode 100644 tests/exprSubst.test

diff --git a/doc/Tcl.n b/doc/Tcl.n
index df4472a..cbca7af 100644
--- a/doc/Tcl.n
+++ b/doc/Tcl.n
@@ -17,13 +17,39 @@ Summary of Tcl language syntax.
 .SS "SYNTAX"
 .PP
 The following rules define the syntax and semantics of the Tcl language:
-.IP "[1] \fBCommands.\fR"
-A Tcl script is a string containing one or more commands.
+.IP "[1] \fBScripts.\fR"
+A Tcl script is a string of one of two kinds: a \fIcommand script\fR,
+made of one or more commands, or an \fIexpression script\fR, made of
+one expression.
+.RS
+.TP 5
+\fBCommand scripts.\fR
+A command script contains one or more commands.
 Semi-colons and newlines are command separators unless quoted as
 described below.
 Close brackets are command terminators during command substitution
 (see below) unless quoted.
+.TP 5
+\fBExpression scripts.\fR
+.VS TIP759
+The script of an expression substitution (rule [7]), which begins with
+an open parenthesis
+.PQ ( "" ,
+is an expression script: the whole script, parentheses included, is one
+expression, as described in the \fBexpr\fR manual page. Semi-colons and
+newlines inside it are not command separators.
+During expression substitution (see below), the expression ends at the
+first close parenthesis that is immediately followed by a close bracket
+and leaves the parentheses of the expression balanced:
+.QW )]
+is one symbol.
+.VE TIP759
+.RE
 .IP "[2] \fBEvaluation.\fR"
+How a script is evaluated depends on its kind.
+.RS
+.TP 5
+\fBEvaluation of a command.\fR
 A command is evaluated in two steps.
 First, the Tcl interpreter breaks the command into \fIwords\fR
 and performs substitutions as described below.
@@ -36,18 +62,63 @@ The routine is free to interpret each of its words
 in any way it likes, such as an integer, variable name, list,
 or Tcl script.
 Different commands interpret their words differently.
+.VS TIP759
+There is one exception: a command made of a single word that is a
+single expression substitution, such as
+.QW "[( $x * 3 )]"
+alone on a line, is evaluated as the expression; its value is the
+result of the command and is not used as a command name.
+.VE TIP759
+.TP 5
+\fBEvaluation of an expression.\fR
+.VS TIP759
+An expression is evaluated as by the \fBexpr\fR command, in two steps.
+First, it is broken into \fIoperands\fR and operators (see rule [3]);
+the precedence of the operators, given in the \fBexpr\fR manual page,
+and parentheses determine the order in which the operators apply.
+Secondly, each operator is applied to the values of its operands.
+Substitutions in an operand are performed when that operand is
+evaluated, not before (see rule [11]).
+No routine is located: the value of the expression is the result.
+.VE TIP759
+.RE
 .IP "[3] \fBWords.\fR"
+How a script is divided into words depends on its kind (rule [1]).
+.RS
+.TP 5
+\fBWords of a command.\fR
 Words of a command are separated by white space (except for
 newlines, which are command separators).
+.TP 5
+\fBOperands of an expression.\fR
+.VS TIP759
+An expression is a sequence of operands and operators, as described
+in the \fBexpr\fR manual page; its operands play the role of words.
+Unlike in a command, white space, including newlines, does not
+separate operands: it is ignored, except that it ends a number or a
+name. An operand ends at the first character that cannot continue it,
+such as white space, an operator, a comma or a parenthesis.
+Two operands must be separated by an operator, or by a comma between
+the arguments of a function; otherwise the expression is an error, as
+in \fB1 2\fR or \fB\N'34'a\N'34'\N'34'b\N'34'\fR, whereas
+\fB\N'34'a\N'34'eq\N'34'a\N'34'\fR is valid.
+An operand is a number, a boolean value, a quoted word (rule [4]),
+a braced word (rule [6]), a substitution (rules [7] to [9]) or a function call.
+The value of a substituted operand is always a single operand: it is
+never parsed again as an expression.
+.VE TIP759
+.RE
 .IP "[4] \fBDouble quotes.\fR"
-If the first character of a word is double-quote
+If the first character of a word, or of an operand of an expression,
+is double-quote
 .PQ \N'34'
 then the word is terminated by the next double-quote character.
 If semi-colons, close brackets, or white space characters
 (including newlines) appear between the quotes then they are treated
 as ordinary characters and included in the word.
-Command substitution, variable substitution, and backslash substitution
-are performed on the characters between the quotes as described below.
+Command substitution, expression substitution, variable substitution,
+and backslash substitution are performed on the characters between
+the quotes as described below.
 The double-quotes are not retained as part of the word.
 .IP "[5] \fBArgument expansion.\fR"
 If a word starts with the string
@@ -64,7 +135,8 @@ substituted. For instance,
 is equivalent to
 .QW "cmd a b {[c]} d {$e} f {g h}" .
 .IP "[6] \fBBraces.\fR"
-If the first character of a word is an open brace
+If the first character of a word, or of an operand of an expression,
+is an open brace
 .PQ {
 and rule [5] does not apply, then
 the word is terminated by the matching close brace
@@ -80,20 +152,57 @@ below, nor do semi-colons, newlines, close brackets,
 or white space receive any special interpretation.
 The word will consist of exactly the characters between the
 outer braces, not including the braces themselves.
-.IP "[7] \fBCommand substitution.\fR"
+.IP "[7] \fBScript substitution.\fR"
 If a word contains an open bracket
 .PQ [
-then Tcl performs \fIcommand substitution\fR.
+then Tcl performs \fIscript substitution\fR: the characters following
+the open bracket form a script (rule [1]), which is evaluated; its
+result is substituted into the word in place of the brackets and all of
+the characters between them.
+.VS TIP759
+The kind of the script decides where it ends and how it is evaluated.
+.VE TIP759
+There may be any number of script substitutions in a single word.
+Script substitution is not performed on words enclosed in braces.
+.RS
+.TP 5
+\fBCommand substitution.\fR
+If the open bracket is not immediately followed by an open parenthesis,
+the script is a command script, and Tcl performs
+\fIcommand substitution\fR.
 To do this it invokes the Tcl interpreter recursively to process
 the characters following the open bracket as a Tcl script.
 The script may contain any number of commands and must be terminated
 by a close bracket
 .PQ ] "" .
 The result of the script (i.e. the result of its last command) is
-substituted into the word in place of the brackets and all of the
-characters between them.
-There may be any number of command substitutions in a single word.
-Command substitution is not performed on words enclosed in braces.
+the result of the substitution.
+.VS TIP759
+To substitute the result of a command whose name begins with an open
+parenthesis, put a space after the open bracket.
+.VE TIP759
+.TP 5
+\fBExpression substitution.\fR
+.VS TIP759
+If the open bracket is immediately followed by an open parenthesis
+.PQ [(
+the script is an expression script, and Tcl performs
+\fIexpression substitution\fR.
+The script extends from that open parenthesis to the first close
+parenthesis that is immediately followed by a close bracket
+.PQ )]
+and leaves the parentheses balanced; parentheses inside braces, quotes
+and nested substitutions are not counted.
+It is evaluated as an expression, as by the \fBexpr\fR command, and the
+value of the expression is the result of the substitution.
+For instance,
+.QW "set area [( $w * $h )]"
+is equivalent to
+.QW "set area [expr {$w * $h}]" .
+A command made of a single expression substitution is described in
+rule [2].
+.VE TIP759
+.RE
 .IP "[8] \fBVariable substitution.\fR"
 If a word contains a dollar-sign
 .PQ $
@@ -231,6 +340,11 @@ Backslash substitution is not performed on words enclosed in braces,
 except for backslash-newline as described above.
 .RE
 .IP "[10] \fBComments.\fR"
+Comments are recognized differently in a command script and in an
+expression.
+.RS
+.TP 5
+\fBComments in a command script.\fR
 If a hash character
 .PQ #
 appears at a point where Tcl is
@@ -239,7 +353,22 @@ then the hash character and the characters that follow it, up
 through the next newline, are treated as a comment and ignored.
 The comment character only has significance when it appears
 at the beginning of a command.
+.TP 5
+\fBComments in an expression.\fR
+.VS TIP759
+If a hash character
+.PQ #
+appears at a point where an operand is expected,
+then the hash character and the characters that follow it, up
+through the next newline, are treated as a comment and ignored,
+as described in the \fBexpr\fR manual page.
+.VE TIP759
+.RE
 .IP "[11] \fBOrder of substitution.\fR"
+The order of substitutions depends on the kind of script.
+.RS
+.TP 5
+\fBOrder of substitution in a command.\fR
 Each character is processed exactly once by the Tcl interpreter
 as part of creating the words of a command.
 For example, if variable substitution occurs then no further
@@ -262,13 +391,33 @@ set y [set x 0][incr x][incr x]
 .PP
 will always set the variable \fIy\fR to the value, \fI012\fR.
 .RE
+.TP 5
+\fBOrder of substitution in an expression.\fR
+.VS TIP759
+Substitutions in an expression are performed when the operand that
+contains them is evaluated, not before the expression is evaluated.
+Operands are evaluated from left to right, except that the operators
+\fB&&\fR, \fB||\fR and \fB?:\fR evaluate only the operands they need.
+Thus
+.QW "expr {$n != 0 && [check $n]}"
+does not invoke \fBcheck\fR when \fIn\fR is 0.
+As in a command, the value of a substitution is not substituted again.
+.VE TIP759
+.RE
 .IP "[12] \fBSubstitution and word boundaries.\fR"
 Substitutions do not affect the word boundaries of a command,
 except for argument expansion as specified in rule [5].
 For example, during variable substitution the entire value of
 the variable becomes part of a single word, even if the variable's
 value contains spaces.
-.PP
+.VS TIP759
+Likewise, in an expression, a substitution always gives a single
+operand: if the value of \fBx\fR is
+\fB1 + 1\fR, then
+.QW "$x * 2"
+multiplies the string \fB1 + 1\fR by 2, which is an error, and does
+not compute 4.
+.VE TIP759
 .SS "TCL VALUES"
 .PP
 Conceptually, all values in Tcl are strings, or to be precise, sequences of
@@ -301,7 +450,7 @@ to U+00FF and may be stored as an array of bytes. In all cases this internal
 representation is irrelevant at the Tcl language level but exposed in the Tcl
 C API.
 .SH KEYWORDS
-backslash, command, comment, script, substitution, variable
+backslash, command, comment, expression, script, substitution, variable
 '\" Local Variables:
 '\" mode: nroff
 '\" fill-column: 78
diff --git a/doc/expr.n b/doc/expr.n
index 843dc66..f659047 100644
--- a/doc/expr.n
+++ b/doc/expr.n
@@ -112,6 +112,14 @@ A Tcl command enclosed in \fBbrackets\fR
 Command substitution is performed as according to the command substitution rule
 for \fBTcl\fR.
 .TP
+An expression enclosed in \fB[(\fR and \fB)]\fR
+.
+.VS TIP759
+Expression substitution, as described in the script substitution rule
+([7]) for \fBTcl\fR: the value of the expression between the brackets is the
+value of the operand.
+.VE TIP759
+.TP
 A function call.
 .
 This is mathematical function such as \fBsin($x)\fR, whose arguments have any of
@@ -447,6 +455,16 @@ A forced string comparison whose result is 0:
 .CE
 .VE TIP461
 .PP
+.VS TIP759
+Compute a value with an expression substitution, the short form of
+\fB[expr {...}]\fR in a word:
+.PP
+.CS
+set area [( $width * $height )]
+puts "half: [( $area / 2.0 )]"
+.CE
+.VE TIP759
+.PP
 Define a procedure that computes an
 .QW interesting
 mathematical function:
diff --git a/doc/subst.n b/doc/subst.n
index 50d0b2b..7e5335a 100644
--- a/doc/subst.n
+++ b/doc/subst.n
@@ -11,17 +11,17 @@
 .BS
 '\" Note:  do not modify the .SH NAME line immediately below!
 .SH NAME
-subst \- Perform backslash, command, and variable substitutions
+subst \- Perform backslash, command, expression, and variable substitutions
 .SH SYNOPSIS
 .nf
-\fBsubst \fR?\fB\-nobackslashes\fR? ?\fB\-nocommands\fR? ?\fB\-novariables\fR? \fIstring\fR
-\fBsubst \fR?\fB\-backslashes\fR? ?\fB\-commands\fR? ?\fB\-variables\fR? \fIstring\fR
+\fBsubst \fR?\fB\-nobackslashes\fR? ?\fB\-nocommands\fR? ?\fB\-noexpr\fR? ?\fB\-novariables\fR? \fIstring\fR
+\fBsubst \fR?\fB\-backslashes\fR? ?\fB\-commands\fR? ?\fB\-expr\fR? ?\fB\-variables\fR? \fIstring\fR
 .fi
 .BE
 .SH DESCRIPTION
 .PP
 This command performs variable substitutions, command substitutions,
-and backslash substitutions on its \fIstring\fR argument and
+expression substitutions and backslash substitutions on its \fIstring\fR argument and
 returns the fully-substituted result.
 The substitutions are performed in exactly the same way as for
 Tcl commands.
@@ -29,14 +29,21 @@ As a result, the \fIstring\fR argument is actually substituted twice,
 once by the Tcl parser in the usual fashion for Tcl commands, and
 again by the \fIsubst\fR command.
 .PP
-If any of the \fB\-nobackslashes\fR, \fB\-nocommands\fR, or
-\fB\-novariables\fR are specified, then the corresponding substitutions
+If any of the \fB\-nobackslashes\fR, \fB\-nocommands\fR, \fB\-noexpr\fR,
+or \fB\-novariables\fR are specified, then the corresponding substitutions
 are not performed.
 For example, if \fB\-nocommands\fR is specified, command substitution
 is not performed:  open and close brackets are treated as ordinary characters
 with no special interpretation.
-.PP
-If any of the \fB\-backslashes\fR, \fB\-commands\fR, or
+.VS TIP759
+Expression substitution
+.QW [( ... )]
+(see rule [7] of the \fBTcl\fR manual page) is controlled by
+\fB\-noexpr\fR, not by \fB\-nocommands\fR: with \fB\-noexpr\fR, an
+open bracket followed by an open parenthesis is an ordinary character.
+.VE TIP759
+.PP
+If any of the \fB\-backslashes\fR, \fB\-commands\fR, \fB\-expr\fR, or
 \fB\-variables\fR are specified, then only the corresponding
 substitutions are performed. This means that the following lines are
 equivalent:
diff --git a/generic/tcl.h b/generic/tcl.h
index ac35656..a617e04 100644
--- a/generic/tcl.h
+++ b/generic/tcl.h
@@ -513,7 +513,8 @@ typedef struct stat *Tcl_OldStat_;
 #define TCL_SUBST_COMMANDS	001
 #define TCL_SUBST_VARIABLES	002
 #define TCL_SUBST_BACKSLASHES	004
-#define TCL_SUBST_ALL		007
+#define TCL_SUBST_EXPR		010
+#define TCL_SUBST_ALL		017
 
 /*
  * Forward declaration of Tcl_Obj to prevent an error when the forward
diff --git a/generic/tclBasic.c b/generic/tclBasic.c
index f044eef..f95b31c 100644
--- a/generic/tclBasic.c
+++ b/generic/tclBasic.c
@@ -5542,8 +5542,19 @@ TclEvalEx(
 	    eeFramePtr->line = lines;
 
 	    TclArgumentEnter(interp, objv, objectsUsed, eeFramePtr);
-	    code = Tcl_EvalObjv(interp, objectsUsed, objv,
-		    TCL_EVAL_NOERR | TCL_EVAL_SOURCE_IN_FRAME);
+	    if (TclIsExprCommand(parsePtr)) {
+		/*
+		 * TIP 759: a command that is one expression substitution
+		 * [(...)]: its value, already computed as the only word, is the
+		 * result. It is not a command name.
+		 */
+
+		Tcl_SetObjResult(interp, objv[0]);
+		code = TCL_OK;
+	    } else {
+		code = Tcl_EvalObjv(interp, objectsUsed, objv,
+			TCL_EVAL_NOERR | TCL_EVAL_SOURCE_IN_FRAME);
+	    }
 	    TclArgumentRelease(interp, objv, objectsUsed);
 
 	    eeFramePtr->line = NULL;
diff --git a/generic/tclCmdMZ.c b/generic/tclCmdMZ.c
index ca8bcea..1558a5f 100644
--- a/generic/tclCmdMZ.c
+++ b/generic/tclCmdMZ.c
@@ -3389,15 +3389,17 @@ TclSubstOptions(
     int *flagPtr)
 {
     static const char *const substOptions[] = {
-	"-backslashes", "-commands", "-variables",
-	"-nobackslashes", "-nocommands", "-novariables", NULL
+	"-backslashes", "-commands", "-expr", "-variables",
+	"-nobackslashes", "-nocommands", "-noexpr", "-novariables", NULL
     };
     static const int optionFlags[] = {
 	TCL_SUBST_BACKSLASHES,		/* -backslashes */
 	TCL_SUBST_COMMANDS,		/* -commands */
+	TCL_SUBST_EXPR,			/* -expr (TIP 759: [(expr)]) */
 	TCL_SUBST_VARIABLES,		/* -variables */
 	TCL_SUBST_BACKSLASHES << 16,	/* -nobackslashes */
 	TCL_SUBST_COMMANDS    << 16,	/* -nocommands */
+	TCL_SUBST_EXPR        << 16,	/* -noexpr */
 	TCL_SUBST_VARIABLES   << 16	/* -novariables */
     };
     int flags = numOpts ? 0 : TCL_SUBST_ALL;
@@ -3447,8 +3449,8 @@ TclNRSubstObjCmd(
 
     if (objc < 2) {
 	Tcl_WrongNumArgs(interp, 1, objv,
-		"?-backslashes? ?-commands? ?-variables? "
-		"?-nobackslashes? ?-nocommands? ?-novariables? string");
+		"?-backslashes? ?-commands? ?-expr? ?-variables? "
+		"?-nobackslashes? ?-nocommands? ?-noexpr? ?-novariables? string");
 	return TCL_ERROR;
     }
 
diff --git a/generic/tclCompCmdsSZ.c b/generic/tclCompCmdsSZ.c
index a100354..f29d8ed 100644
--- a/generic/tclCompCmdsSZ.c
+++ b/generic/tclCompCmdsSZ.c
@@ -1560,7 +1560,8 @@ TclSubstCompile(
 		int foundCommand = 0;
 
 		for (i=2 ; i<=tokenPtr->numComponents ; i++) {
-		    if (tokenPtr[i].type == TCL_TOKEN_COMMAND) {
+		    if (tokenPtr[i].type == TCL_TOKEN_COMMAND
+			    || tokenPtr[i].type == TCL_TOKEN_SUB_EXPR) {
 			foundCommand = 1;
 			break;
 		    }
@@ -1608,6 +1609,10 @@ TclSubstCompile(
 			envPtr);
 		count++;
 		break;
+	    case TCL_TOKEN_SUB_EXPR:	/* TIP 759: [(expr)] */
+		TclCompileSubExpr(interp, tokenPtr, envPtr);
+		count++;
+		break;
 	    case TCL_TOKEN_VARIABLE:
 		TclCompileVarSubst(interp, tokenPtr, envPtr);
 		count++;
diff --git a/generic/tclCompExpr.c b/generic/tclCompExpr.c
index a5b3940..1d9d309 100644
--- a/generic/tclCompExpr.c
+++ b/generic/tclCompExpr.c
@@ -503,10 +503,24 @@ static void		ConvertTreeToTokens(const char *start, Tcl_Size numBytes,
 			    Tcl_Parse *parsePtr);
 static int		ExecConstantExprTree(Tcl_Interp *interp, OpNode *nodes,
 			    Tcl_Size index, Tcl_Obj *const **litObjvPtr);
+/*
+ * TIP 759: what ParseExpr needs and gives for an expression substitution
+ * [(...)].
+ */
+
+typedef struct SubstExpr {
+    Tcl_Size length;		/* Bytes up to and including the "]", or 0. */
+    int depth;			/* Nesting depth of [(...)] in [(...)]. */
+} SubstExpr;
+
+static int		ParseExprSubst(Tcl_Interp *interp, const char *start,
+			    Tcl_Size numBytes, Tcl_Size *lengthPtr,
+			    Tcl_Parse *parsePtr, int depth);
 static int		ParseExpr(Tcl_Interp *interp, const char *start,
 			    Tcl_Size numBytes, OpNode **opTreePtr,
 			    Tcl_Obj *litList, Tcl_Obj *funcList,
-			    Tcl_Parse *parsePtr, bool parseOnly);
+			    Tcl_Parse *parsePtr, bool parseOnly,
+			    SubstExpr *substPtr);
 static Tcl_Size		ParseLexeme(const char *start, Tcl_Size numBytes,
 			    unsigned char *lexemePtr, Tcl_Obj **literalPtr);
 
@@ -553,11 +567,19 @@ ParseExpr(
     Tcl_Parse *parsePtr,	/* Structure to fill with tokens representing
 				 * those operands that require run time
 				 * substitutions. */
-    bool parseOnly)		/* A boolean indicating whether the caller's
+    bool parseOnly,		/* A boolean indicating whether the caller's
 				 * aim is just a parse, or whether it will go
 				 * on to compile the expression. Different
 				 * optimizations are appropriate for the two
 				 * scenarios. */
+    SubstExpr *substPtr)	/* TIP 759: NULL, or the expression is the
+				 * "(...)" of an expression substitution
+				 * [(...)]. The parse then ends with the ")"
+				 * that balances the first "(", when "]"
+				 * follows it directly, and the number of
+				 * bytes up to and including that "]" is
+				 * written in substPtr->length (0 if there is
+				 * none). */
 {
     OpNode *nodes = NULL;	/* Pointer to the OpNode storage array where
 				 * we build the parse tree. */
@@ -617,7 +639,13 @@ ParseExpr(
 				 * original expression. In order to keep the
 				 * error message readable, we impose this
 				 * limit on the substring size we extract. */
+    const char *exprStart = start;
+    int parenDepth = 0;		/* TIP 759: depth of parentheses, for an
+				 * expression substitution [(...)]. */
 
+    if (substPtr != NULL) {
+	substPtr->length = 0;
+    }
     TclParseInit(interp, start, numBytes, parsePtr);
 
     nodes = (OpNode *)Tcl_AttemptAlloc(nodesAvailable * sizeof(OpNode));
@@ -944,10 +972,29 @@ ParseExpr(
 		break;
 
 	    case SCRIPT: {
-		Tcl_Parse *nestedPtr = (Tcl_Parse *)
-			TclStackAlloc(interp, sizeof(Tcl_Parse));
+		Tcl_Parse *nestedPtr;
 
 		tokenPtr = parsePtr->tokenPtr + parsePtr->numTokens;
+		if (numBytes > 1 && start[1] == '(') {
+		    /*
+		     * TIP 759: an expression substitution [(...)].
+		     */
+
+		    code = ParseExprSubst(interp, start, numBytes, &scanned,
+			    parsePtr,
+			    (substPtr != NULL) ? substPtr->depth + 1 : 1);
+		    if (code == TCL_OK) {
+			tokenPtr->type = TCL_TOKEN_SUB_EXPR;
+			tokenPtr->start = start;
+			tokenPtr->size = scanned;
+			tokenPtr->numComponents = 0;
+			parsePtr->numTokens++;
+		    }
+		    break;
+		}
+
+		nestedPtr = (Tcl_Parse *)
+			TclStackAlloc(interp, sizeof(Tcl_Parse));
 		tokenPtr->type = TCL_TOKEN_COMMAND;
 		tokenPtr->start = start;
 		tokenPtr->numComponents = 0;
@@ -1048,6 +1095,9 @@ ParseExpr(
 	} /* case LEAF */
 
 	case UNARY:
+	    if (substPtr != NULL && lexeme == OPEN_PAREN) {
+		parenDepth++;
+	    }
 
 	    /*
 	     * A unary operator appearing just after something that's not an
@@ -1095,6 +1145,21 @@ ParseExpr(
 	    OpNode *incompletePtr;
 	    unsigned char precedence = prec[lexeme];
 
+	    if (substPtr != NULL && lexeme == CLOSE_PAREN
+		    && --parenDepth == 0) {
+		/*
+		 * TIP 759: the ")" that balances the first "(" ends an
+		 * expression substitution when "]" follows it directly: ")]"
+		 * is one symbol. The parse ends here: this lexeme is the last
+		 * one.
+		 */
+
+		if (numBytes > 1 && start[1] == ']') {
+		    substPtr->length = (start - exprStart) + 2;
+		    numBytes = scanned;
+		}
+	    }
+
 	    /*
 	     * A binary operator appearing just after another operator is a
 	     * syntax error -- one of the two operators is missing an operand.
@@ -1822,6 +1887,123 @@ ConvertTreeToTokens(
     }
 }
 
+/*
+ *----------------------------------------------------------------------
+ *
+ * TclParseExprSubst --
+ *
+ *	TIP 759. START points at "[(", the beginning of an expression
+ *	substitution [(...)]. Find where it ends: the ")" that balances the
+ *	first "(", directly followed by "]": ")]" is one symbol.
+ *
+ * Results:
+ *	TCL_OK, and the length of the whole substitution, from "[" to "]",
+ *	is written to *lengthPtr. TCL_ERROR if the expression is not valid
+ *	or has no end: the error message is left in interp (if not NULL), and
+ *	the errorType, term (the "[") and incomplete fields of parsePtr are
+ *	set.
+ *
+ *----------------------------------------------------------------------
+ */
+
+int
+TclParseExprSubst(
+    Tcl_Interp *interp,		/* For error reporting, or NULL. */
+    const char *start,		/* Points to "[(". */
+    Tcl_Size numBytes,		/* Bytes available from start. */
+    Tcl_Size *lengthPtr,	/* Receives the length of [(...)]. */
+    Tcl_Parse *parsePtr)	/* Receives the error information. */
+{
+    return ParseExprSubst(interp, start, numBytes, lengthPtr, parsePtr, 0);
+}
+
+static int
+ParseExprSubst(
+    Tcl_Interp *interp,		/* For error reporting, or NULL. */
+    const char *start,		/* Points to "[(". */
+    Tcl_Size numBytes,		/* Bytes available from start. */
+    Tcl_Size *lengthPtr,	/* Receives the length of [(...)]. */
+    Tcl_Parse *parsePtr,	/* Receives the error information. */
+    int depth)			/* Nesting depth in other [(...)]. */
+{
+    Interp *iPtr = (Interp *) interp;
+    SubstExpr subst;
+    OpNode *opTree = NULL;
+    Tcl_Obj *litList, *funcList;
+    Tcl_Size length;
+    int code;
+    Tcl_Parse *exprParsePtr;
+
+    /*
+     * Each nested [(...)] is parsed by a nested call of ParseExpr: limit the
+     * depth, so that the C stack does not overflow. The interpreter's
+     * recursion limit applies, as for nested compilations; without an
+     * interpreter, the default one.
+     */
+
+    if ((depth > ((iPtr != NULL) ? iPtr->maxNestingDepth : MAX_NESTING_DEPTH))
+	    || ((iPtr != NULL)
+	    && (iPtr->numLevels / 5 > iPtr->maxNestingDepth / 4))) {
+	if (interp != NULL) {
+	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
+		    "too many nested expression substitutions",
+		    TCL_AUTO_LENGTH));
+	    Tcl_SetErrorCode(interp, "TCL", "LIMIT", "STACK", (char *)NULL);
+	}
+	parsePtr->errorType = TCL_PARSE_SYNTAX;
+	parsePtr->term = start;
+	parsePtr->incomplete = 0;
+	return TCL_ERROR;
+    }
+
+    exprParsePtr = (Tcl_Parse *)TclStackAlloc(interp, sizeof(Tcl_Parse));
+    subst.length = 0;
+    subst.depth = depth;
+    TclNewObj(litList);
+    TclNewObj(funcList);
+    if (iPtr != NULL) {
+	iPtr->numLevels++;
+    }
+    code = ParseExpr(interp, start + 1, numBytes - 1, &opTree, litList,
+	    funcList, exprParsePtr, true /* parseOnly */, &subst);
+    if (iPtr != NULL) {
+	iPtr->numLevels--;
+    }
+    length = subst.length;
+    Tcl_DecrRefCount(funcList);
+    Tcl_DecrRefCount(litList);
+    if (code == TCL_OK && length == 0) {
+	/*
+	 * A valid expression, but the string ends before the "]".
+	 */
+
+	if (interp != NULL) {
+	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
+		    "missing close-bracket", TCL_AUTO_LENGTH));
+	    Tcl_SetErrorCode(interp, "TCL", "PARSE", "EXPR", "UNBALANCED",
+		    (char *)NULL);
+	}
+	exprParsePtr->errorType = TCL_PARSE_MISSING_BRACKET;
+	exprParsePtr->incomplete = 1;
+	code = TCL_ERROR;
+    } else if (code != TCL_OK
+	    && exprParsePtr->errorType == TCL_PARSE_MISSING_PAREN) {
+	exprParsePtr->errorType = TCL_PARSE_MISSING_BRACKET;
+	exprParsePtr->incomplete = 1;
+    }
+    if (code == TCL_OK) {
+	*lengthPtr = 1 + length;
+    } else {
+	parsePtr->errorType = exprParsePtr->errorType;
+	parsePtr->term = start;
+	parsePtr->incomplete = exprParsePtr->incomplete;
+    }
+    Tcl_FreeParse(exprParsePtr);
+    TclStackFree(interp, exprParsePtr);
+    Tcl_Free(opTree);
+    return code;
+}
+
 /*
  *----------------------------------------------------------------------
  *
@@ -1873,7 +2055,7 @@ Tcl_ParseExpr(
     }
 
     code = ParseExpr(interp, start, numBytes, &opTree, litList, funcList,
-	    exprParsePtr, true /* parseOnly */);
+	    exprParsePtr, true /* parseOnly */, NULL);
     Tcl_DecrRefCount(funcList);
     Tcl_DecrRefCount(litList);
 
@@ -2205,7 +2387,7 @@ TclCompileExpr(
     TclNewObj(litList);
     TclNewObj(funcList);
     code = ParseExpr(interp, script, numBytes, &opTree, litList,
-	    funcList, parsePtr, false /* parseOnly */);
+	    funcList, parsePtr, false /* parseOnly */, NULL);
 
     if (code == TCL_OK) {
 	/*
diff --git a/generic/tclCompile.c b/generic/tclCompile.c
index 7e031a2..bb7bfe9 100644
--- a/generic/tclCompile.c
+++ b/generic/tclCompile.c
@@ -2417,6 +2417,14 @@ CompileCommandTokens(
     /* If cmdPtr != NULL, try to call cmdPtr->compileProc */
     if (cmdPtr) {
 	code = CompileCmdCompileProc(interp, parsePtr, cmdPtr, envPtr);
+    } else if (TclIsExprCommand(parsePtr)) {
+	/*
+	 * TIP 759: a command that is one expression substitution [(...)] is
+	 * compiled as the expression. Its value is the value of the command.
+	 */
+
+	TclCompileSubExpr(interp, tokenPtr + 1, envPtr);
+	code = TCL_OK;
     }
 
     if (code == TCL_ERROR) {
@@ -2647,6 +2655,41 @@ TclCompileScript(
     TclCheckStackDepth(depth+1, envPtr);
 }
 
+/*
+ *----------------------------------------------------------------------
+ *
+ * TclCompileSubExpr --
+ *
+ *	TIP 759. Compiles the expression of an expression substitution
+ *	[(...)], a TCL_TOKEN_SUB_EXPR token. Each nested [(...)] is compiled
+ *	by a nested call: the depth is limited as for nested scripts, so that
+ *	the C stack does not overflow.
+ *
+ *----------------------------------------------------------------------
+ */
+
+void
+TclCompileSubExpr(
+    Tcl_Interp *interp,
+    Tcl_Token *tokenPtr,	/* The TCL_TOKEN_SUB_EXPR token. */
+    CompileEnv *envPtr)
+{
+    Interp *iPtr = (Interp *) interp;
+
+    if (iPtr->numLevels / 5 > iPtr->maxNestingDepth / 4) {
+	Tcl_SetObjResult(interp, Tcl_NewStringObj(
+		"too many nested compilations (infinite loop?)",
+		TCL_AUTO_LENGTH));
+	Tcl_SetErrorCode(interp, "TCL", "LIMIT", "STACK", (char *)NULL);
+	TclCompileSyntaxError(interp, envPtr);
+	return;
+    }
+    iPtr->numLevels++;
+    TclCompileExpr(interp, tokenPtr->start + 1, tokenPtr->size - 2, envPtr,
+	    true);
+    iPtr->numLevels--;
+}
+
 /*
  *----------------------------------------------------------------------
  *
@@ -2856,6 +2899,30 @@ TclCompileTokens(
 	    numObjsToConcat++;
 	    break;
 
+	case TCL_TOKEN_SUB_EXPR:
+	    /*
+	     * TIP 759: expression substitution [(...)]. Push any accumulated
+	     * chars appearing before it.
+	     */
+
+	    if (Tcl_DStringLength(&textBuffer) > 0) {
+		int literal = TclPushDString(envPtr, &textBuffer);
+
+		numObjsToConcat++;
+		Tcl_DStringFree(&textBuffer);
+		if (numCL) {
+		    TclContinuationsEnter(TclFetchLiteral(envPtr, literal),
+			    numCL, clPosition);
+		}
+		numCL = 0;
+	    }
+
+	    envPtr->line += adjust;
+	    TclCompileSubExpr(interp, tokenPtr, envPtr);
+	    envPtr->line -= adjust;
+	    numObjsToConcat++;
+	    break;
+
 	case TCL_TOKEN_VARIABLE:
 	    /*
 	     * Push any accumulated chars appearing before the $<var>.
diff --git a/generic/tclInt.h b/generic/tclInt.h
index 16f3d7d..a24ca61 100644
--- a/generic/tclInt.h
+++ b/generic/tclInt.h
@@ -3605,6 +3605,24 @@ MODULE_SCOPE int	TclParseNumber(Tcl_Interp *interp, Tcl_Obj *objPtr,
 MODULE_SCOPE void	TclParseInit(Tcl_Interp *interp, const char *string,
 			    Tcl_Size numBytes, Tcl_Parse *parsePtr);
 MODULE_SCOPE Tcl_Size	TclParseAllWhiteSpace(const char *src, Tcl_Size numBytes);
+MODULE_SCOPE void	TclCompileSubExpr(Tcl_Interp *interp,
+			    Tcl_Token *tokenPtr, struct CompileEnv *envPtr);
+MODULE_SCOPE int	TclParseExprSubst(Tcl_Interp *interp,
+			    const char *start, Tcl_Size numBytes,
+			    Tcl_Size *lengthPtr, Tcl_Parse *parsePtr);
+
+/*
+ * TIP 759: is the command parsed in *parsePtr made of one word, itself made
+ * of one TCL_TOKEN_SUB_EXPR token, an expression substitution [(...)]? The
+ * value of the expression is then the result of the command; it is not a
+ * command name.
+ */
+
+#define TclIsExprCommand(parsePtr) \
+    ((parsePtr)->numWords == 1 \
+	&& (parsePtr)->tokenPtr[0].type == TCL_TOKEN_WORD \
+	&& (parsePtr)->tokenPtr[0].numComponents == 1 \
+	&& (parsePtr)->tokenPtr[1].type == TCL_TOKEN_SUB_EXPR)
 MODULE_SCOPE int	TclProcessReturn(Tcl_Interp *interp,
 			    int code, int level, Tcl_Obj *returnOpts);
 MODULE_SCOPE void	TclUndoRefCount(Tcl_Obj *objPtr);
diff --git a/generic/tclParse.c b/generic/tclParse.c
index 3a40a40..f5c1a6e 100644
--- a/generic/tclParse.c
+++ b/generic/tclParse.c
@@ -1106,6 +1106,32 @@ ParseTokens(
 	    }
 	    src += parsePtr->tokenPtr[varToken].size;
 	    numBytes -= parsePtr->tokenPtr[varToken].size;
+	} else if (numBytes >= 2 && src[0] == '[' && src[1] == '(') {
+	    /*
+	     * TIP 759: expression substitution [(expr)]. The expression
+	     * parser finds where it ends: the ")" that balances the first
+	     * "(", followed by "]".
+	     */
+
+	    Tcl_Size length;
+
+	    if (!(flags & TCL_SUBST_EXPR)) {
+		tokenPtr->type = TCL_TOKEN_TEXT;
+		tokenPtr->size = 1;
+		parsePtr->numTokens++;
+		src++;
+		numBytes--;
+		continue;
+	    }
+	    if (TclParseExprSubst(parsePtr->interp, src, numBytes, &length,
+		    parsePtr) != TCL_OK) {
+		return TCL_ERROR;
+	    }
+	    tokenPtr->type = TCL_TOKEN_SUB_EXPR;
+	    tokenPtr->size = length;
+	    parsePtr->numTokens++;
+	    src += length;
+	    numBytes -= length;
 	} else if (*src == '[') {
 	    Tcl_Parse *nestedPtr;
 
@@ -2002,9 +2028,10 @@ TclSubstParse(
 	    parsePtr->end = p + length;
 	    p = parsePtr->term + 1;
 	    length = parsePtr->end - p;
-	    if (length == 0) {
+	    if (length == 0 || ((flags & TCL_SUBST_EXPR) && *p == '(')) {
 		/*
-		 * No commands, just an unmatched [. As in previous cases,
+		 * No commands, just an unmatched [, or a bad expression
+		 * substitution [(...)] (TIP 759). As in previous cases,
 		 * existing token stream is OK.
 		 */
 	    } else {
@@ -2219,7 +2246,32 @@ TclSubstTokens(
 		adjust++;
 	    }
 	    break;
+	case TCL_TOKEN_SUB_EXPR: {
+	    /*
+	     * TIP 759: expression substitution [(expr)]. The expression is
+	     * the text between the brackets.
+	     */
+
+	    Tcl_Obj *exprObj, *valueObj;
+
+	    exprObj = Tcl_NewStringObj(tokenPtr->start + 1, tokenPtr->size - 2);
+	    Tcl_IncrRefCount(exprObj);
+	    code = Tcl_ExprObj(interp, exprObj, &valueObj);
+	    Tcl_DecrRefCount(exprObj);
+	    TclAdvanceLines(&line, tokenPtr->start + 1,
+		    tokenPtr->start + tokenPtr->size - 1);
+	    if (code == TCL_OK) {
+		/*
+		 * Tcl_ExprObj gives the caller a reference; appendObj is
+		 * borrowed, as for a command, from the interpreter result.
+		 */
 
+		Tcl_SetObjResult(interp, valueObj);
+		Tcl_DecrRefCount(valueObj);
+		appendObj = Tcl_GetObjResult(interp);
+	    }
+	    break;
+	}
 	case TCL_TOKEN_COMMAND: {
 	    /* TIP #280: Transfer line information to nested command */
 	    iPtr->numLevels++;
diff --git a/tests/exprSubst.test b/tests/exprSubst.test
new file mode 100644
index 0000000..9bb9089
--- /dev/null
+++ b/tests/exprSubst.test
@@ -0,0 +1,306 @@
+# Commands covered: expression substitution [(...)] (TIP 759)
+#
+# This file contains a collection of tests for the expression substitution
+# [(expr)] of TIP 759, in scripts, in [subst] and in expressions. Sourcing
+# this file into Tcl runs the tests and generates output for errors. No
+# output means no errors were found.
+#
+# See the file "license.terms" for information on usage and redistribution of
+# this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
+
+::tcltest::loadTestedCommands
+catch [list package require -exact tcl::test [info patchlevel]]
+
+testConstraint testevalex [llength [info commands testevalex]]
+
+# In a word of a command
+
+test exprSubst-1.1 {whole word} {
+    set x [(1+2)]
+} 3
+test exprSubst-1.2 {variables in the expression} {
+    set a 3
+    set x [( $a * 2 )]
+} 6
+test exprSubst-1.3 {in a quoted word} {
+    set a 3
+    set x "v=[($a+1)]!"
+} v=4!
+test exprSubst-1.4 {followed by text in the word} {
+    set x [(1)]+1
+} 1+1
+test exprSubst-1.5 {two substitutions in a word} {
+    set x [( 1+2 )][( 3 )]
+} 33
+test exprSubst-1.6 {")]" is one symbol: no white space inside} -body {
+    set x [( 1+2 ) ]
+} -returnCodes error -match glob -result {invalid character "]"*}
+test exprSubst-1.7 {the first "(" is closed early} {
+    set x [(1)+(2)]
+} 3
+test exprSubst-1.8 {nested parentheses} {
+    set x [( (1+2)*(3+4) )]
+} 21
+test exprSubst-1.9 {function call} {
+    set x [( max(1,2) )]
+} 2
+test exprSubst-1.10 {nested expression substitution} {
+    set x [(1+[(2*3)])]
+} 7
+test exprSubst-1.11 {command substitution inside} {
+    set L {1 2 3}
+    set x [( [llength $L] * 2 )]
+} 6
+test exprSubst-1.12 {brackets and parentheses in strings are skipped} {
+    set x [( {a)]} eq "a)]" )]
+} 1
+test exprSubst-1.13 {close bracket in a quoted string} {
+    set x "[( "]" )]"
+} \]
+test exprSubst-1.14 {in an array index} {
+    set y(2) 7
+    set x $y([(1+1)])
+} 7
+test exprSubst-1.15 {on several lines} {
+    set x [(
+	1 +
+	2
+    )]
+} 3
+test exprSubst-1.16 {in a procedure} -setup {
+    proc p {v} {return [( $v*7 )]}
+} -body {
+    p 6
+} -cleanup {
+    rename p {}
+} -result 42
+test exprSubst-1.17 {in a loop body} {
+    set r {}
+    foreach v {1 2 3} {lappend r [($v*$v)]}
+    set r
+} {1 4 9}
+test exprSubst-1.18 {in a lambda} {
+    apply {{} {set a 5; return [($a**2)]}}
+} 25
+test exprSubst-1.19 {error in the expression} -body {
+    set x [(1/0)]
+} -returnCodes error -result {divide by zero}
+test exprSubst-1.20 {error is catchable} {
+    list [catch {set x [(1/0)]} m] $m
+} {1 {divide by zero}}
+test exprSubst-1.21 {not compiled: Tcl_EvalEx} -constraints testevalex -body {
+    testevalex {set x [( 2*[(3+4)] )]}
+} -result 14
+test exprSubst-1.22 {not compiled: Tcl_EvalEx, error} -constraints testevalex -body {
+    testevalex {set x [(1/0)]}
+} -returnCodes error -result {divide by zero}
+
+test exprSubst-1.23 {deep nesting is limited, no C stack overflow} -body {
+    set n 5000
+    eval "set x [string repeat {[( 1 + } $n]0[string repeat { )]} $n]"
+} -returnCodes error -match glob -result {too many nested expression substitutions*}
+test exprSubst-1.24 {deep nesting mixed with commands} -body {
+    set n 5000
+    eval "set x [string repeat {[( 1 + [list } $n]0[string repeat { ] )]} $n]"
+} -returnCodes error -match glob -result {too many nested*}
+test exprSubst-1.25 {moderate nesting} {
+    set n 200
+    eval "set x [string repeat {[( 1 + } $n]0[string repeat { )]} $n]"
+} 200
+test exprSubst-1.26 {deep nesting in subst} -body {
+    set n 5000
+    subst "[string repeat {[( 1 + } $n]0[string repeat { )]} $n]"
+} -returnCodes error -match glob -result {too many nested expression substitutions*}
+
+# A command that is one expression substitution: its value is the result
+
+test exprSubst-5.1 {expression substitution alone as a command} {
+    set x 1
+    eval {[($x*3)]}
+} 3
+test exprSubst-5.2 {alone as a command, side effect} -setup {
+    unset -nocomplain y
+} -body {
+    set x 2
+    eval {[( [set y $x] * 3 )]
+	set y}
+} -result 2
+test exprSubst-5.3 {alone as a command, in a procedure} -setup {
+    proc p {x} {[( [set y $x] )]; return $y}
+} -body {
+    p 4
+} -cleanup {
+    rename p {}
+} -result 4
+test exprSubst-5.4 {alone as a command, compiled as an expression} -setup {
+    proc p {x} {[($x*3)]}
+} -body {
+    list [p 5] [string match {*invoke*} [tcl::unsupported::disassemble proc p]]
+} -cleanup {
+    rename p {}
+} -result {15 0}
+test exprSubst-5.5 {alone as a command, Tcl_EvalEx} -constraints testevalex -body {
+    set x 1
+    testevalex {[($x*7)]}
+} -result 7
+test exprSubst-5.6 {alone as a command, in a sourced file} -setup {
+    set f [makeFile {set x 3
+[($x*3)]} exprSubst5.tcl]
+} -body {
+    source $f
+} -cleanup {
+    removeFile exprSubst5.tcl
+} -result 9
+test exprSubst-5.7 {two substitutions in the word: a command name} -setup {
+    proc 12 {} {return twelve}
+} -body {
+    eval {[(1)][(2)]}
+} -cleanup {
+    rename 12 {}
+} -result twelve
+test exprSubst-5.8 {with an argument: a command name} -setup {
+    proc 3 {a} {return three$a}
+} -body {
+    eval {[(1+2)] !}
+} -cleanup {
+    rename 3 {}
+} -result three!
+test exprSubst-5.9 {expanded: a command name} -setup {
+    proc 3 {} {return three}
+} -body {
+    eval {{*}[(1+2)]}
+} -cleanup {
+    rename 3 {}
+} -result three
+test exprSubst-5.10 {command substitution alone: still a command name} -setup {
+    proc 3 {} {return three}
+} -body {
+    eval {[expr {1+2}]}
+} -cleanup {
+    rename 3 {}
+} -result three
+test exprSubst-5.11 {alone as a command, error} -body {
+    eval {[(1/0)]}
+} -returnCodes error -result {divide by zero}
+
+# Syntax
+
+test exprSubst-2.1 {missing close bracket} -body {
+    set x [(1+2)
+} -returnCodes error -result {missing close-bracket}
+test exprSubst-2.2 {bad syntax} -body {
+    set x [(1+) ]
+} -returnCodes error -match glob -result {missing operand at _@_*}
+test exprSubst-2.3 {unbalanced close paren} -body {
+    set x [(1+2))]
+} -returnCodes error -match glob -result {unbalanced close paren*}
+test exprSubst-2.4 {text after the expression} -body {
+    set x [(1+2) foo]
+} -returnCodes error -match glob -result {invalid bareword "foo"*}
+test exprSubst-2.5 {info complete} {
+    list [info complete "set x \[(1+2"] [info complete "set x \[(1+2)"] \
+	[info complete "set x \[(1+2)\]"] [info complete "set x \[(\"a\""]
+} {0 0 1 0}
+test exprSubst-2.6 {a command whose name starts with "(" needs a space} -setup {
+    proc (p) {} {return cmd}
+} -body {
+    set x [ (p)]
+} -cleanup {
+    rename (p) {}
+} -result cmd
+
+# In an expression
+
+test exprSubst-3.1 {operand of an expression} {
+    expr {[(1)]+1}
+} 2
+test exprSubst-3.2 {operand, with white space} {
+    expr {[( 1 )] + 1}
+} 2
+test exprSubst-3.3 {quoted strings inside} {
+    expr {1+[( "a"=="b" )]}
+} 1
+test exprSubst-3.4 {two operands} {
+    expr {[(2)]*[(3)]}
+} 6
+test exprSubst-3.5 {error inside} -body {
+    expr {[(1/0)] + 1}
+} -returnCodes error -result {divide by zero}
+test exprSubst-3.6 {missing close bracket inside} -body {
+    expr {1 + [(2)}
+} -returnCodes error -match glob -result {missing close-bracket*}
+test exprSubst-3.7 {missing close paren inside} -body {
+    expr {1 + [(2}
+} -returnCodes error -match glob -result {unbalanced open paren*}
+
+# subst
+
+test exprSubst-4.1 {subst} {
+    subst {a [(1+2)] b}
+} {a 3 b}
+test exprSubst-4.2 {subst -noexpr} {
+    subst -noexpr {a [(1+2)] b}
+} {a [(1+2)] b}
+test exprSubst-4.3 {subst -nocommands keeps expressions} {
+    subst -nocommands {a [(1+2)] b [list x]}
+} {a 3 b [list x]}
+test exprSubst-4.4 {subst -expr alone} {
+    set a 1
+    subst -expr {a [(1+2)] b [list x] $a}
+} {a 3 b [list x] $a}
+test exprSubst-4.5 {subst, compiled} -setup {
+    proc p {} {subst {a [(1+2)] b}}
+} -body {
+    p
+} -cleanup {
+    rename p {}
+} -result {a 3 b}
+test exprSubst-4.6 {subst, not compiled} {
+    set s {a [(1+2)] b}
+    subst $s
+} {a 3 b}
+test exprSubst-4.7 {subst, syntax error} -body {
+    subst {a [(1+) ] b}
+} -returnCodes error -match glob -result {missing operand at _@_*}
+test exprSubst-4.8 {subst, error in the expression, compiled} -setup {
+    proc p {} {subst {a [(1/0)] b}}
+} -body {
+    p
+} -cleanup {
+    rename p {}
+} -returnCodes error -result {divide by zero}
+test exprSubst-4.9 {subst, break in the expression} {
+    subst {a [( [break] )] b}
+} {a }
+test exprSubst-4.11 {subst, syntax error, no endless loop} -body {
+    subst {[( 1 + )]}
+} -returnCodes error -match glob -result {missing operand at _@_*}
+test exprSubst-4.12 {subst, empty expression, no endless loop} -body {
+    subst {[( ) ]}
+} -returnCodes error -match glob -result {empty subexpression*}
+test exprSubst-4.13 {subst, syntax error, compiled} -setup {
+    proc p {} {subst {a [( 1 + )] b}}
+} -body {
+    p
+} -cleanup {
+    rename p {}
+} -returnCodes error -match glob -result {missing operand at _@_*}
+test exprSubst-4.14 {subst, missing close bracket} -body {
+    subst {a [( 1 + 2 ) b}
+} -returnCodes error -match glob -result {invalid bareword "b"*}
+test exprSubst-4.10 {subst -noexpr -nocommands} {
+    subst -noexpr -nocommands {[(1+2)] [list x]}
+} {[(1+2)] [list x]}
+
+# cleanup
+::tcltest::cleanupTests
+return
+
+# Local Variables:
+# mode: tcl
+# End:
diff --git a/tests/subst.test b/tests/subst.test
index 30dba7d..29c3fa7 100644
--- a/tests/subst.test
+++ b/tests/subst.test
@@ -22,10 +22,10 @@ testConstraint testbytestring [llength [info commands testbytestring]]
 
 test subst-1.1 {basics} -returnCodes error -body {
     subst
-} -result {wrong # args: should be "subst ?-backslashes? ?-commands? ?-variables? ?-nobackslashes? ?-nocommands? ?-novariables? string"}
+} -result {wrong # args: should be "subst ?-backslashes? ?-commands? ?-expr? ?-variables? ?-nobackslashes? ?-nocommands? ?-noexpr? ?-novariables? string"}
 test subst-1.2 {basics} -returnCodes error -body {
     subst a b c
-} -result {bad option "a": must be -backslashes, -commands, -variables, -nobackslashes, -nocommands, or -novariables}
+} -result {bad option "a": must be -backslashes, -commands, -expr, -variables, -nobackslashes, -nocommands, -noexpr, or -novariables}
 
 test subst-2.1 {simple strings} {
     subst {}
@@ -123,13 +123,13 @@ test subst-6.1 {clear the result after command substitution} -body {
 
 test subst-7.1 {switches} -returnCodes error -body {
     subst foo bar
-} -result {bad option "foo": must be -backslashes, -commands, -variables, -nobackslashes, -nocommands, or -novariables}
+} -result {bad option "foo": must be -backslashes, -commands, -expr, -variables, -nobackslashes, -nocommands, -noexpr, or -novariables}
 test subst-7.2 {switches} -returnCodes error -body {
     subst -no bar
-} -result {ambiguous option "-no": must be -backslashes, -commands, -variables, -nobackslashes, -nocommands, or -novariables}
+} -result {ambiguous option "-no": must be -backslashes, -commands, -expr, -variables, -nobackslashes, -nocommands, -noexpr, or -novariables}
 test subst-7.3 {switches} -returnCodes error -body {
     subst -bogus bar
-} -result {bad option "-bogus": must be -backslashes, -commands, -variables, -nobackslashes, -nocommands, or -novariables}
+} -result {bad option "-bogus": must be -backslashes, -commands, -expr, -variables, -nobackslashes, -nocommands, -noexpr, or -novariables}
 test subst-7.4 {switches} {
     set x 123
     subst -nobackslashes {abc $x [expr {1 + 2}] \\\x41}
-- 
2.43.0