Patchwork [c++] Fix pr22138

login
register
mail settings
Submitter Shujing Zhao
Date July 1, 2010, 6 a.m.
Message ID <4C2C2EFC.6050605@oracle.com>
Download mbox | patch
Permalink /patch/57473/
State New
Headers show

Comments

Shujing Zhao - July 1, 2010, 6 a.m.
On 07/01/2010 06:05 AM, Jason Merrill wrote:
> I would check that the next token after 'template' is '<', so we don't 
> get this error message for ill-formed code like
> 
>   template f<int>();
> 
> which isn't a template declaration at all, but rather someone trying to 
> get the compiler to treat 'f' as a template name even though there's no 
> f template in scope.
> 
> I agree that the at_*_scope_p issue isn't relevant to this patch.
> 
Thanks. This revision patch is fixed to consider the next token. If 'template' 
is not start template declaration in function body, it would still error 
"expected primary-expression before 'template'" . The above testcase is added.

Tested with bootstrap on i686-pc-linux-gnu. Is it ok?

Regards
Pearly
gcc/cp/
2010-07-01  Shujing Zhao  <pearly.zhao@oracle.com>

	PR c++/22138
	* parser.c (cp_parser_primary_expression): Error if local template is
	declared.

gcc/testsuite/
2010-07-01  Shujing Zhao  <pearly.zhao@oracle.com>
	
	PR c++/22138
	* g++.dg/parse/template25.C: New.
Jason Merrill - July 1, 2010, 1:58 p.m.
OK.

Jason

Patch

Index: cp/parser.c
===================================================================
--- cp/parser.c	(revision 161363)
+++ cp/parser.c	(working copy)
@@ -3754,6 +3754,16 @@  cp_parser_primary_expression (cp_parser 
 	case RID_AT_SELECTOR:
 	  return cp_parser_objc_expression (parser);
 
+	case RID_TEMPLATE:
+	  if (parser->in_function_body
+	      && (cp_lexer_peek_nth_token (parser->lexer, 2)->type
+	      	  == CPP_LESS))
+	    {
+	      error_at (token->location,
+			"a template declaration cannot appear at block scope");
+	      cp_parser_skip_to_end_of_block_or_statement (parser);
+	      return error_mark_node;
+	    }
 	default:
 	  cp_parser_error (parser, "expected primary-expression");
 	  return error_mark_node;
Index: testsuite/g++.dg/parse/template25.C
===================================================================
--- testsuite/g++.dg/parse/template25.C	(revision 0)
+++ testsuite/g++.dg/parse/template25.C	(revision 0)
@@ -0,0 +1,14 @@ 
+// PR c++/22318. Improve diagnostic for local template declaration.
+// { dg-do compile }
+void f(void)
+{
+  template<typename T> class A /* { dg-error "a template declaration cannot appear at block scope" } */
+  {
+  };
+}
+
+void g(void)
+{
+  template f<int>(); /* { dg-error "expected primary-expression" } */
+  /* { dg-error "expected ';'" "" { target *-*-* } 12 } */
+}