Monday, February 21, 2011

Re: C syntax, and spurious semicolons

On 22/02/11 1:23 AM, Hugh Sasse wrote:
> I've been assisting a colleague with their C code, and he has
> learned to add semicolons at the end of statements too well. His
> current favourite mistake is to write
> if (expression == value);
> {
> do_something();
> };

O nooo!!!

> I frequently miss the trailing semicolon on the first line. So I
> was wondering if it would make sense to modify the C syntax file to
> highlight
> if (expr);
> such that the semicolon shows up as an error. Clearly it is a legal
> null statement, and so is syntactically correct. But if one only
> wanted the expr for its side effects, one would not need to put it
> in an if. To do this because one is only using the else part is
> poor communication with other programmers.

I agree nobody should ever do this, even though it's valid.

> Is there a good reason not to change the syntax file? Otherwise,
> can anyone suggest a patch: my skills in this area are suboptimal,
> as I don't change syntax files very often.

It's a relatively complicated change, because the syntax file currently
doesn't recognise the if as a construct; it only recognises if as a
keyword and treats the parentheses just as any other set of parentheses.

This code seems to work for me to get it to recognise the construct and
call the empty-statement semi-colon an error; it also highlights the
parentheses of the if as a keyword, as a side-effect. You can put it in
~/.vim/after/syntax/c.vim (or on Windows,
$HOME/vimfiles/after/syntax/c.vim) and it should work.

syn clear cConditional
syn keyword cConditional else switch
syn region cIf matchgroup=cConditional start=+if\_s*(+ end=+)\_s*\ze[^;)]+
contains=ALLBUT,@cParenGroup,cCppParen,cCppString,@Spell skipwhite skipnl
skipempty nextgroup=cSemiError
syn match cSemiError contained ";"
hi link cSemiError cParenError

Not sure that it's a good idea for the distributed Vim C syntax file,
though. It may slow down the matching, possibly, and there may be a
bunch of corner cases that don't work so well, and other usability
glitches while you're writing code (before the syntax is valid). I guess
it depends if others would find this useful, and whether there are
noticable hassles with it or not. Maybe try it out and get back to us if
you think it would be worth including (Bram is the maintainer of the C
syntax, so he's the person you'd need to convince!).

Ben.

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: