Search code examples
tclexpr

Why doesn't compiler automatically brace expr?


I was reading through Donal Fellows' excellent explanation on why you should brace your expr.

It makes me wonder why doesn't the tcl compiler automatically brace {} the expr? What are conditions under which this automatic bracing will fail?


Solution

  • It makes me wonder why doesn't the tcl compiler automatically brace {} the expr?

    It actually did so during some of the alphas for 8.0. It was removed because the wider community absolutely hated it. The core Tcl language — the 12 rules on the Tcl(n) manual page — is kept extremely small and simple, and it's applied uniformly to everything.

    No special cases. That is what most Tcl programmers want.

    If I remember right, the auto-bracing was particularly considered for if and while. With if, it was because omitting the braces for a test of the result of a command was a particularly common practice with Tcl 7 because it was faster (the expression engine was rather embarrassingly slow). With while, it was because omitting the braces was a common user bug.

    What are conditions under which this automatic bracing will fail?

    Well, it would be noticeable in something like this:

    set a 1
    set b 2
    set op +
    set c [expr $a$op$b]
    

    Right now, that sets c to 3. With auto-bracing, it would be a syntax error (since the expression grammar doesn't have anything it can do with three variables in a row). A work-around was proposed:

    set c [eval expr $a$op$b]
    

    But frankly, getting everyone to brace their expressions except when they really wanted double-substitution (and runtime expression compilation) was considered to be better.

    Double-substitution is almost always an indication of a security bug, and it's always an indication of a performance problem; there's virtually always a better (faster, safer) way to do it. Brace your expressions. It's safer and faster and really easy to do: what's not to like?