[cfe-dev] c++ templates

Doug Gregor doug.gregor at gmail.com
Thu Nov 13 18:25:55 PST 2008


On Thu, Nov 13, 2008 at 12:31 PM, Andrew Sutton
<andrew.n.sutton at gmail.com> wrote:
> I'm working on a set of reverse engineering  tools (as in program analysis,
> not the illegal kind) that operate on template source code and have decided
> to use clang for its implementation. Imagine my surprise when I found out
> that clang doesn't quite support templates. Rather than wait for somebody
> else to build it, I decided I would try to do this myself. How hard can it
> be :)
>
> Attached is a very (VERY) preliminary stab at the beginning of template
> parsing for clang. It's not complete, it doesn't do anything, there's no AST
> stuff, I haven't even considered scopes and name resolution, etc., etc. It
> just recognizes "template <...>". I had hoped to spend some spare time, an
> hour or so a day (whenever possible) to continue working on this. Please
> bear in mind that a) I've never worked on a real compiler before and b) I
> probably don't fully understand the requirements of what I'm working on.
>
> I hope this is an adequate start.

Welcome to Clang :)

You certainly picked off a rather big piece of C++, eh? I have some
comments on your patch:

Index: test/Parser/cxx/temp/parse-err-1.cpp
Index: test/Parser/cxx/temp/parse-err-2.cpp
[etc]

Please collapse all of these parser tests into a single .cpp file
(say, test/Parser/cxx-template-decl.cpp). We like to minimize the
number of test files (within reason!) because it keeps testing fast.

 Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
   switch (Tok.getKind()) {
+  case tok::kw_export:
+  case tok::kw_template:
+    // TODO There's also the case of 'export template'. Can I look ahead?
+    return ParseTemplateDeclaration(Context);

You get look ahead with NextToken(). However, you don't need to do
that here. "export" only shows up in one place in the C++ grammar, and
always followed by "template".

+
+#include <iostream>
+

I know it's just for debugging, but we're moving away from using
iostreams for anything in Clang.

+    // For some reason, this is generating a compiler error when parsing the
+    // declaration. Apparently, ParseDeclaration doesn't want to match a
+    // function-definition, but will match a function declaration. Odd..
+    return ParseDeclaration(Context);

I think you want ParseDeclarationOrFunctionDefinition, at least for
now. We'll need to tweak the parsing a little bit to restrict it to
parsing only a single declaration when inside a template-declaration,
which might mean we want a different function to handle this case.

Your patch is a step in the right direction.

  - Doug



More information about the cfe-dev mailing list