Version 1 of Overloaded source for C-style comments

Updated 2006-06-05 15:26:32

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 http://wiki.tcl.tk/2523 and http://wiki.tcl.tk/8520 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 
      info script $filename 
      uplevel 1 $script 
   } 

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 */
  }

Category Example