What is the usage of Nested comments in some programming languages? - programming-languages

Why nested comments use by some programming languages such as MATLAB ,I just want to know usage of this kind comments in a program and what are the advantages we can gain by using this nested comments ?

The answer is nested comments allows commented-out code that contains comments itself
example in C++ has block comments delimited by /../ that can span multiple lines and line comments delimited by //.

Usually, coding standards for a particular project or program have rules about which comment style to use when; a common convention is to use block comments (/* */) for method and class documentation, and inline comments (//) for remarks inside method bodies and such, e.g.:
/**
* Helper class to store Foo objects inside a bar.
*/
public class Foobar {
/**
* Stores a Foo in this Foobar's bar, unless the bar already contains
* an equivalent Foo.
* Returns the number of Foos added (always 0 or 1).
*/
public int storeFoo(Foo foo) {
// Don't add a foo we already have!
if (this.bar.contains(foo)) {
return 0;
}
// OK, we don't have this foo yet, so we'll add it.
this.bar.append(foo);
return 1;
}
}
If someone wants to temporarily disable entire methods or classes in the above program.It's very helpful, if that language allows nested comments.

You can use comments...:
to temporally disable some lines of code.
as titles for sections.
to comment each line.
to add some notations or comments on other comments.
to send macro orders.
And you can mix all of them. That's why we need different ways to mark comments and create nested comments.

Good old Turbo Pascal aka Borland Pascal allows multi-line comments either with curly braces { } or with parenthesis star (* *), which nest independently of one another even though multi-line comments in the same style do not nest.
A good workaround from my old work place was use of typical brace { } comments for all informational comments and specialized use of the less common parenthesis star (* *) only to comment out code. Marking the middle lines of commented out code with something like ** is still a decent idea, and macros can be used to achieve this in programmer editors
function ComputeCost(var x : longint);
{ Wide version: Apply discounts to raw price.}
(* CODE GRAVEYARD!
** function ComputeCost(var x : integer);
** {Apply discounts to raw price.}
*)
Minimalists will always discount the need for nested comments by saying that C style languages allow constructs like #ifdef SOMETHING or the elegantly short #if 0 to disable code. True minimalists want old code removed completely and say version control takes the place of keeping old code. A good counter is that commented out code together with programmer editors with folding support, e.g. Vim, allows visually stepping over dead code while keeping it for reference.

I feel that nested comments are not necessary! In general a comment is omitted by the compiler so comments serve a main purpose for indicating the programmer what he had done or a new programmer to know the flow of the program..why unnecessarily nest comments..just an indication that can be without nesting.. eg:
for(;;)
{
if()
{
}
}/* a loop with an if condition*/
**need not be as**
/*a loop/*if condition*/for n times*/

Related

Finding the start of an expression when the end of the previous one is difficult to express

I've got a file format that looks a little like this:
blockA {
uniqueName42 -> uniqueName aWord1 anotherWord "Some text"
anotherUniqueName -> uniqueName23 aWord2
blockB {
thing -> anotherThing
}
}
Lots more blocks with arbitrary nesting levels.
The lines with the arrow in them define relationships between two things. Each relationship has some optional metadata (multi-word quoted or single word unquoted).
The challenge I'm having is that because the there can be an arbitrary number of metadata items in a relationship my parser is treating anotherUniqueName as a metadata item from the first relationship rather than the start of the second relationship.
You can see this in the image below. The parser is only recognising one relationshipDeclaration when a second should start with StringLiteral: anotherUniqueName
The parser looks a bit like this:
block
: BLOCK LBRACE relationshipDeclaration* RBRACE
;
relationshipDeclaration
: StringLiteral? ARROW StringLiteral StringLiteral*
;
I'm hoping to avoid lexical modes because the fact that these relationships can appear almost anywhere in the file will leave me up to my eyes in NL+ :-(
Would appreciate any ideas on what options I have. Is there a way to look ahead, spot the '->', for example?
Thanks a million.
Your example certainly looks like the NL is what signals the end of a relationshipDeclaration.
If that's the case, then you'll need NLs to be tokens available to your parse rules so the parser can know recognize the end.
As you've alluded to, you could potentially use -> to trigger a different Lexer Mode and generate different tokens for content between the -> and the NL and then use those tokens in your parse rule for relationshipDeclaration.
If it's as simple as your snippet indicates, then just capturing RD_StringLiteral tokens in that lexical mode, would probably be easier to deal with than handling all the places you might need to allow for NL. This would be pretty simple as Lexer modes go.
(BTW you can use x+ to get the same effect as x x*)
relationshipDeclaration
: StringLiteral? ARROW RD_StringLiteral+
;
I don't think there's a third option for dealing with this.

Stick with 2 layouts only when pretty printing

I'm pretty-printing a C++ method declaration and I want arguments list to be rendered in a compact form if it fits the line:
void method(MyLongClassName& instance, const MyClass& c);
or to be formatted in columns if it doesn't:
void method( MyLongClassName& instance,
const MyClass& c,
int counter);
all other layouts I want to eliminate from consideration.
It seems to be simple neither with wl-pprint nor with pretty, if not hacking the sources.
Any ideas?
A solution to a more general problem how to choose a layout that fits to a single line or, if none, use a substitute can be found here: Optional spaces and multiple alternatives in wl-pprint-extras

Ternary operator should not be used on a single line in Node.js. Why?

Consider the following sample codes:
1.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)
? 'yes'
: 'no';
console.log(IsAdminUser);
2.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)?'yes': 'no';
console.log(IsAdminUser);
The 2nd sample I am very comfortable with & I code in that style, but it was told that its wrong way of doing without any supportive reasons.
Why is it recommended not to use a single line ternary operator in Node.js?
Can anyone put some light on the reason why it is so?
Advance Thanks for great help.
With all coding standards, they are generally for readability and maintainability. My guess is the author finds it more readable on separate lines. The compiler / interpreter for your language will handle it all the same. As long as you / your project have a set standard and stick to it, you'll be fine. I recommend that the standards be worked on or at least reviewed by everyone on the project before casting them in stone. I think that if you're breaking it up on separate lines like that, you may as well define an if/else conditional block and use that.
Be wary of coding standards rules that do not have a justification.
Personally, I do not like the ternary operator as it feels unnatural to me and I always have to read the line a few times to understand what it's doing. I find separate if/else blocks easier for me to read. Personal preference of course.
It is in fact wrong to put the ? on a new line; even though it doesn’t hurt in practice.
The reason is a JS feature called “Automatic Semicolon Insertion”. When a var statement ends with a newline (without a trailing comma, which would indicate that more declarations are to follow), your JS interpreter should automatically insert a semicolon.
This semicolon would have the effect that IsAdminUser is assigned a boolean value (namely the result of User.Privileges == AdminPrivileges). After that, a new (invalid) expression would start with the question mark of what you think is a ternary operator.
As mentioned, most JS interpreters are smart enough to recognize that you have a newline where you shouldn’t have one, and implicitely fix your ternary operator. And, when minifying your script, the newline is removed anyway.
So, no problem in practice, but you’re relying on an implicit fix of common JS engines. It’s better to write the ternary operator like this:
var foo = bar ? "yes" : "no";
Or, for larger expressions:
var foo = bar ?
"The operation was successful" : "The operation has failed.";
Or even:
var foo = bar ?
"Congratulations, the operation was a total success!" :
"Oh, no! The operation has horribly failed!";
I completely disagree with the person who made this recommendation. The ternary operator is a standard feature of all 'C' style languages (C,C++,Java,C#,Javascript etc.), and most developers who code in these languages are completely comfortable with the single line version.
The first version just looks weird to me. If I was maintaining code and saw this, I would correct it back to a single line.
If you want verbose, use if-else. If you want neat and compact use a ternary.
My guess is the person who made this recommendation simply wasn't very familiar with the operator, so found it confusing.
Because it's easier on the eye and easier to read. It's much easier to see what your first snippet is doing at a glance - I don't even have to read to the end of a line. I can simply look at one spot and immediately know what values IsAdminUser will have for what conditions. Much the same reason as why you wouldn't write an entire if/else block on one line.
Remember that these are style conventions and are not necessarily backed up by objective (or technical) reasoning.
The reason for having ? and : on separate lines is so that it's easier to figure out what changed if your source control has a line-by-line comparison.
If you've just changed the stuff between the ? and : and everything is on a single line, the entire line can be marked as changed (based on your comparison tool).

groovy: use brackets on method calls or not?

this is a fairly general question about whether people should be using brackets on method calls that take parameters or not.
i.e.
def someFunc(def p) {
...
}
then calling:
someFunc "abc"
vs...
someFunc("abc")
Is this just a question of consistency, or is there specific use cases for each?
It's primarily a question of consistency and readability, but note that Groovy won't always let you get away with omitting parentheses. For one, you can't omit parentheses in nested method calls:
def foo(n) { n }
println foo 1 // won't work
See the section entitled "Omitting parentheses" in the Style guide.
There's no specific case where you must remove them, you can always use them. It's just prettier to leave them out.
There are cases where you can't do that (where you could confuse a list/map parameter with a subscript operator for instance, nested calls, or when the statement is an assignment), but the general rule is that the outmost call can have no parenthesis if there is no ambiguity.
(deleted several lines, as I've just received notification that there is a post already with that info)
Groovy 1.8 will allow even more cases to omit parenthesis, you can check them out at
http://groovyconsole.appspot.com/script/355001
"an empty pair of parentheses is just useless syntactical noise!"
It seems to me that they are encouraging you to use parenthesis when they serve a purpose, but omit them when they are just "noise"

lexer/parser ambiguity

How does a lexer solve this ambiguity?
/*/*/
How is it that it doesn't just say, oh yeah, that's the begining of a multi-line comment, followed by another multi-line comment.
Wouldn't a greedy lexer just return the following tokens?
/*
/*
/
I'm in the midst of writing a shift-reduce parser for CSS and yet this simple comment thing is in my way. You can read this question if you wan't some more background information.
UPDATE
Sorry for leaving this out in the first place. I'm planning to add extensions to the CSS language in this form /* # func ( args, ... ) */ but I don't want to confuse an editor which understands CSS but not this extension comment of mine. That's why the lexer just can't ignore comments.
One way to do it is for the lexer to enter a different internal state on encountering the first /*. For example, flex calls these "start conditions" (matching C-style comments is one of the examples on that page).
The simplest way would probably be to lex the comment as one single token - that is, don't emit a "START COMMENT" token, but instead continue reading in input until you can emit a "COMMENT BLOCK" token that includes the entire /*(anything)*/ bit.
Since comments are not relevant to the actual parsing of executable code, it's fine for them to basically be stripped out by the lexer (or at least, clumped into a single token). You don't care about token matches within a comment.
In most languages, this is not ambiguous: the first slash and asterix are consumed to produce the "start of multi-line comment" token. It is followed by a slash which is plain "content" within the comment and finally the last two characters are the "end of multi-line comment" token.
Since the first 2 characters are consumed, the first asterix cannot also be used to produce an end of comment token. I just noted that it could produce a second "start of comment" token... oops, that could be a problem, depending on the amount of context is available for the parser.
I speak here of tokens, assuming a parser-level handling of the comments. But the same applies to a lexer, whereby the underlying rule is to start with '/*' and then not stop till '*/' is found. Effectively, a lexer-level handling of the whole comment wouldn't be confused by the second "start of comment".
Since CSS does not support nested comments, your example would typically parse into a single token, COMMENT.
That is, the lexer would see /* as a start-comment marker and then consume everything up to and including a */ sequence.
Use the regexp's algorithm, search from the beginning of the string working way back to the current location.
if (chars[currentLocation] == '/' and chars[currentLocation - 1] == '*') {
for (int i = currentLocation - 2; i >= 0; i --) {
if (chars[i] == '/' && chars[i + 1] == '*') {
// .......
}
}
}
It's like applying the regexp /\*([^\*]|\*[^\/])\*/ greedy and bottom-up.
One way to solve this would be to have your lexer return:
/
*
/
*
/
And have your parser deal with it from there. That's what I'd probably do for most programming languages, as the /'s and *'s can also be used for multiplication and other such things, which are all too complicated for the lexer to worry about. The lexer should really just be returning elementary symbols.
If what the token is starts to depend too much on context, what you're looking for may very well be a simpler token.
That being said, CSS is not a programming language so /'s and *'s can't be overloaded. Really afaik they can't be used for anything else other than comments. So I'd be very tempted to just pass the whole thing as a comment token unless you have a good reason not to: /\*.*\*/

Resources