Skip to content
Tcl Source Code Artifact [ecd8688139]
Login

Artifact [ecd8688139]

Artifact ecd8688139d827ead03f321971f3e849632f3d1f9b3eca5b1c5dc302463a2c06:


From 73c8584eb772bfef110dc60a73f45bd8275d398b Mon Sep 17 00:00:00 2001
From: Florent Merlet <[email protected]>
Date: Thu, 29 Oct 2026 10:54:47 +0100
Subject: [PATCH 2/7] TIP 759 (2/7): expression scripts "(...)"

A script that begins with "(" and ends with ")" (a newline may follow)
is one expression: {(...)}, "(...)" and (...) as a procedure body, a
loop body, an eval'ed or sourced script... The value of the expression
is the result of the script. Only the whole script is tested, not the
text left after its first commands.

- TclParseExprScript: recognizes such a script and gives one command
  of one word, a TCL_TOKEN_SUB_EXPR token for the whole expression.
  TclCompileScript and TclEvalEx call it on the whole script, before
  parsing its first command; Tcl_ParseCommand is unchanged.
- CompileCommandTokens and TclEvalEx already take that command as an
  expression (TclIsExprCommand).
- TclSubstTokens, TclCompileSubExpr: a SUB_EXPR token that does not start
  with "[" is evaluated as a whole.
- Tests: exprScript.test. Docs: Tcl.n, expr.n.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MrNWAEyXLqekovNBvbMZ4z
---
 doc/Tcl.n             |  26 ++++--
 doc/expr.n            |   8 ++
 generic/tclBasic.c    |  10 ++-
 generic/tclCompile.c  |  26 ++++--
 generic/tclInt.h      |   9 +-
 generic/tclParse.c    |  75 +++++++++++++++-
 tests/exprScript.test | 195 ++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 325 insertions(+), 24 deletions(-)
 create mode 100644 tests/exprScript.test

diff --git a/doc/Tcl.n b/doc/Tcl.n
index cbca7af..b577927 100644
--- a/doc/Tcl.n
+++ b/doc/Tcl.n
@@ -20,7 +20,8 @@ The following rules define the syntax and semantics of the Tcl language:
 .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.
+one expression. Commands that take a script as an argument, such as
+the body of \fBproc\fR or \fBforeach\fR, accept both kinds.
 .RS
 .TP 5
 \fBCommand scripts.\fR
@@ -32,12 +33,23 @@ Close brackets are command terminators during command substitution
 .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.
+A script that begins with an open parenthesis
+.PQ (
+and ends with a close parenthesis
+.PQ ) ""
+(a newline may follow it) 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. For instance, the body of
+.QW "proc hypot {a b} {( sqrt($a**2 + $b**2) )}"
+is an expression script, and so is
+.QW "(\N'34'Hi there\N'34')" ,
+whose result is the string \fBHi there\fR.
+Only a whole script is tested: in a script of several commands, a
+command that begins with an open parenthesis is an ordinary command.
+Conversely, a script such as
+.QW "(cmd) (x)"
+is an expression script, and an error.
 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:
diff --git a/doc/expr.n b/doc/expr.n
index f659047..626f975 100644
--- a/doc/expr.n
+++ b/doc/expr.n
@@ -456,6 +456,14 @@ A forced string comparison whose result is 0:
 .VE TIP461
 .PP
 .VS TIP759
+A procedure whose body is an expression script (see rule [1] of the
+\fBTcl\fR manual page): the body is one expression.
+.PP
+.CS
+proc hypot {a b} {( sqrt($a**2 + $b**2) )}
+lmap x {1 2 3} {( $x * $x )}
+.CE
+.PP
 Compute a value with an expression substitution, the short form of
 \fB[expr {...}]\fR in a word:
 .PP
diff --git a/generic/tclBasic.c b/generic/tclBasic.c
index f95b31c..8f15074 100644
--- a/generic/tclBasic.c
+++ b/generic/tclBasic.c
@@ -5359,7 +5359,10 @@ TclEvalEx(
 
     iPtr->evalFlags = 0;
     do {
-	if (Tcl_ParseCommand(interp, p, bytesLeft, 0, parsePtr) != TCL_OK) {
+	if (!((p == script) /* TIP 759: expression script */
+		&& TclParseExprScript(interp, p, bytesLeft, parsePtr))
+		&& (Tcl_ParseCommand(interp, p, bytesLeft, 0, parsePtr)
+		!= TCL_OK)) {
 	    code = TCL_ERROR;
 	    Tcl_LogCommandInfo(interp, script, parsePtr->commandStart,
 		    parsePtr->term + 1 - parsePtr->commandStart);
@@ -5545,8 +5548,9 @@ TclEvalEx(
 	    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.
+		 * [(...)], or an expression script (...): its value, already
+		 * computed as the only word, is the result, not a command
+		 * name.
 		 */
 
 		Tcl_SetObjResult(interp, objv[0]);
diff --git a/generic/tclCompile.c b/generic/tclCompile.c
index bb7bfe9..3d8d3d2 100644
--- a/generic/tclCompile.c
+++ b/generic/tclCompile.c
@@ -2419,8 +2419,9 @@ CompileCommandTokens(
 	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.
+	 * TIP 759: a command that is one expression substitution [(...)], or
+	 * an expression script (...), is compiled as the expression. Its
+	 * value is the value of the command.
 	 */
 
 	TclCompileSubExpr(interp, tokenPtr + 1, envPtr);
@@ -2539,7 +2540,10 @@ TclCompileScript(
 	do {
 	    const char *next;
 
-	    if (TCL_OK != Tcl_ParseCommand(interp, p, numBytes, 0, parsePtr)) {
+	    if (!((p == script) /* TIP 759 */
+		    && TclParseExprScript(interp, p, numBytes, parsePtr))
+		    && (TCL_OK != Tcl_ParseCommand(interp, p, numBytes, 0,
+		    parsePtr))) {
 		/*
 		* Compile bytecodes to report the parsePtr error at runtime.
 		*/
@@ -2661,9 +2665,9 @@ TclCompileScript(
  * 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.
+ *	[(...)] or of an expression script (...), 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.
  *
  *----------------------------------------------------------------------
  */
@@ -2685,8 +2689,14 @@ TclCompileSubExpr(
 	return;
     }
     iPtr->numLevels++;
-    TclCompileExpr(interp, tokenPtr->start + 1, tokenPtr->size - 2, envPtr,
-	    true);
+    if (tokenPtr->start[0] == '[') {
+	TclCompileExpr(interp, tokenPtr->start + 1, tokenPtr->size - 2,
+		envPtr, true);
+    } else {
+	/* TIP 759: expression script "(...)", the whole text */
+	TclCompileExpr(interp, tokenPtr->start, tokenPtr->size, envPtr,
+		true);
+    }
     iPtr->numLevels--;
 }
 
diff --git a/generic/tclInt.h b/generic/tclInt.h
index a24ca61..a355756 100644
--- a/generic/tclInt.h
+++ b/generic/tclInt.h
@@ -3607,15 +3607,18 @@ MODULE_SCOPE void	TclParseInit(Tcl_Interp *interp, const char *string,
 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	TclParseExprScript(Tcl_Interp *interp,
+			    const char *start, Tcl_Size numBytes,
+			    Tcl_Parse *parsePtr);
 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.
+ * of one TCL_TOKEN_SUB_EXPR token: an expression substitution [(...)], or an
+ * expression script (...)? The value of the expression is then the result
+ * of the command; it is not a command name.
  */
 
 #define TclIsExprCommand(parsePtr) \
diff --git a/generic/tclParse.c b/generic/tclParse.c
index f5c1a6e..9cf25e1 100644
--- a/generic/tclParse.c
+++ b/generic/tclParse.c
@@ -234,6 +234,7 @@ Tcl_ParseCommand(
     parsePtr->commentSize = 0;
     parsePtr->commandStart = NULL;
     parsePtr->commandSize = 0;
+
     if (nested != 0) {
 	terminators = TYPE_COMMAND_END | TYPE_CLOSE_BRACK;
     } else {
@@ -535,6 +536,68 @@ Tcl_ParseCommand(
     }
 }
 
+/*
+ *----------------------------------------------------------------------
+ *
+ * TclParseExprScript --
+ *
+ *	TIP 759. Is the script an expression script: does it begin with "("
+ *	and end with ")" (or with ")" and a newline, as typed in a console)?
+ *	Then the whole script is one command of one word, a
+ *	TCL_TOKEN_SUB_EXPR token for the whole expression (see
+ *	TclIsExprCommand).
+ *
+ *	Only the callers that evaluate or compile a whole script call it, on
+ *	the whole script, before parsing its first command: the test is on the
+ *	script, not on the text left after the previous commands.
+ *
+ * Results:
+ *	1 and *parsePtr filled if it is an expression script, 0 otherwise
+ *	(*parsePtr is then untouched).
+ *
+ *----------------------------------------------------------------------
+ */
+
+int
+TclParseExprScript(
+    Tcl_Interp *interp,		/* For the parse structure, or NULL. */
+    const char *start,		/* The whole script. */
+    Tcl_Size numBytes,		/* Its length in bytes. */
+    Tcl_Parse *parsePtr)	/* Filled if it is an expression script. */
+{
+    Tcl_Token *tokenPtr;
+    Tcl_Size length = numBytes;
+
+    if ((start == NULL) || (numBytes < 2) || (start[0] != '(')) {
+	return 0;
+    }
+    if (start[length - 1] == '\n') {
+	length--;
+    }
+    if (start[length - 1] != ')') {
+	return 0;
+    }
+    TclParseInit(interp, start, numBytes, parsePtr);
+    parsePtr->commentStart = NULL;
+    parsePtr->commentSize = 0;
+    TclGrowParseTokenArray(parsePtr, 2);
+    tokenPtr = parsePtr->tokenPtr;
+    tokenPtr[0].type = TCL_TOKEN_WORD;
+    tokenPtr[0].start = start;
+    tokenPtr[0].size = length;
+    tokenPtr[0].numComponents = 1;
+    tokenPtr[1].type = TCL_TOKEN_SUB_EXPR;
+    tokenPtr[1].start = start;
+    tokenPtr[1].size = length;
+    tokenPtr[1].numComponents = 0;
+    parsePtr->numTokens = 2;
+    parsePtr->numWords = 1;
+    parsePtr->commandStart = start;
+    parsePtr->commandSize = length;
+    parsePtr->term = start + length;
+    return 1;
+}
+
 /*
  *----------------------------------------------------------------------
  *
@@ -2254,12 +2317,18 @@ TclSubstTokens(
 
 	    Tcl_Obj *exprObj, *valueObj;
 
-	    exprObj = Tcl_NewStringObj(tokenPtr->start + 1, tokenPtr->size - 2);
+	    if (tokenPtr->start[0] == '[') {
+		exprObj = Tcl_NewStringObj(tokenPtr->start + 1,
+			tokenPtr->size - 2);
+	    } else {
+		/* TIP 759: expression script "(...)", the whole text */
+		exprObj = Tcl_NewStringObj(tokenPtr->start, tokenPtr->size);
+	    }
 	    Tcl_IncrRefCount(exprObj);
 	    code = Tcl_ExprObj(interp, exprObj, &valueObj);
 	    Tcl_DecrRefCount(exprObj);
-	    TclAdvanceLines(&line, tokenPtr->start + 1,
-		    tokenPtr->start + tokenPtr->size - 1);
+	    TclAdvanceLines(&line, tokenPtr->start,
+		    tokenPtr->start + tokenPtr->size);
 	    if (code == TCL_OK) {
 		/*
 		 * Tcl_ExprObj gives the caller a reference; appendObj is
diff --git a/tests/exprScript.test b/tests/exprScript.test
new file mode 100644
index 0000000..a2a05fb
--- /dev/null
+++ b/tests/exprScript.test
@@ -0,0 +1,195 @@
+# Commands covered: expression scripts "(...)" (TIP 759)
+#
+# This file contains a collection of tests for the expression scripts of
+# TIP 759: a script that begins with "(" and ends with ")" is one
+# expression. 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]]
+
+# Forms given by the parser: {(...)}, "(...)", (...)
+
+test exprScript-1.1 {procedure body} -setup {
+    proc sq {x} {($x*$x)}
+} -body {
+    sq 5
+} -cleanup {
+    rename sq {}
+} -result 25
+test exprScript-1.2 {procedure body, function and white space} -setup {
+    proc hyp {a b} {( sqrt($a**2 + $b**2) )}
+} -body {
+    hyp 3 4
+} -cleanup {
+    rename hyp {}
+} -result 5.0
+test exprScript-1.3 {braced loop body} {
+    lmap v {1 2 3} {($v*10)}
+} {10 20 30}
+test exprScript-1.4 {quoted loop body} {
+    lmap v {1 2 3} "(\$v+1)"
+} {2 3 4}
+test exprScript-1.5 {bare word, substituted before the call} {
+    set n 4
+    lmap v {1 2} ($n*2)
+} {8 8}
+test exprScript-1.6 {eval} {
+    set a 3
+    eval {($a+1)}
+} 4
+test exprScript-1.7 {eval, quoted} {
+    set a 3
+    eval "(\$a+2)"
+} 5
+test exprScript-1.8 {uplevel} {
+    uplevel 0 {(1+1)}
+} 2
+test exprScript-1.9 {if body} {
+    if {1} {(42)}
+} 42
+test exprScript-1.10 {the first "(" is closed early} {
+    eval {(1)+(2)}
+} 3
+test exprScript-1.11 {lambda} {
+    apply {{x} {($x - 1)}} 10
+} 9
+test exprScript-1.12 {newline after the close paren} {
+    eval "(2*3)\n"
+} 6
+test exprScript-1.13 {only a whole script: not its last command} -body {
+    eval {set b 5
+($b+1)}
+} -returnCodes error -result {invalid command name "(5+1)"}
+test exprScript-1.13.1 {only a whole script: in a procedure body} -setup {
+    proc p {} {set b 5
+($b+1)}
+} -body {
+    p
+} -cleanup {
+    rename p {}
+} -returnCodes error -result {invalid command name "(5+1)"}
+test exprScript-1.13.2 {nested script in brackets} {
+    set b 5
+    list [eval {set c [eval {($b*2)}]}] $c
+} {10 10}
+test exprScript-1.14 {command substitution inside} -setup {
+    proc f {} {( [llength {a b c}] )}
+} -body {
+    f
+} -cleanup {
+    rename f {}
+} -result 3
+test exprScript-1.15 {same script object twice} {
+    set a 3
+    set s {($a*$a)}
+    list [eval $s] [eval $s]
+} {9 9}
+test exprScript-1.16 {semicolon and newline are not separators} {
+    eval {(1 +
+	2)}
+} 3
+
+# Not compiled: Tcl_EvalEx
+
+test exprScript-2.1 {Tcl_EvalEx} -constraints testevalex -body {
+    set a 3
+    testevalex {($a * 7)}
+} -result 21
+test exprScript-2.2 {Tcl_EvalEx, first "(" closed early} -constraints {
+    testevalex
+} -body {
+    testevalex {(1)+(2)}
+} -result 3
+test exprScript-2.3 {Tcl_EvalEx, newline after} -constraints testevalex -body {
+    testevalex "(2*3)\n"
+} -result 6
+test exprScript-2.4 {Tcl_EvalEx, only a whole script} -constraints {
+    testevalex
+} -body {
+    testevalex {set b 5
+($b+1)}
+} -returnCodes error -result {invalid command name "(5+1)"}
+test exprScript-2.6 {Tcl_EvalEx, sourced file} -setup {
+    set f [makeFile {( 6 * 7 )} exprScript26.tcl]
+} -body {
+    source $f
+} -cleanup {
+    removeFile exprScript26.tcl
+} -result 42
+test exprScript-2.5 {Tcl_EvalEx, error} -constraints testevalex -body {
+    testevalex {(1/0)}
+} -returnCodes error -result {divide by zero}
+
+# Errors and limits
+
+test exprScript-3.1 {error in the expression} -body {
+    eval {(1/0)}
+} -returnCodes error -result {divide by zero}
+test exprScript-3.2 {error info} -setup {
+    proc e {} {(1/0)}
+} -body {
+    catch e m o
+    dict get $o -errorinfo
+} -cleanup {
+    rename e {}
+} -result {divide by zero
+    invoked from within
+"(1/0)"
+    (procedure "e" line 1)
+    invoked from within
+"e"}
+test exprScript-3.3 {syntax error} -body {
+    eval {(a b)}
+} -returnCodes error -match glob -result {invalid bareword "a"*}
+test exprScript-3.4 {empty expression} -body {
+    eval {()}
+} -returnCodes error -match glob -result {empty subexpression*}
+test exprScript-3.5 {script that does not end with ")" is not one} -body {
+    eval {(1+2) ;}
+} -returnCodes error -result {invalid command name "(1+2)"}
+test exprScript-3.6 {command name that starts with "("} -setup {
+    proc (x) {} {return cmd}
+} -body {
+    list [eval {(x) }] [eval { (x)}]
+} -cleanup {
+    rename (x) {}
+} -result {cmd cmd}
+test exprScript-3.7 {expression substitution alone: its value is the result} {
+    eval {[(1+2)]}
+} 3
+test exprScript-3.8 {nested command substitution is not an expression script} -setup {
+    proc (x) {} {return cmd}
+} -body {
+    set r [(x)]
+} -cleanup {
+    rename (x) {}
+} -returnCodes error -match glob -result {invalid bareword "x"*}
+
+# Bytecode
+
+test exprScript-4.1 {compiled as an expression} -setup {
+    proc sq {x} {($x*$x)}
+} -body {
+    string match "*mult*" [tcl::unsupported::disassemble proc sq]
+} -cleanup {
+    rename sq {}
+} -result 1
+
+# cleanup
+::tcltest::cleanupTests
+return
+
+# Local Variables:
+# mode: tcl
+# End:
-- 
2.43.0