Overloaded source for C-style comments

DKF 2006-06-05 in comp.lang.tcl:

In most languages, comments are dealt with very early in the parsing process by the tokenizer (the thing which also identifies the strings and reserved words). This is not what Tcl does. In Tcl, comments are parsed at the same time as all the other basic syntactic components of the language (such as brace nesting) so that the commenting and quoting can interact, occasionally unfortunately. But Tcl does gain from this in some powerful ways; it is far easier to embed other languages in Tcl than virtually any other language, and https://wiki.tcl-lang.org/2523 (CriTcl) and https://wiki.tcl-lang.org/8520 (Critcl goes Fortran) talk about some of the practical benefits of doing this. Embedding Tcl in C or Fortran is much less neat...

Not that Tcl isn't capable of change. One way of getting the sort of commenting you're after would be to redefine the source command to recognize (and completely excise) some new commenting scheme so that you can comment things out however you want. Here's an example:

   proc source {filename} { 
      set f [open $filename] 
      set script [read $f] 
      close $f 
      # Only this next line is not done by normal [source] 
      regsub -all {/\*.*?\*/} $script {} script
      set saveScriptname [info script]
      info script $filename 
      uplevel 1 $script 
      info script $saveScriptname

UKo 2007-05-10: for nested scripts it is necessary to reset the scriptname that was in use before!

DKF: No it's not, since that information should actually be just restored automatically on return from your procedure.

With this, you could then use C-style comments in the rest of your code, like this:

   foreach argument $argv { /* process the command line */ 
      /* print it */         puts $argument 
      /* print its length */ puts [string length $argument] 
      /* if {$argument == 0} {     Unbalanced braces in comments! */ 
         frobnicate /* comment in the middle */ $argument 
      /* } */ 

OK, so I've gone a little mad with commenting there. :-) But the point is, once you've done that redefinition, all scripts loaded in that interpreter will understand your new (local) commenting rules. Please don't distribute the files with those changes in though, or you'll have people scratching their heads a lot when doing maintenance. :-D

But, of course, the following might not work as expected (depending on what you expect...):

  set pityTheFool {
    /* who wants to treat a comment as data */

KPV I've always felt that languages, such as HTML and postscript, where changing the content of a comment can affect the output to be rather horrid.

DKF: Yeah, but that's the trade-off with doing this sort of thing. I suppose a more complex rule for defining what is a comment and what is not could be defined, but that'd be hairy (and much longer to write).

For other comment styles, see also: