Nesting line comments inside of block comments


#1

Hi,
I’m very new to Rust. However, I’ve noticed something about the Rust comment syntax that might be considered a shortcoming, although definitely not a serious one.

This is a valid line comment in Rust:

// a strange comment */ wierd stuff

However, currently if I try to comment out a block of code containing this line comment, using block comments, it does not work:

/*
// a strange comment */ wierd stuff
*/

because the block comment ends at the */ inside the line comment, leaving the ‘wierd stuff’ outside the comment, as well as the trailing */. In other words, the line comment does not properly nest inside of the block comment.

While this could definitely fall into the category of ‘just don’t do that’, it probably would not be too difficult to make line comments properly nest inside of block comments, so that any star-slash or slash-star or that occurs inside a line comment is effectively escaped from the point of view of any containing block comment.


#2

Hmm,

Possibly more troubling is that a block comment opened by /* can be terminated by a / inside a string literal.
Maybe it’s just unrealistic to expect to be able to use /
*/ block comments as a foolproof method of commenting out arbitrary code.


#3
  1. The Rust comment behavior in this regard is identical to C++98 and C99 and all other languages that borrow the // - /* */ comment syntax.
  2. Block comments are not exclusively for disabling code, they are also (primarily) intended for commenting out non-code such as English text. English text frequently doesn’t contain balanced quotes, and it would be very annoying if a comment end was ignored after an odd number of apostrophes.
  3. Modern style in most programming languages avoids block comments entirely. rustfmt removes all block comments from your code by default. Usual practice for temporarily disabling blocks of code is to turn all lines into line comments; many editors have a command to toggle comments on all lines in the selected region.

#4

While Rust probably won’t change the comment syntax anytime soon, Lua does have an interesting solution to the problem

-- A block comment is declared as:
-- ---------

--[[
    block comment.

    more stuff.
]]

-- Nested block comments have one or more equals sign between the double 
-- brackets.
-- --------

--[=[

]=]

-- You can have any number of equals signs between the two double-brackets.
-- So this is valid:
-- ----------

--[===================================[
    Still a comment!

    Incredibly fancy.
]===================================]

-- These are nested block comments.
-- ----------

--[===[

    --[==[

        --[=[

            --[[
                
            ]]

        ]=]

    ]==]

]===]

The program is valid and won’t output anything (because it’s all comments.) You can test on the Lua Demo Site