| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 1 | <html> | 
 | 2 | <head> | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 3 | <title>"Clang" CFE Internals Manual</title> | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 4 | <link type="text/css" rel="stylesheet" href="../menu.css" /> | 
 | 5 | <link type="text/css" rel="stylesheet" href="../content.css" /> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 6 | <style type="text/css"> | 
 | 7 | td { | 
 | 8 | 	vertical-align: top; | 
 | 9 | } | 
 | 10 | </style> | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 11 | </head> | 
 | 12 | <body> | 
 | 13 |  | 
 | 14 | <!--#include virtual="../menu.html.incl"--> | 
 | 15 |  | 
 | 16 | <div id="content"> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 17 |  | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 18 | <h1>"Clang" CFE Internals Manual</h1> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 19 |  | 
 | 20 | <ul> | 
 | 21 | <li><a href="#intro">Introduction</a></li> | 
 | 22 | <li><a href="#libsystem">LLVM System and Support Libraries</a></li> | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 23 | <li><a href="#libbasic">The Clang 'Basic' Library</a> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 24 |   <ul> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 25 |   <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 26 |   <li><a href="#SourceLocation">The SourceLocation and SourceManager | 
 | 27 |       classes</a></li> | 
 | 28 |   </ul> | 
 | 29 | </li> | 
 | 30 | <li><a href="#liblex">The Lexer and Preprocessor Library</a> | 
 | 31 |   <ul> | 
 | 32 |   <li><a href="#Token">The Token class</a></li> | 
 | 33 |   <li><a href="#Lexer">The Lexer class</a></li> | 
| Chris Lattner | 3932fe0 | 2009-01-06 06:02:08 +0000 | [diff] [blame] | 34 |   <li><a href="#AnnotationToken">Annotation Tokens</a></li> | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 35 |   <li><a href="#TokenLexer">The TokenLexer class</a></li> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 36 |   <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li> | 
 | 37 |   </ul> | 
 | 38 | </li> | 
 | 39 | <li><a href="#libparse">The Parser Library</a> | 
 | 40 |   <ul> | 
 | 41 |   </ul> | 
 | 42 | </li> | 
 | 43 | <li><a href="#libast">The AST Library</a> | 
 | 44 |   <ul> | 
 | 45 |   <li><a href="#Type">The Type class and its subclasses</a></li> | 
 | 46 |   <li><a href="#QualType">The QualType class</a></li> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 47 |   <li><a href="#DeclarationName">Declaration names</a></li> | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 48 |   <li><a href="#DeclContext">Declaration contexts</a> | 
 | 49 |     <ul> | 
 | 50 |       <li><a href="#Redeclarations">Redeclarations and Overloads</a></li> | 
 | 51 |       <li><a href="#LexicalAndSemanticContexts">Lexical and Semantic | 
 | 52 |       Contexts</a></li> | 
 | 53 |       <li><a href="#TransparentContexts">Transparent Declaration Contexts</a></li> | 
 | 54 |       <li><a href="#MultiDeclContext">Multiply-Defined Declaration Contexts</a></li> | 
 | 55 |     </ul> | 
 | 56 |   </li> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 57 |   <li><a href="#CFG">The CFG class</a></li> | 
| Chris Lattner | 7bad199 | 2008-11-16 21:48:07 +0000 | [diff] [blame] | 58 |   <li><a href="#Constants">Constant Folding in the Clang AST</a></li> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 59 |   </ul> | 
 | 60 | </li> | 
 | 61 | </ul> | 
 | 62 |  | 
 | 63 |  | 
 | 64 | <!-- ======================================================================= --> | 
 | 65 | <h2 id="intro">Introduction</h2> | 
 | 66 | <!-- ======================================================================= --> | 
 | 67 |  | 
 | 68 | <p>This document describes some of the more important APIs and internal design | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 69 | decisions made in the Clang C front-end.  The purpose of this document is to | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 70 | both capture some of this high level information and also describe some of the | 
 | 71 | design decisions behind it.  This is meant for people interested in hacking on | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 72 | Clang, not for end-users.  The description below is categorized by | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 73 | libraries, and does not describe any of the clients of the libraries.</p> | 
 | 74 |  | 
 | 75 | <!-- ======================================================================= --> | 
 | 76 | <h2 id="libsystem">LLVM System and Support Libraries</h2> | 
 | 77 | <!-- ======================================================================= --> | 
 | 78 |  | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 79 | <p>The LLVM libsystem library provides the basic Clang system abstraction layer, | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 80 | which is used for file system access.  The LLVM libsupport library provides many | 
 | 81 | underlying libraries and <a  | 
 | 82 | href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>, | 
 | 83 |  including command line option | 
 | 84 | processing and various containers.</p> | 
 | 85 |  | 
 | 86 | <!-- ======================================================================= --> | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 87 | <h2 id="libbasic">The Clang 'Basic' Library</h2> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 88 | <!-- ======================================================================= --> | 
 | 89 |  | 
 | 90 | <p>This library certainly needs a better name.  The 'basic' library contains a | 
 | 91 | number of low-level utilities for tracking and manipulating source buffers, | 
 | 92 | locations within the source buffers, diagnostics, tokens, target abstraction, | 
 | 93 | and information about the subset of the language being compiled for.</p> | 
 | 94 |  | 
 | 95 | <p>Part of this infrastructure is specific to C (such as the TargetInfo class), | 
 | 96 | other parts could be reused for other non-C-based languages (SourceLocation, | 
 | 97 | SourceManager, Diagnostics, FileManager).  When and if there is future demand | 
 | 98 | we can figure out if it makes sense to introduce a new library, move the general | 
 | 99 | classes somewhere else, or introduce some other solution.</p> | 
 | 100 |  | 
 | 101 | <p>We describe the roles of these classes in order of their dependencies.</p> | 
 | 102 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 103 |  | 
 | 104 | <!-- ======================================================================= --> | 
 | 105 | <h3 id="Diagnostics">The Diagnostics Subsystem</h3> | 
 | 106 | <!-- ======================================================================= --> | 
 | 107 |  | 
 | 108 | <p>The Clang Diagnostics subsystem is an important part of how the compiler | 
 | 109 | communicates with the human.  Diagnostics are the warnings and errors produced | 
 | 110 | when the code is incorrect or dubious.  In Clang, each diagnostic produced has | 
 | 111 | (at the minimum) a unique ID, a <a href="#SourceLocation">SourceLocation</a> to | 
 | 112 | "put the caret", an English translation associated with it, and a severity (e.g. | 
 | 113 | <tt>WARNING</tt> or <tt>ERROR</tt>).  They can also optionally include a number | 
 | 114 | of arguments to the dianostic (which fill in "%0"'s in the string) as well as a | 
 | 115 | number of source ranges that related to the diagnostic.</p> | 
 | 116 |  | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 117 | <p>In this section, we'll be giving examples produced by the Clang command line | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 118 | driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many | 
 | 119 | different ways</a> depending on how the DiagnosticClient interface is | 
 | 120 | implemented.  A representative example of a diagonstic is:</p> | 
 | 121 |  | 
 | 122 | <pre> | 
 | 123 | t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float') | 
 | 124 |    <font color="darkgreen">P = (P-42) + Gamma*4;</font> | 
 | 125 |        <font color="blue">~~~~~~ ^ ~~~~~~~</font> | 
 | 126 | </pre> | 
 | 127 |  | 
 | 128 | <p>In this example, you can see the English translation, the severity (error), | 
 | 129 | you can see the source location (the caret ("^") and file/line/column info), | 
 | 130 | the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex | 
 | 131 | float").  You'll have to believe me that there is a unique ID backing the | 
 | 132 | diagnostic :).</p> | 
 | 133 |  | 
 | 134 | <p>Getting all of this to happen has several steps and involves many moving | 
 | 135 | pieces, this section describes them and talks about best practices when adding | 
 | 136 | a new diagnostic.</p> | 
 | 137 |  | 
 | 138 | <!-- ============================ --> | 
 | 139 | <h4>The DiagnosticKinds.def file</h4> | 
 | 140 | <!-- ============================ --> | 
 | 141 |  | 
 | 142 | <p>Diagnostics are created by adding an entry to the <tt><a | 
 | 143 | href="http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def" | 
 | 144 | >DiagnosticKinds.def</a></tt> file.  This file encodes the unique ID of the  | 
 | 145 | diagnostic (as an enum, the first argument), the severity of the diagnostic | 
 | 146 | (second argument) and the English translation + format string.</p> | 
 | 147 |  | 
 | 148 | <p>There is little sanity with the naming of the unique ID's right now.  Some | 
 | 149 | start with err_, warn_, ext_ to encode the severity into the name.  Since the | 
 | 150 | enum is referenced in the C++ code that produces the diagnostic, it is somewhat | 
 | 151 | useful for it to be reasonably short.</p> | 
 | 152 |  | 
 | 153 | <p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>, | 
 | 154 | <tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}.  The | 
 | 155 | <tt>ERROR</tt> severity is used for diagnostics indicating the program is never | 
 | 156 | acceptable under any circumstances.  When an error is emitted, the AST for the | 
 | 157 | input code may not be fully built.  The <tt>EXTENSION</tt> and <tt>EXTWARN</tt> | 
 | 158 | severities are used for extensions to the language that Clang accepts.  This | 
 | 159 | means that Clang fully understands and can represent them in the AST, but we | 
 | 160 | produce diagnostics to tell the user their code is non-portable.  The difference | 
 | 161 | is that the former are ignored by default, and the later warn by default.  The | 
 | 162 | <tt>WARNING</tt> severity is used for constructs that are valid in the currently | 
 | 163 | selected source language but that are dubious in some way.  The <tt>NOTE</tt> | 
 | 164 | level is used to staple more information onto a previous diagnostics.</p> | 
 | 165 |  | 
 | 166 | <p>These <em>severities</em> are mapped into a smaller set (the | 
 | 167 | Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>, | 
| Chris Lattner | 0aad297 | 2009-02-05 22:49:08 +0000 | [diff] [blame] | 168 | <tt>Error</tt>, <tt>Fatal</tt> }) of output <em>levels</em> by the diagnostics | 
 | 169 | subsystem based | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 170 | on various configuration options.  For example, if the user specifies | 
 | 171 | <tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if they specify | 
 | 172 | <tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>.  Clang also internally | 
 | 173 | supports a fully fine grained mapping mechanism that allows you to map any | 
 | 174 | diagnostic that doesn't have <tt>ERRROR</tt> severity to any output level that | 
 | 175 | you want.  This is used to implement options like <tt>-Wunused_macros</tt>, | 
| Chris Lattner | 0aad297 | 2009-02-05 22:49:08 +0000 | [diff] [blame] | 176 | <tt>-Wundef</tt> etc.  Fatal errors are considered so severe that diagnostics | 
 | 177 | that occur after them are supressed as "almost certainly useless".</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 178 |  | 
 | 179 | <!-- ================= --> | 
 | 180 | <h4>The Format String</h4> | 
 | 181 | <!-- ================= --> | 
 | 182 |  | 
 | 183 | <p>The format string for the diagnostic is very simple, but it has some power. | 
 | 184 | It takes the form of a string in English with markers that indicate where and | 
 | 185 | how arguments to the diagnostic are inserted and formatted.  For example, here | 
 | 186 | are some simple format strings:</p> | 
 | 187 |  | 
 | 188 | <pre> | 
 | 189 |   "binary integer literals are an extension" | 
 | 190 |   "format string contains '\\0' within the string body" | 
 | 191 |   "more '<b>%%</b>' conversions than data arguments" | 
| Chris Lattner | 545b368 | 2008-11-23 20:27:13 +0000 | [diff] [blame] | 192 |   "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)" | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 193 |   "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator" | 
 | 194 |        " (has <b>%1</b> parameter<b>%s1</b>)" | 
 | 195 | </pre> | 
 | 196 |  | 
 | 197 | <p>These examples show some important points of format strings.  You can use any | 
 | 198 |    plain ASCII character in the diagnostic string except "%" without a problem, | 
 | 199 |    but these are C strings, so you have to use and be aware of all the C escape | 
 | 200 |    sequences (as in the second example).  If you want to produce a "%" in the | 
 | 201 |    output, use the "%%" escape sequence, like the third diagnostic.  Finally, | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 202 |    Clang uses the "%...[digit]" sequences to specify where and how arguments to | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 203 |    the diagnostic are formatted.</p> | 
 | 204 |     | 
 | 205 | <p>Arguments to the diagnostic are numbered according to how they are specified | 
 | 206 |    by the C++ code that <a href="#producingdiag">produces them</a>, and are | 
 | 207 |    referenced by <tt>%0</tt> .. <tt>%9</tt>.  If you have more than 10 arguments | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 208 |    to your diagnostic, you are doing something wrong :).  Unlike printf, there | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 209 |    is no requirement that arguments to the diagnostic end up in the output in | 
 | 210 |    the same order as they are specified, you could have a format string with | 
 | 211 |    <tt>"%1 %0"</tt> that swaps them, for example.  The text in between the | 
 | 212 |    percent and digit are formatting instructions.  If there are no instructions, | 
 | 213 |    the argument is just turned into a string and substituted in.</p> | 
 | 214 |  | 
 | 215 | <p>Here are some "best practices" for writing the English format string:</p> | 
 | 216 |  | 
 | 217 | <ul> | 
 | 218 | <li>Keep the string short.  It should ideally fit in the 80 column limit of the | 
 | 219 |     <tt>DiagnosticKinds.def</tt> file.  This avoids the diagnostic wrapping when | 
 | 220 |     printed, and forces you to think about the important point you are conveying | 
 | 221 |     with the diagnostic.</li> | 
 | 222 | <li>Take advantage of location information.  The user will be able to see the | 
 | 223 |     line and location of the caret, so you don't need to tell them that the | 
 | 224 |     problem is with the 4th argument to the function: just point to it.</li> | 
 | 225 | <li>Do not capitalize the diagnostic string, and do not end it with a | 
 | 226 |     period.</li> | 
 | 227 | <li>If you need to quote something in the diagnostic string, use single | 
 | 228 |     quotes.</li> | 
 | 229 | </ul> | 
 | 230 |  | 
 | 231 | <p>Diagnostics should never take random English strings as arguments: you | 
 | 232 | shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like | 
 | 233 | <tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing | 
 | 234 | this prevents <a href="translation">translating</a> the Clang diagnostics to | 
 | 235 | other languages (because they'll get random English words in their otherwise | 
 | 236 | localized diagnostic).  The exceptions to this are C/C++ language keywords | 
 | 237 | (e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>).  Note | 
 | 238 | that things like "pointer" and "reference" are not keywords.  On the other | 
 | 239 | hand, you <em>can</em> include anything that comes from the user's source code, | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 240 | including variable names, types, labels, etc.  The 'select' format can be  | 
 | 241 | used to achieve this sort of thing in a localizable way, see below.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 242 |  | 
 | 243 | <!-- ==================================== --> | 
 | 244 | <h4>Formatting a Diagnostic Argument</a></h4> | 
 | 245 | <!-- ==================================== --> | 
 | 246 |  | 
 | 247 | <p>Arguments to diagnostics are fully typed internally, and come from a couple | 
 | 248 | different classes: integers, types, names, and random strings.  Depending on | 
 | 249 | the class of the argument, it can be optionally formatted in different ways. | 
 | 250 | This gives the DiagnosticClient information about what the argument means | 
 | 251 | without requiring it to use a specific presentation (consider this MVC for | 
 | 252 | Clang :).</p> | 
 | 253 |  | 
 | 254 | <p>Here are the different diagnostic argument formats currently supported by | 
 | 255 | Clang:</p> | 
 | 256 |  | 
 | 257 | <table> | 
 | 258 | <tr><td colspan="2"><b>"s" format</b></td></tr> | 
 | 259 | <tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr> | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 260 | <tr><td>Class:</td><td>Integers</td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 261 | <tr><td>Description:</td><td>This is a simple formatter for integers that is | 
 | 262 |     useful when producing English diagnostics.  When the integer is 1, it prints | 
 | 263 |     as nothing.  When the integer is not 1, it prints as "s".  This allows some | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 264 |     simple grammatical forms to be to be handled correctly, and eliminates the | 
 | 265 |     need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 266 |  | 
 | 267 | <tr><td colspan="2"><b>"select" format</b></td></tr> | 
 | 268 | <tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2 | 
 | 269 |      operator"</tt></td></tr> | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 270 | <tr><td>Class:</td><td>Integers</td></tr> | 
| Chris Lattner | cc54334 | 2008-11-22 23:50:47 +0000 | [diff] [blame] | 271 | <tr><td>Description:</td><td>This format specifier is used to merge multiple | 
 | 272 |     related diagnostics together into one common one, without requiring the | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 273 |     difference to be specified as an English string argument.  Instead of | 
| Chris Lattner | cc54334 | 2008-11-22 23:50:47 +0000 | [diff] [blame] | 274 |     specifying the string, the diagnostic gets an integer argument and the | 
 | 275 |     format string selects the numbered option.  In this case, the "%2" value | 
 | 276 |     must be an integer in the range [0..2].  If it is 0, it prints 'unary', if | 
 | 277 |     it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'.  This | 
 | 278 |     allows other language translations to substitute reasonable words (or entire | 
 | 279 |     phrases) based on the semantics of the diagnostic instead of having to do | 
 | 280 |     things textually.</td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 281 |  | 
 | 282 | <tr><td colspan="2"><b>"plural" format</b></td></tr> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 283 | <tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to | 
 | 284 |     your computer"</tt></td></tr> | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 285 | <tr><td>Class:</td><td>Integers</td></tr> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 286 | <tr><td>Description:</td><td><p>This is a formatter for complex plural forms. | 
 | 287 |     It is designed to handle even the requirements of languages with very | 
 | 288 | 	complex plural forms, as many Baltic languages have. The argument consists | 
 | 289 | 	of a series of expression/form pairs, separated by ':', where the first form | 
 | 290 | 	whose expression evaluates to true is the result of the modifier.</p> | 
 | 291 | 	<p>An expression can be empty, in which case it is always true. See the | 
 | 292 | 	example at the top. Otherwise, it is a series of one or more numeric | 
 | 293 | 	conditions, separated by ','. If any condition matches, the expression | 
 | 294 | 	matches. Each numeric condition can take one of three forms.</p> | 
 | 295 | 	<ul> | 
 | 296 | 	    <li>number: A simple decimal number matches if the argument is the same | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 297 | 		as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 298 | 		<li>range: A range in square brackets matches if the argument is within | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 299 | 		the range. Then range is inclusive on both ends. Example: | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 300 | 		<tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li> | 
 | 301 | 		<li>modulo: A modulo operator is followed by a number, and | 
 | 302 |                 equals sign and either a number or a range. The tests are the | 
 | 303 |                 same as for plain | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 304 | 		numbers and ranges, but the argument is taken modulo the number first. | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 305 | 		Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything | 
 | 306 | 		else}1"</tt></li> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 307 | 	</ul> | 
 | 308 | 	<p>The parser is very unforgiving. A syntax error, even whitespace, will | 
 | 309 | 	abort, as will a failure to match the argument against any | 
 | 310 | 	expression.</p></td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 311 |  | 
| Chris Lattner | 077bf5e | 2008-11-24 03:33:13 +0000 | [diff] [blame] | 312 | <tr><td colspan="2"><b>"objcclass" format</b></td></tr> | 
 | 313 | <tr><td>Example:</td><td><tt>"method %objcclass0 not found"</tt></td></tr> | 
 | 314 | <tr><td>Class:</td><td>DeclarationName</td></tr> | 
 | 315 | <tr><td>Description:</td><td><p>This is a simple formatter that indicates the | 
 | 316 |     DeclarationName corresponds to an Objective-C class method selector.  As | 
 | 317 |     such, it prints the selector with a leading '+'.</p></td></tr> | 
 | 318 |  | 
 | 319 | <tr><td colspan="2"><b>"objcinstance" format</b></td></tr> | 
 | 320 | <tr><td>Example:</td><td><tt>"method %objcinstance0 not found"</tt></td></tr> | 
 | 321 | <tr><td>Class:</td><td>DeclarationName</td></tr> | 
 | 322 | <tr><td>Description:</td><td><p>This is a simple formatter that indicates the | 
 | 323 |     DeclarationName corresponds to an Objective-C instance method selector.  As | 
 | 324 |     such, it prints the selector with a leading '-'.</p></td></tr> | 
 | 325 |  | 
| Douglas Gregor | 47b9a1c | 2009-02-04 17:27:36 +0000 | [diff] [blame] | 326 | <tr><td colspan="2"><b>"q" format</b></td></tr> | 
 | 327 | <tr><td>Example:</td><td><tt>"candidate found by name lookup is %q0"</tt></td></tr> | 
 | 328 | <tr><td>Class:</td><td>NamedDecl*</td></tr> | 
 | 329 | <tr><td>Description</td><td><p>This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., "std::vector" rather than "vector".</p></td></tr> | 
 | 330 |      | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 331 | </table> | 
 | 332 |  | 
| Chris Lattner | cc54334 | 2008-11-22 23:50:47 +0000 | [diff] [blame] | 333 | <p>It is really easy to add format specifiers to the Clang diagnostics system, | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 334 | but they should be discussed before they are added.  If you are creating a lot | 
 | 335 | of repetitive diagnostics and/or have an idea for a useful formatter, please | 
 | 336 | bring it up on the cfe-dev mailing list.</p> | 
| Chris Lattner | cc54334 | 2008-11-22 23:50:47 +0000 | [diff] [blame] | 337 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 338 | <!-- ===================================================== --> | 
 | 339 | <h4><a name="#producingdiag">Producing the Diagnostic</a></h4> | 
 | 340 | <!-- ===================================================== --> | 
 | 341 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 342 | <p>Now that you've created the diagnostic in the DiagnosticKinds.def file, you | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 343 | need to write the code that detects the condition in question and emits the | 
 | 344 | new diagnostic.  Various components of Clang (e.g. the preprocessor, Sema, | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 345 | etc) provide a helper function named "Diag".  It creates a diagnostic and | 
 | 346 | accepts the arguments, ranges, and other information that goes along with | 
 | 347 | it.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 348 |  | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 349 | <p>For example, the binary expression error comes from code like this:</p> | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 350 |  | 
 | 351 | <pre> | 
 | 352 |   if (various things that are bad) | 
 | 353 |     Diag(Loc, diag::err_typecheck_invalid_operands) | 
 | 354 |       << lex->getType() << rex->getType() | 
 | 355 |       << lex->getSourceRange() << rex->getSourceRange(); | 
 | 356 | </pre> | 
 | 357 |  | 
 | 358 | <p>This shows that use of the Diag method: they take a location (a <a | 
 | 359 | href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value | 
 | 360 | (which matches the name from DiagnosticKinds.def).  If the diagnostic takes | 
 | 361 | arguments, they are specified with the << operator: the first argument | 
 | 362 | becomes %0, the second becomes %1, etc.  The diagnostic interface allows you to | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame] | 363 | specify arguments of many different types, including <tt>int</tt> and | 
 | 364 | <tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and | 
 | 365 | <tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and | 
 | 366 | <tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc. | 
 | 367 | SourceRanges are also specified with the << operator, but do not have a | 
 | 368 | specific ordering requirement.</p> | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 369 |  | 
 | 370 | <p>As you can see, adding and producing a diagnostic is pretty straightforward. | 
 | 371 | The hard part is deciding exactly what you need to say to help the user, picking | 
 | 372 | a suitable wording, and providing the information needed to format it correctly. | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame] | 373 | The good news is that the call site that issues a diagnostic should be | 
 | 374 | completely independent of how the diagnostic is formatted and in what language | 
 | 375 | it is rendered. | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 376 | </p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 377 |  | 
 | 378 | <!-- ============================================================= --> | 
 | 379 | <h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4> | 
 | 380 | <!-- ============================================================= --> | 
 | 381 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 382 | <p>Once code generates a diagnostic with all of the arguments and the rest of | 
 | 383 | the relevant information, Clang needs to know what to do with it.  As previously | 
 | 384 | mentioned, the diagnostic machinery goes through some filtering to map a | 
 | 385 | severity onto a diagnostic level, then (assuming the diagnostic is not mapped to | 
 | 386 | "<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient | 
 | 387 | interface with the information.</p> | 
 | 388 |  | 
 | 389 | <p>It is possible to implement this interface in many different ways.  For | 
 | 390 | example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns | 
 | 391 | the arguments into strings (according to the various formatting rules), prints | 
 | 392 | out the file/line/column information and the string, then prints out the line of | 
 | 393 | code, the source ranges, and the caret.  However, this behavior isn't required. | 
 | 394 | </p> | 
 | 395 |  | 
 | 396 | <p>Another implementation of the DiagnosticClient interface is the | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 397 | 'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode. | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame] | 398 | Instead of formatting and printing out the diagnostics, this implementation just | 
 | 399 | captures and remembers the diagnostics as they fly by.  Then -verify compares | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 400 | the list of produced diagnostics to the list of expected ones.  If they disagree, | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame] | 401 | it prints out its own output. | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 402 | </p> | 
 | 403 |  | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame] | 404 | <p>There are many other possible implementations of this interface, and this is | 
 | 405 | why we prefer diagnostics to pass down rich structured information in arguments. | 
 | 406 | For example, an HTML output might want declaration names be linkified to where | 
 | 407 | they come from in the source.  Another example is that a GUI might let you click | 
 | 408 | on typedefs to expand them.  This application would want to pass significantly | 
 | 409 | more information about types through to the GUI than a simple flat string.  The | 
 | 410 | interface allows this to happen.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 411 |  | 
 | 412 | <!-- ====================================================== --> | 
 | 413 | <h4><a name="translation">Adding Translations to Clang</a></h4> | 
 | 414 | <!-- ====================================================== --> | 
 | 415 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 416 | <p>Not possible yet!  Diagnostic strings should be written in UTF-8, the client | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame] | 417 | can translate to the relevant code page if needed.  Each translation completely | 
 | 418 | replaces the format string for the diagnostic.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 419 |  | 
 | 420 |  | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 421 | <!-- ======================================================================= --> | 
 | 422 | <h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3> | 
 | 423 | <!-- ======================================================================= --> | 
 | 424 |  | 
 | 425 | <p>Strangely enough, the SourceLocation class represents a location within the | 
 | 426 | source code of the program.  Important design points include:</p> | 
 | 427 |  | 
 | 428 | <ol> | 
 | 429 | <li>sizeof(SourceLocation) must be extremely small, as these are embedded into | 
 | 430 |     many AST nodes and are passed around often.  Currently it is 32 bits.</li> | 
 | 431 | <li>SourceLocation must be a simple value object that can be efficiently | 
 | 432 |     copied.</li> | 
 | 433 | <li>We should be able to represent a source location for any byte of any input | 
 | 434 |     file.  This includes in the middle of tokens, in whitespace, in trigraphs, | 
 | 435 |     etc.</li> | 
 | 436 | <li>A SourceLocation must encode the current #include stack that was active when | 
 | 437 |     the location was processed.  For example, if the location corresponds to a | 
 | 438 |     token, it should contain the set of #includes active when the token was | 
 | 439 |     lexed.  This allows us to print the #include stack for a diagnostic.</li> | 
 | 440 | <li>SourceLocation must be able to describe macro expansions, capturing both | 
 | 441 |     the ultimate instantiation point and the source of the original character | 
 | 442 |     data.</li> | 
 | 443 | </ol> | 
 | 444 |  | 
 | 445 | <p>In practice, the SourceLocation works together with the SourceManager class | 
| Chris Lattner | 18376dd | 2009-01-16 07:00:50 +0000 | [diff] [blame] | 446 | to encode two pieces of information about a location: it's spelling location | 
| Chris Lattner | 88054de | 2009-01-16 07:15:35 +0000 | [diff] [blame] | 447 | and it's instantiation location.  For most tokens, these will be the same.  However, | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 448 | for a macro expansion (or tokens that came from a _Pragma directive) these will | 
 | 449 | describe the location of the characters corresponding to the token and the | 
 | 450 | location where the token was used (i.e. the macro instantiation point or the  | 
 | 451 | location of the _Pragma itself).</p> | 
 | 452 |  | 
| Chris Lattner | 3fcbb89 | 2008-11-23 08:32:53 +0000 | [diff] [blame] | 453 | <p>For efficiency, we only track one level of macro instantiations: if a token was | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 454 | produced by multiple instantiations, we only track the source and ultimate | 
 | 455 | destination.  Though we could track the intermediate instantiation points, this | 
 | 456 | would require extra bookkeeping and no known client would benefit substantially | 
 | 457 | from this.</p> | 
 | 458 |  | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 459 | <p>The Clang front-end inherently depends on the location of a token being | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 460 | tracked correctly.  If it is ever incorrect, the front-end may get confused and | 
 | 461 | die.  The reason for this is that the notion of the 'spelling' of a Token in | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 462 | Clang depends on being able to find the original input characters for the token. | 
| Chris Lattner | 18376dd | 2009-01-16 07:00:50 +0000 | [diff] [blame] | 463 | This concept maps directly to the "spelling location" for the token.</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 464 |  | 
 | 465 | <!-- ======================================================================= --> | 
 | 466 | <h2 id="liblex">The Lexer and Preprocessor Library</h2> | 
 | 467 | <!-- ======================================================================= --> | 
 | 468 |  | 
 | 469 | <p>The Lexer library contains several tightly-connected classes that are involved | 
 | 470 | with the nasty process of lexing and preprocessing C source code.  The main | 
 | 471 | interface to this library for outside clients is the large <a  | 
 | 472 | href="#Preprocessor">Preprocessor</a> class. | 
 | 473 | It contains the various pieces of state that are required to coherently read | 
 | 474 | tokens out of a translation unit.</p> | 
 | 475 |  | 
 | 476 | <p>The core interface to the Preprocessor object (once it is set up) is the | 
 | 477 | Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from | 
 | 478 | the preprocessor stream.  There are two types of token providers that the | 
 | 479 | preprocessor is capable of reading from: a buffer lexer (provided by the <a  | 
 | 480 | href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 481 | href="#TokenLexer">TokenLexer</a> class).   | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 482 |  | 
 | 483 |  | 
 | 484 | <!-- ======================================================================= --> | 
 | 485 | <h3 id="Token">The Token class</h3> | 
 | 486 | <!-- ======================================================================= --> | 
 | 487 |  | 
 | 488 | <p>The Token class is used to represent a single lexed token.  Tokens are | 
 | 489 | intended to be used by the lexer/preprocess and parser libraries, but are not | 
 | 490 | intended to live beyond them (for example, they should not live in the ASTs).<p> | 
 | 491 |  | 
 | 492 | <p>Tokens most often live on the stack (or some other location that is efficient | 
 | 493 | to access) as the parser is running, but occasionally do get buffered up.  For | 
 | 494 | example, macro definitions are stored as a series of tokens, and the C++ | 
| Chris Lattner | 3fcbb89 | 2008-11-23 08:32:53 +0000 | [diff] [blame] | 495 | front-end periodically needs to buffer tokens up for tentative parsing and | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 496 | various pieces of look-ahead.  As such, the size of a Token matter.  On a 32-bit | 
 | 497 | system, sizeof(Token) is currently 16 bytes.</p> | 
 | 498 |  | 
| Chris Lattner | 3932fe0 | 2009-01-06 06:02:08 +0000 | [diff] [blame] | 499 | <p>Tokens occur in two forms: "<a href="#AnnotationToken">Annotation | 
 | 500 | Tokens</a>" and normal tokens.  Normal tokens are those returned by the lexer, | 
 | 501 | annotation tokens represent semantic information and are produced by the parser, | 
 | 502 | replacing normal tokens in the token stream.  Normal tokens contain the | 
 | 503 | following information:</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 504 |  | 
 | 505 | <ul> | 
 | 506 | <li><b>A SourceLocation</b> - This indicates the location of the start of the | 
 | 507 | token.</li> | 
 | 508 |  | 
 | 509 | <li><b>A length</b> - This stores the length of the token as stored in the | 
 | 510 | SourceBuffer.  For tokens that include them, this length includes trigraphs and | 
 | 511 | escaped newlines which are ignored by later phases of the compiler.  By pointing | 
 | 512 | into the original source buffer, it is always possible to get the original | 
 | 513 | spelling of a token completely accurately.</li> | 
 | 514 |  | 
 | 515 | <li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if | 
 | 516 | identifier lookup was enabled when the token was lexed (e.g. the lexer was not | 
 | 517 | reading in 'raw' mode) this contains a pointer to the unique hash value for the | 
 | 518 | identifier.  Because the lookup happens before keyword identification, this | 
 | 519 | field is set even for language keywords like 'for'.</li> | 
 | 520 |  | 
 | 521 | <li><b>TokenKind</b> - This indicates the kind of token as classified by the | 
 | 522 | lexer.  This includes things like <tt>tok::starequal</tt> (for the "*=" | 
 | 523 | operator), <tt>tok::ampamp</tt> for the "&&" token, and keyword values | 
 | 524 | (e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords.  Note  | 
 | 525 | that some tokens can be spelled multiple ways.  For example, C++ supports | 
 | 526 | "operator keywords", where things like "and" are treated exactly like the | 
 | 527 | "&&" operator.  In these cases, the kind value is set to | 
 | 528 | <tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to  | 
 | 529 | consider both forms.  For something that cares about which form is used (e.g. | 
 | 530 | the preprocessor 'stringize' operator) the spelling indicates the original | 
 | 531 | form.</li> | 
 | 532 |  | 
 | 533 | <li><b>Flags</b> - There are currently four flags tracked by the | 
 | 534 | lexer/preprocessor system on a per-token basis: | 
 | 535 |  | 
 | 536 |   <ol> | 
 | 537 |   <li><b>StartOfLine</b> - This was the first token that occurred on its input | 
 | 538 |        source line.</li> | 
 | 539 |   <li><b>LeadingSpace</b> - There was a space character either immediately | 
 | 540 |        before the token or transitively before the token as it was expanded | 
 | 541 |        through a macro.  The definition of this flag is very closely defined by | 
 | 542 |        the stringizing requirements of the preprocessor.</li> | 
 | 543 |   <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to | 
 | 544 |       represent identifier tokens which have macro expansion disabled.  This | 
 | 545 |       prevents them from being considered as candidates for macro expansion ever | 
 | 546 |       in the future.</li> | 
 | 547 |   <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the | 
 | 548 |       token includes a trigraph or escaped newline.  Since this is uncommon, | 
 | 549 |       many pieces of code can fast-path on tokens that did not need cleaning. | 
 | 550 |       </p> | 
 | 551 |    </ol> | 
 | 552 | </li> | 
 | 553 | </ul> | 
 | 554 |  | 
| Chris Lattner | 3932fe0 | 2009-01-06 06:02:08 +0000 | [diff] [blame] | 555 | <p>One interesting (and somewhat unusual) aspect of normal tokens is that they | 
 | 556 | don't contain any semantic information about the lexed value.  For example, if | 
 | 557 | the token was a pp-number token, we do not represent the value of the number | 
 | 558 | that was lexed (this is left for later pieces of code to decide).  Additionally, | 
 | 559 | the lexer library has no notion of typedef names vs variable names: both are | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 560 | returned as identifiers, and the parser is left to decide whether a specific | 
 | 561 | identifier is a typedef or a variable (tracking this requires scope information  | 
| Chris Lattner | 3932fe0 | 2009-01-06 06:02:08 +0000 | [diff] [blame] | 562 | among other things).  The parser can do this translation by replacing tokens | 
 | 563 | returned by the preprocessor with "Annotation Tokens".</p> | 
 | 564 |  | 
 | 565 | <!-- ======================================================================= --> | 
 | 566 | <h3 id="AnnotationToken">Annotation Tokens</h3> | 
 | 567 | <!-- ======================================================================= --> | 
 | 568 |  | 
 | 569 | <p>Annotation Tokens are tokens that are synthesized by the parser and injected | 
 | 570 | into the preprocessor's token stream (replacing existing tokens) to record | 
 | 571 | semantic information found by the parser.  For example, if "foo" is found to be | 
 | 572 | a typedef, the "foo" <tt>tok::identifier</tt> token is replaced with an | 
 | 573 | <tt>tok::annot_typename</tt>.  This is useful for a couple of reasons: 1) this | 
 | 574 | makes it easy to handle qualified type names (e.g. "foo::bar::baz<42>::t") | 
 | 575 | in C++ as a single "token" in the parser. 2) if the parser backtracks, the | 
 | 576 | reparse does not need to redo semantic analysis to determine whether a token | 
 | 577 | sequence is a variable, type, template, etc.</p> | 
 | 578 |  | 
 | 579 | <p>Annotation Tokens are created by the parser and reinjected into the parser's | 
 | 580 | token stream (when backtracking is enabled).  Because they can only exist in | 
 | 581 | tokens that the preprocessor-proper is done with, it doesn't need to keep around | 
 | 582 | flags like "start of line" that the preprocessor uses to do its job. | 
 | 583 | Additionally, an annotation token may "cover" a sequence of preprocessor tokens | 
 | 584 | (e.g. <tt>a::b::c</tt> is five preprocessor tokens).  As such, the valid fields | 
 | 585 | of an annotation token are different than the fields for a normal token (but | 
 | 586 | they are multiplexed into the normal Token fields):</p> | 
 | 587 |  | 
 | 588 | <ul> | 
 | 589 | <li><b>SourceLocation "Location"</b> - The SourceLocation for the annotation | 
 | 590 | token indicates the first token replaced by the annotation token. In the example | 
 | 591 | above, it would be the location of the "a" identifier.</li> | 
 | 592 |  | 
 | 593 | <li><b>SourceLocation "AnnotationEndLoc"</b> - This holds the location of the | 
 | 594 | last token replaced with the annotation token.  In the example above, it would | 
 | 595 | be the location of the "c" identifier.</li> | 
 | 596 |  | 
 | 597 | <li><b>void* "AnnotationValue"</b> - This contains an opaque object that the | 
 | 598 | parser gets from Sema through an Actions module, it is passed around and Sema | 
 | 599 | intepretes it, based on the type of annotation token.</li> | 
 | 600 |  | 
 | 601 | <li><b>TokenKind "Kind"</b> - This indicates the kind of Annotation token this | 
 | 602 | is.  See below for the different valid kinds.</li> | 
 | 603 | </ul> | 
 | 604 |  | 
 | 605 | <p>Annotation tokens currently come in three kinds:</p> | 
 | 606 |  | 
 | 607 | <ol> | 
 | 608 | <li><b>tok::annot_typename</b>: This annotation token represents a | 
 | 609 | resolved typename token that is potentially qualified.  The AnnotationValue | 
| Steve Naroff | b43a50f | 2009-01-28 19:39:02 +0000 | [diff] [blame] | 610 | field contains a pointer returned by Action::getTypeName().  In the case of the | 
| Chris Lattner | 3932fe0 | 2009-01-06 06:02:08 +0000 | [diff] [blame] | 611 | Sema actions module, this is a <tt>Decl*</tt> for the type.</li> | 
 | 612 |  | 
 | 613 | <li><b>tok::annot_cxxscope</b>: This annotation token represents a C++ scope | 
 | 614 | specifier, such as "A::B::".  This corresponds to the grammar productions "::" | 
 | 615 | and ":: [opt] nested-name-specifier".  The AnnotationValue pointer is returned | 
 | 616 | by the Action::ActOnCXXGlobalScopeSpecifier and | 
 | 617 | Action::ActOnCXXNestedNameSpecifier callbacks.  In the case of Sema, this is a | 
 | 618 | <tt>DeclContext*</tt>.</li> | 
 | 619 |  | 
 | 620 | <li><b>tok::annot_template_id</b>: This annotation token represents a C++ | 
 | 621 | template-id such as "foo<int, 4>", which may refer to a function or type | 
 | 622 | depending on whether foo is a function template or class template.  The | 
 | 623 | AnnotationValue pointer is a pointer to a malloc'd TemplateIdAnnotation object. | 
 | 624 | FIXME: I don't think the parsing logic is right for this.  Shouldn't type | 
 | 625 | templates be turned into annot_typename??</li> | 
 | 626 |  | 
 | 627 | </ol> | 
 | 628 |  | 
| Cedric Venet | da76b28 | 2009-01-06 16:22:54 +0000 | [diff] [blame] | 629 | <p>As mentioned above, annotation tokens are not returned by the preprocessor, | 
| Chris Lattner | 3932fe0 | 2009-01-06 06:02:08 +0000 | [diff] [blame] | 630 | they are formed on demand by the parser.  This means that the parser has to be | 
 | 631 | aware of cases where an annotation could occur and form it where appropriate. | 
 | 632 | This is somewhat similar to how the parser handles Translation Phase 6 of C99: | 
 | 633 | String Concatenation (see C99 5.1.1.2).  In the case of string concatenation, | 
 | 634 | the preprocessor just returns distinct tok::string_literal and | 
 | 635 | tok::wide_string_literal tokens and the parser eats a sequence of them wherever | 
 | 636 | the grammar indicates that a string literal can occur.</p> | 
 | 637 |  | 
 | 638 | <p>In order to do this, whenever the parser expects a tok::identifier or | 
 | 639 | tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or | 
 | 640 | TryAnnotateCXXScopeToken methods to form the annotation token.  These methods | 
 | 641 | will maximally form the specified annotation tokens and replace the current | 
 | 642 | token with them, if applicable.  If the current tokens is not valid for an | 
 | 643 | annotation token, it will remain an identifier or :: token.</p> | 
 | 644 |  | 
 | 645 |  | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 646 |  | 
 | 647 | <!-- ======================================================================= --> | 
 | 648 | <h3 id="Lexer">The Lexer class</h3> | 
 | 649 | <!-- ======================================================================= --> | 
 | 650 |  | 
 | 651 | <p>The Lexer class provides the mechanics of lexing tokens out of a source | 
 | 652 | buffer and deciding what they mean.  The Lexer is complicated by the fact that | 
 | 653 | it operates on raw buffers that have not had spelling eliminated (this is a | 
 | 654 | necessity to get decent performance), but this is countered with careful coding | 
 | 655 | as well as standard performance techniques (for example, the comment handling | 
 | 656 | code is vectorized on X86 and PowerPC hosts).</p> | 
 | 657 |  | 
 | 658 | <p>The lexer has a couple of interesting modal features:</p> | 
 | 659 |  | 
 | 660 | <ul> | 
 | 661 | <li>The lexer can operate in 'raw' mode.  This mode has several features that | 
 | 662 |     make it possible to quickly lex the file (e.g. it stops identifier lookup, | 
 | 663 |     doesn't specially handle preprocessor tokens, handles EOF differently, etc). | 
 | 664 |     This mode is used for lexing within an "<tt>#if 0</tt>" block, for | 
 | 665 |     example.</li> | 
 | 666 | <li>The lexer can capture and return comments as tokens.  This is required to | 
 | 667 |     support the -C preprocessor mode, which passes comments through, and is | 
 | 668 |     used by the diagnostic checker to identifier expect-error annotations.</li> | 
 | 669 | <li>The lexer can be in ParsingFilename mode, which happens when preprocessing | 
| Chris Lattner | 8438624 | 2007-09-16 19:25:23 +0000 | [diff] [blame] | 670 |     after reading a #include directive.  This mode changes the parsing of '<' | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 671 |     to return an "angled string" instead of a bunch of tokens for each thing | 
 | 672 |     within the filename.</li> | 
 | 673 | <li>When parsing a preprocessor directive (after "<tt>#</tt>") the | 
 | 674 |     ParsingPreprocessorDirective mode is entered.  This changes the parser to | 
 | 675 |     return EOM at a newline.</li> | 
 | 676 | <li>The Lexer uses a LangOptions object to know whether trigraphs are enabled, | 
 | 677 |     whether C++ or ObjC keywords are recognized, etc.</li> | 
 | 678 | </ul> | 
 | 679 |  | 
 | 680 | <p>In addition to these modes, the lexer keeps track of a couple of other | 
 | 681 |    features that are local to a lexed buffer, which change as the buffer is | 
 | 682 |    lexed:</p> | 
 | 683 |  | 
 | 684 | <ul> | 
 | 685 | <li>The Lexer uses BufferPtr to keep track of the current character being | 
 | 686 |     lexed.</li> | 
 | 687 | <li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token | 
 | 688 |     will start with its "start of line" bit set.</li> | 
 | 689 | <li>The Lexer keeps track of the current #if directives that are active (which | 
 | 690 |     can be nested).</li> | 
 | 691 | <li>The Lexer keeps track of an <a href="#MultipleIncludeOpt"> | 
 | 692 |     MultipleIncludeOpt</a> object, which is used to | 
 | 693 |     detect whether the buffer uses the standard "<tt>#ifndef XX</tt> / | 
 | 694 |     <tt>#define XX</tt>" idiom to prevent multiple inclusion.  If a buffer does, | 
 | 695 |     subsequent includes can be ignored if the XX macro is defined.</li> | 
 | 696 | </ul> | 
 | 697 |  | 
 | 698 | <!-- ======================================================================= --> | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 699 | <h3 id="TokenLexer">The TokenLexer class</h3> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 700 | <!-- ======================================================================= --> | 
 | 701 |  | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 702 | <p>The TokenLexer class is a token provider that returns tokens from a list | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 703 | of tokens that came from somewhere else.  It typically used for two things: 1) | 
 | 704 | returning tokens from a macro definition as it is being expanded 2) returning | 
 | 705 | tokens from an arbitrary buffer of tokens.  The later use is used by _Pragma and | 
 | 706 | will most likely be used to handle unbounded look-ahead for the C++ parser.</p> | 
 | 707 |  | 
 | 708 | <!-- ======================================================================= --> | 
 | 709 | <h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3> | 
 | 710 | <!-- ======================================================================= --> | 
 | 711 |  | 
 | 712 | <p>The MultipleIncludeOpt class implements a really simple little state machine | 
 | 713 | that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>" | 
 | 714 | idiom that people typically use to prevent multiple inclusion of headers.  If a | 
 | 715 | buffer uses this idiom and is subsequently #include'd, the preprocessor can | 
 | 716 | simply check to see whether the guarding condition is defined or not.  If so, | 
 | 717 | the preprocessor can completely ignore the include of the header.</p> | 
 | 718 |  | 
 | 719 |  | 
 | 720 |  | 
 | 721 | <!-- ======================================================================= --> | 
 | 722 | <h2 id="libparse">The Parser Library</h2> | 
 | 723 | <!-- ======================================================================= --> | 
 | 724 |  | 
 | 725 | <!-- ======================================================================= --> | 
 | 726 | <h2 id="libast">The AST Library</h2> | 
 | 727 | <!-- ======================================================================= --> | 
 | 728 |  | 
 | 729 | <!-- ======================================================================= --> | 
 | 730 | <h3 id="Type">The Type class and its subclasses</h3> | 
 | 731 | <!-- ======================================================================= --> | 
 | 732 |  | 
 | 733 | <p>The Type class (and its subclasses) are an important part of the AST.  Types | 
 | 734 | are accessed through the ASTContext class, which implicitly creates and uniques | 
 | 735 | them as they are needed.  Types have a couple of non-obvious features: 1) they | 
 | 736 | do not capture type qualifiers like const or volatile (See | 
 | 737 | <a href="#QualType">QualType</a>), and 2) they implicitly capture typedef | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 738 | information.  Once created, types are immutable (unlike decls).</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 739 |  | 
 | 740 | <p>Typedefs in C make semantic analysis a bit more complex than it would | 
 | 741 | be without them.  The issue is that we want to capture typedef information | 
 | 742 | and represent it in the AST perfectly, but the semantics of operations need to | 
 | 743 | "see through" typedefs.  For example, consider this code:</p> | 
 | 744 |  | 
 | 745 | <code> | 
 | 746 | void func() {<br> | 
| Bill Wendling | 30d1775 | 2007-10-06 01:56:01 +0000 | [diff] [blame] | 747 |   typedef int foo;<br> | 
 | 748 |   foo X, *Y;<br> | 
 | 749 |   typedef foo* bar;<br> | 
 | 750 |   bar Z;<br> | 
 | 751 |   *X;   <i>// error</i><br> | 
 | 752 |   **Y;  <i>// error</i><br> | 
 | 753 |   **Z;  <i>// error</i><br> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 754 | }<br> | 
 | 755 | </code> | 
 | 756 |  | 
 | 757 | <p>The code above is illegal, and thus we expect there to be diagnostics emitted | 
 | 758 | on the annotated lines.  In this example, we expect to get:</p> | 
 | 759 |  | 
 | 760 | <pre> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 761 | <b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 762 | *X; // error | 
 | 763 | <font color="blue">^~</font> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 764 | <b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 765 | **Y; // error | 
 | 766 | <font color="blue">^~~</font> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 767 | <b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b> | 
 | 768 | **Z; // error | 
 | 769 | <font color="blue">^~~</font> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 770 | </pre> | 
 | 771 |  | 
 | 772 | <p>While this example is somewhat silly, it illustrates the point: we want to | 
 | 773 | retain typedef information where possible, so that we can emit errors about | 
 | 774 | "<tt>std::string</tt>" instead of "<tt>std::basic_string<char, std:...</tt>". | 
 | 775 | Doing this requires properly keeping typedef information (for example, the type | 
 | 776 | of "X" is "foo", not "int"), and requires properly propagating it through the | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 777 | various operators (for example, the type of *Y is "foo", not "int").  In order | 
 | 778 | to retain this information, the type of these expressions is an instance of the | 
 | 779 | TypedefType class, which indicates that the type of these expressions is a | 
 | 780 | typedef for foo. | 
 | 781 | </p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 782 |  | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 783 | <p>Representing types like this is great for diagnostics, because the | 
 | 784 | user-specified type is always immediately available.  There are two problems | 
 | 785 | with this: first, various semantic checks need to make judgements about the | 
| Chris Lattner | 33fc68a | 2007-07-31 18:54:50 +0000 | [diff] [blame] | 786 | <em>actual structure</em> of a type, ignoring typdefs.  Second, we need an | 
 | 787 | efficient way to query whether two types are structurally identical to each | 
 | 788 | other, ignoring typedefs.  The solution to both of these problems is the idea of | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 789 | canonical types.</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 790 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 791 | <!-- =============== --> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 792 | <h4>Canonical Types</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 793 | <!-- =============== --> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 794 |  | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 795 | <p>Every instance of the Type class contains a canonical type pointer.  For | 
 | 796 | simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>", | 
 | 797 | "<tt>int**</tt>"), the type just points to itself.  For types that have a | 
 | 798 | typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>", | 
 | 799 | "<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their | 
 | 800 | structurally equivalent type without any typedefs (e.g. "<tt>int</tt>", | 
 | 801 | "<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 802 |  | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 803 | <p>This design provides a constant time operation (dereferencing the canonical | 
 | 804 | type pointer) that gives us access to the structure of types.  For example, | 
 | 805 | we can trivially tell that "bar" and "foo*" are the same type by dereferencing | 
 | 806 | their canonical type pointers and doing a pointer comparison (they both point | 
 | 807 | to the single "<tt>int*</tt>" type).</p> | 
 | 808 |  | 
 | 809 | <p>Canonical types and typedef types bring up some complexities that must be | 
 | 810 | carefully managed.  Specifically, the "isa/cast/dyncast" operators generally | 
 | 811 | shouldn't be used in code that is inspecting the AST.  For example, when type | 
 | 812 | checking the indirection operator (unary '*' on a pointer), the type checker | 
 | 813 | must verify that the operand has a pointer type.  It would not be correct to | 
 | 814 | check that with "<tt>isa<PointerType>(SubExpr->getType())</tt>", | 
 | 815 | because this predicate would fail if the subexpression had a typedef type.</p> | 
 | 816 |  | 
 | 817 | <p>The solution to this problem are a set of helper methods on Type, used to | 
 | 818 | check their properties.  In this case, it would be correct to use | 
 | 819 | "<tt>SubExpr->getType()->isPointerType()</tt>" to do the check.  This | 
 | 820 | predicate will return true if the <em>canonical type is a pointer</em>, which is | 
 | 821 | true any time the type is structurally a pointer type.  The only hard part here | 
 | 822 | is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p> | 
 | 823 |  | 
 | 824 | <p>The second problem we face is how to get access to the pointer type once we | 
 | 825 | know it exists.  To continue the example, the result type of the indirection | 
 | 826 | operator is the pointee type of the subexpression.  In order to determine the | 
 | 827 | type, we need to get the instance of PointerType that best captures the typedef | 
 | 828 | information in the program.  If the type of the expression is literally a | 
 | 829 | PointerType, we can return that, otherwise we have to dig through the | 
 | 830 | typedefs to find the pointer type.  For example, if the subexpression had type | 
 | 831 | "<tt>foo*</tt>", we could return that type as the result.  If the subexpression | 
 | 832 | had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do | 
 | 833 | <em>not</em> want "<tt>int*</tt>").  In order to provide all of this, Type has | 
| Chris Lattner | 11406c1 | 2007-07-31 16:50:51 +0000 | [diff] [blame] | 834 | a getAsPointerType() method that checks whether the type is structurally a | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 835 | PointerType and, if so, returns the best one.  If not, it returns a null | 
 | 836 | pointer.</p> | 
 | 837 |  | 
 | 838 | <p>This structure is somewhat mystical, but after meditating on it, it will  | 
 | 839 | make sense to you :).</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 840 |  | 
 | 841 | <!-- ======================================================================= --> | 
 | 842 | <h3 id="QualType">The QualType class</h3> | 
 | 843 | <!-- ======================================================================= --> | 
 | 844 |  | 
 | 845 | <p>The QualType class is designed as a trivial value class that is small, | 
 | 846 | passed by-value and is efficient to query.  The idea of QualType is that it | 
 | 847 | stores the type qualifiers (const, volatile, restrict) separately from the types | 
 | 848 | themselves: QualType is conceptually a pair of "Type*" and bits for the type | 
 | 849 | qualifiers.</p> | 
 | 850 |  | 
 | 851 | <p>By storing the type qualifiers as bits in the conceptual pair, it is | 
 | 852 | extremely efficient to get the set of qualifiers on a QualType (just return the | 
 | 853 | field of the pair), add a type qualifier (which is a trivial constant-time | 
 | 854 | operation that sets a bit), and remove one or more type qualifiers (just return | 
 | 855 | a QualType with the bitfield set to empty).</p> | 
 | 856 |  | 
 | 857 | <p>Further, because the bits are stored outside of the type itself, we do not | 
 | 858 | need to create duplicates of types with different sets of qualifiers (i.e. there | 
 | 859 | is only a single heap allocated "int" type: "const int" and "volatile const int" | 
 | 860 | both point to the same heap allocated "int" type).  This reduces the heap size | 
 | 861 | used to represent bits and also means we do not have to consider qualifiers when | 
 | 862 | uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p> | 
 | 863 |  | 
 | 864 | <p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in | 
 | 865 | the low bit of the pointer to the Type object.  This means that QualType is | 
 | 866 | exactly the same size as a pointer, and this works fine on any system where | 
 | 867 | malloc'd objects are at least 8 byte aligned.</p> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 868 |  | 
 | 869 | <!-- ======================================================================= --> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 870 | <h3 id="DeclarationName">Declaration names</h3> | 
 | 871 | <!-- ======================================================================= --> | 
 | 872 |  | 
 | 873 | <p>The <tt>DeclarationName</tt> class represents the name of a | 
 | 874 |   declaration in Clang. Declarations in the C family of languages can | 
| Chris Lattner | 3fcbb89 | 2008-11-23 08:32:53 +0000 | [diff] [blame] | 875 |   take several different forms. Most declarations are named by  | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 876 |   simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in | 
 | 877 |   the function declaration <code>f(int x)</code>. In C++, declaration | 
 | 878 |   names can also name class constructors ("<code>Class</code>" | 
 | 879 |   in <code>struct Class { Class(); }</code>), class destructors | 
 | 880 |   ("<code>~Class</code>"), overloaded operator names ("operator+"), | 
 | 881 |   and conversion functions ("<code>operator void const *</code>"). In | 
 | 882 |   Objective-C, declaration names can refer to the names of Objective-C | 
 | 883 |   methods, which involve the method name and the parameters, | 
| Chris Lattner | 3fcbb89 | 2008-11-23 08:32:53 +0000 | [diff] [blame] | 884 |   collectively called a <i>selector</i>, e.g., | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 885 |   "<code>setWidth:height:</code>". Since all of these kinds of | 
| Chris Lattner | 3fcbb89 | 2008-11-23 08:32:53 +0000 | [diff] [blame] | 886 |   entities - variables, functions, Objective-C methods, C++ | 
 | 887 |   constructors, destructors, and operators - are represented as | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 888 |   subclasses of Clang's common <code>NamedDecl</code> | 
 | 889 |   class, <code>DeclarationName</code> is designed to efficiently | 
 | 890 |   represent any kind of name.</p> | 
 | 891 |  | 
 | 892 | <p>Given | 
 | 893 |   a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code> | 
| Douglas Gregor | 2def483 | 2008-11-17 20:34:05 +0000 | [diff] [blame] | 894 |   will produce a value that describes what kind of name <code>N</code> | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 895 |   stores. There are 8 options (all of the names are inside | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 896 |   the <code>DeclarationName</code> class)</p> | 
 | 897 | <dl> | 
 | 898 |   <dt>Identifier</dt> | 
 | 899 |   <dd>The name is a simple | 
 | 900 |   identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the | 
 | 901 |   corresponding <code>IdentifierInfo*</code> pointing to the actual | 
 | 902 |   identifier. Note that C++ overloaded operators (e.g., | 
 | 903 |   "<code>operator+</code>") are represented as special kinds of | 
 | 904 |   identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code> | 
 | 905 |   function to determine whether an identifier is an overloaded | 
 | 906 |   operator name.</dd> | 
 | 907 |  | 
 | 908 |   <dt>ObjCZeroArgSelector, ObjCOneArgSelector, | 
 | 909 |   ObjCMultiArgSelector</dt> | 
 | 910 |   <dd>The name is an Objective-C selector, which can be retrieved as a | 
 | 911 |     <code>Selector</code> instance | 
 | 912 |     via <code>N.getObjCSelector()</code>. The three possible name | 
 | 913 |     kinds for Objective-C reflect an optimization within | 
 | 914 |     the <code>DeclarationName</code> class: both zero- and | 
 | 915 |     one-argument selectors are stored as a | 
 | 916 |     masked <code>IdentifierInfo</code> pointer, and therefore require | 
 | 917 |     very little space, since zero- and one-argument selectors are far | 
 | 918 |     more common than multi-argument selectors (which use a different | 
 | 919 |     structure).</dd> | 
 | 920 |  | 
 | 921 |   <dt>CXXConstructorName</dt> | 
 | 922 |   <dd>The name is a C++ constructor | 
 | 923 |     name. Use <code>N.getCXXNameType()</code> to retrieve | 
 | 924 |     the <a href="#QualType">type</a> that this constructor is meant to | 
 | 925 |     construct. The type is always the canonical type, since all | 
 | 926 |     constructors for a given type have the same name.</dd> | 
 | 927 |  | 
 | 928 |   <dt>CXXDestructorName</dt> | 
 | 929 |   <dd>The name is a C++ destructor | 
 | 930 |     name. Use <code>N.getCXXNameType()</code> to retrieve | 
 | 931 |     the <a href="#QualType">type</a> whose destructor is being | 
 | 932 |     named. This type is always a canonical type.</dd> | 
 | 933 |  | 
 | 934 |   <dt>CXXConversionFunctionName</dt> | 
 | 935 |   <dd>The name is a C++ conversion function. Conversion functions are | 
 | 936 |   named according to the type they convert to, e.g., "<code>operator void | 
 | 937 |       const *</code>". Use <code>N.getCXXNameType()</code> to retrieve | 
 | 938 |   the type that this conversion function converts to. This type is | 
 | 939 |     always a canonical type.</dd> | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 940 |  | 
 | 941 |   <dt>CXXOperatorName</dt> | 
 | 942 |   <dd>The name is a C++ overloaded operator name. Overloaded operators | 
 | 943 |   are named according to their spelling, e.g., | 
 | 944 |   "<code>operator+</code>" or "<code>operator new | 
 | 945 |   []</code>". Use <code>N.getCXXOverloadedOperator()</code> to | 
 | 946 |   retrieve the overloaded operator (a value of | 
 | 947 |     type <code>OverloadedOperatorKind</code>).</dd> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 948 | </dl> | 
 | 949 |  | 
 | 950 | <p><code>DeclarationName</code>s are cheap to create, copy, and | 
 | 951 |   compare. They require only a single pointer's worth of storage in | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 952 |   the common cases (identifiers, zero- | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 953 |   and one-argument Objective-C selectors) and use dense, uniqued | 
 | 954 |   storage for the other kinds of | 
 | 955 |   names. Two <code>DeclarationName</code>s can be compared for | 
 | 956 |   equality (<code>==</code>, <code>!=</code>) using a simple bitwise | 
 | 957 |   comparison, can be ordered | 
 | 958 |   with <code><</code>, <code>></code>, <code><=</code>, | 
 | 959 |   and <code>>=</code> (which provide a lexicographical ordering for | 
 | 960 |   normal identifiers but an unspecified ordering for other kinds of | 
 | 961 |   names), and can be placed into LLVM <code>DenseMap</code>s | 
 | 962 |   and <code>DenseSet</code>s.</p> | 
 | 963 |  | 
 | 964 | <p><code>DeclarationName</code> instances can be created in different | 
 | 965 |   ways depending on what kind of name the instance will store. Normal | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 966 |   identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 967 |   (<code>Selector</code>) can be implicitly converted | 
 | 968 |   to <code>DeclarationName</code>s. Names for C++ constructors, | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 969 |   destructors, conversion functions, and overloaded operators can be retrieved from | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 970 |   the <code>DeclarationNameTable</code>, an instance of which is | 
 | 971 |   available as <code>ASTContext::DeclarationNames</code>. The member | 
 | 972 |   functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>, | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 973 |   <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively, | 
 | 974 |   return <code>DeclarationName</code> instances for the four kinds of | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 975 |   C++ special function names.</p> | 
 | 976 |  | 
 | 977 | <!-- ======================================================================= --> | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 978 | <h3 id="DeclContext">Declaration contexts</h3> | 
 | 979 | <!-- ======================================================================= --> | 
 | 980 | <p>Every declaration in a program exists within some <i>declaration | 
 | 981 |     context</i>, such as a translation unit, namespace, class, or | 
 | 982 |     function. Declaration contexts in Clang are represented by | 
 | 983 |     the <code>DeclContext</code> class, from which the various | 
 | 984 |   declaration-context AST nodes | 
 | 985 |   (<code>TranslationUnitDecl</code>, <code>NamespaceDecl</code>, <code>RecordDecl</code>, <code>FunctionDecl</code>, | 
 | 986 |   etc.) will derive. The <code>DeclContext</code> class provides | 
 | 987 |   several facilities common to each declaration context:</p> | 
 | 988 | <dl> | 
 | 989 |   <dt>Source-centric vs. Semantics-centric View of Declarations</dt> | 
 | 990 |   <dd><code>DeclContext</code> provides two views of the declarations | 
 | 991 |   stored within a declaration context. The source-centric view | 
 | 992 |   accurately represents the program source code as written, including | 
 | 993 |   multiple declarations of entities where present (see the | 
 | 994 |     section <a href="#Redeclarations">Redeclarations and | 
 | 995 |   Overloads</a>), while the semantics-centric view represents the | 
 | 996 |   program semantics. The two views are kept synchronized by semantic | 
 | 997 |   analysis while the ASTs are being constructed.</dd> | 
 | 998 |  | 
 | 999 |   <dt>Storage of declarations within that context</dt> | 
 | 1000 |   <dd>Every declaration context can contain some number of | 
 | 1001 |     declarations. For example, a C++ class (represented | 
 | 1002 |     by <code>RecordDecl</code>) contains various member functions, | 
 | 1003 |     fields, nested types, and so on. All of these declarations will be | 
 | 1004 |     stored within the <code>DeclContext</code>, and one can iterate | 
 | 1005 |     over the declarations via | 
 | 1006 |     [<code>DeclContext::decls_begin()</code>,  | 
 | 1007 |     <code>DeclContext::decls_end()</code>). This mechanism provides | 
 | 1008 |     the source-centric view of declarations in the context.</dd> | 
 | 1009 |  | 
 | 1010 |   <dt>Lookup of declarations within that context</dt> | 
 | 1011 |   <dd>The <code>DeclContext</code> structure provides efficient name | 
 | 1012 |     lookup for names within that declaration context. For example, | 
 | 1013 |     if <code>N</code> is a namespace we can look for the | 
 | 1014 |     name <code>N::f</code> | 
 | 1015 |     using <code>DeclContext::lookup</code>. The lookup itself is | 
 | 1016 |     based on a lazily-constructed array (for declaration contexts | 
 | 1017 |     with a small number of declarations) or hash table (for | 
 | 1018 |     declaration contexts with more declarations). The lookup | 
 | 1019 |     operation provides the semantics-centric view of the declarations | 
 | 1020 |     in the context.</dd> | 
 | 1021 |  | 
 | 1022 |   <dt>Ownership of declarations</dt> | 
 | 1023 |   <dd>The <code>DeclContext</code> owns all of the declarations that | 
 | 1024 |   were declared within its declaration context, and is responsible | 
 | 1025 |   for the management of their memory as well as their | 
 | 1026 |   (de-)serialization.</dd> | 
 | 1027 | </dl> | 
 | 1028 |  | 
| Douglas Gregor | 4afa39d | 2009-01-20 01:17:11 +0000 | [diff] [blame] | 1029 | <p>All declarations are stored within a declaration context, and one | 
 | 1030 |   can query | 
 | 1031 |   information about the context in which each declaration lives. One | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 1032 |   can retrieve the <code>DeclContext</code> that contains a | 
| Douglas Gregor | 4afa39d | 2009-01-20 01:17:11 +0000 | [diff] [blame] | 1033 |   particular <code>Decl</code> | 
 | 1034 |   using <code>Decl::getDeclContext</code>. However, see the | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 1035 |   section <a href="#LexicalAndSemanticContexts">Lexical and Semantic | 
 | 1036 |   Contexts</a> for more information about how to interpret this | 
 | 1037 |   context information.</p> | 
 | 1038 |  | 
 | 1039 | <h4 id="Redeclarations">Redeclarations and Overloads</h4> | 
 | 1040 | <p>Within a translation unit, it is common for an entity to be | 
 | 1041 | declared several times. For example, we might declare a function "f" | 
 | 1042 |   and then later re-declare it as part of an inlined definition:</p> | 
 | 1043 |  | 
 | 1044 | <pre> | 
 | 1045 | void f(int x, int y, int z = 1); | 
 | 1046 |  | 
 | 1047 | inline void f(int x, int y, int z) { /* ... */ } | 
 | 1048 | </pre> | 
 | 1049 |  | 
 | 1050 | <p>The representation of "f" differs in the source-centric and | 
 | 1051 |   semantics-centric views of a declaration context. In the | 
 | 1052 |   source-centric view, all redeclarations will be present, in the | 
 | 1053 |   order they occurred in the source code, making  | 
 | 1054 |     this view suitable for clients that wish to see the structure of | 
 | 1055 |     the source code. In the semantics-centric view, only the most recent "f" | 
 | 1056 |   will be found by the lookup, since it effectively replaces the first | 
 | 1057 |   declaration of "f".</p> | 
 | 1058 |  | 
 | 1059 | <p>In the semantics-centric view, overloading of functions is | 
 | 1060 |   represented explicitly. For example, given two declarations of a | 
 | 1061 |   function "g" that are overloaded, e.g.,</p> | 
 | 1062 | <pre> | 
 | 1063 | void g(); | 
 | 1064 | void g(int); | 
 | 1065 | </pre> | 
 | 1066 | <p>the <code>DeclContext::lookup</code> operation will return | 
 | 1067 |   an <code>OverloadedFunctionDecl</code> that contains both | 
 | 1068 |   declarations of "g". Clients that perform semantic analysis on a | 
 | 1069 |   program that is not concerned with the actual source code will | 
 | 1070 |   primarily use this semantics-centric view.</p> | 
 | 1071 |  | 
 | 1072 | <h4 id="LexicalAndSemanticContexts">Lexical and Semantic Contexts</h4> | 
| Douglas Gregor | 4afa39d | 2009-01-20 01:17:11 +0000 | [diff] [blame] | 1073 | <p>Each declaration has two potentially different | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 1074 |   declaration contexts: a <i>lexical</i> context, which corresponds to | 
 | 1075 |   the source-centric view of the declaration context, and | 
 | 1076 |   a <i>semantic</i> context, which corresponds to the | 
 | 1077 |   semantics-centric view. The lexical context is accessible | 
| Douglas Gregor | 4afa39d | 2009-01-20 01:17:11 +0000 | [diff] [blame] | 1078 |   via <code>Decl::getLexicalDeclContext</code> while the | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 1079 |   semantic context is accessible | 
| Douglas Gregor | 4afa39d | 2009-01-20 01:17:11 +0000 | [diff] [blame] | 1080 |   via <code>Decl::getDeclContext</code>, both of which return | 
| Douglas Gregor | 074149e | 2009-01-05 19:45:36 +0000 | [diff] [blame] | 1081 |   <code>DeclContext</code> pointers. For most declarations, the two | 
 | 1082 |   contexts are identical. For example:</p> | 
 | 1083 |  | 
 | 1084 | <pre> | 
 | 1085 | class X { | 
 | 1086 | public: | 
 | 1087 |   void f(int x); | 
 | 1088 | }; | 
 | 1089 | </pre> | 
 | 1090 |  | 
 | 1091 | <p>Here, the semantic and lexical contexts of <code>X::f</code> are | 
 | 1092 |   the <code>DeclContext</code> associated with the | 
 | 1093 |   class <code>X</code> (itself stored as a <code>RecordDecl</code> AST | 
 | 1094 |   node). However, we can now define <code>X::f</code> out-of-line:</p> | 
 | 1095 |  | 
 | 1096 | <pre> | 
 | 1097 | void X::f(int x = 17) { /* ... */ } | 
 | 1098 | </pre> | 
 | 1099 |  | 
 | 1100 | <p>This definition of has different lexical and semantic | 
 | 1101 |   contexts. The lexical context corresponds to the declaration | 
 | 1102 |   context in which the actual declaration occurred in the source | 
 | 1103 |   code, e.g., the translation unit containing <code>X</code>. Thus, | 
 | 1104 |   this declaration of <code>X::f</code> can be found by traversing | 
 | 1105 |   the declarations provided by | 
 | 1106 |   [<code>decls_begin()</code>, <code>decls_end()</code>) in the | 
 | 1107 |   translation unit.</p> | 
 | 1108 |  | 
 | 1109 | <p>The semantic context of <code>X::f</code> corresponds to the | 
 | 1110 |   class <code>X</code>, since this member function is (semantically) a | 
 | 1111 |   member of <code>X</code>. Lookup of the name <code>f</code> into | 
 | 1112 |   the <code>DeclContext</code> associated with <code>X</code> will | 
 | 1113 |   then return the definition of <code>X::f</code> (including | 
 | 1114 |   information about the default argument).</p> | 
 | 1115 |  | 
 | 1116 | <h4 id="TransparentContexts">Transparent Declaration Contexts</h4> | 
 | 1117 | <p>In C and C++, there are several contexts in which names that are | 
 | 1118 |   logically declared inside another declaration will actually "leak" | 
 | 1119 |   out into the enclosing scope from the perspective of name | 
 | 1120 |   lookup. The most obvious instance of this behavior is in | 
 | 1121 |   enumeration types, e.g.,</p> | 
 | 1122 | <pre> | 
 | 1123 | enum Color { | 
 | 1124 |   Red,  | 
 | 1125 |   Green, | 
 | 1126 |   Blue | 
 | 1127 | }; | 
 | 1128 | </pre> | 
 | 1129 |  | 
 | 1130 | <p>Here, <code>Color</code> is an enumeration, which is a declaration | 
 | 1131 |   context that contains the | 
 | 1132 |   enumerators <code>Red</code>, <code>Green</code>, | 
 | 1133 |   and <code>Blue</code>. Thus, traversing the list of declarations | 
 | 1134 |   contained in the enumeration <code>Color</code> will | 
 | 1135 |   yield <code>Red</code>, <code>Green</code>, | 
 | 1136 |   and <code>Blue</code>. However, outside of the scope | 
 | 1137 |   of <code>Color</code> one can name the enumerator <code>Red</code> | 
 | 1138 |   without qualifying the name, e.g.,</p> | 
 | 1139 |  | 
 | 1140 | <pre> | 
 | 1141 | Color c = Red; | 
 | 1142 | </pre> | 
 | 1143 |  | 
 | 1144 | <p>There are other entities in C++ that provide similar behavior. For | 
 | 1145 |   example, linkage specifications that use curly braces:</p> | 
 | 1146 |  | 
 | 1147 | <pre> | 
 | 1148 | extern "C" { | 
 | 1149 |   void f(int); | 
 | 1150 |   void g(int); | 
 | 1151 | } | 
 | 1152 | // f and g are visible here | 
 | 1153 | </pre> | 
 | 1154 |  | 
 | 1155 | <p>For source-level accuracy, we treat the linkage specification and | 
 | 1156 |   enumeration type as a | 
 | 1157 |   declaration context in which its enclosed declarations ("Red", | 
 | 1158 |   "Green", and "Blue"; "f" and "g") | 
 | 1159 |   are declared. However, these declarations are visible outside of the | 
 | 1160 |   scope of the declaration context.</p> | 
 | 1161 |  | 
 | 1162 | <p>These language features (and several others, described below) have | 
 | 1163 |   roughly the same set of  | 
 | 1164 |   requirements: declarations are declared within a particular lexical | 
 | 1165 |   context, but the declarations are also found via name lookup in | 
 | 1166 |   scopes enclosing the declaration itself. This feature is implemented | 
 | 1167 |   via <i>transparent</i> declaration contexts | 
 | 1168 |   (see <code>DeclContext::isTransparentContext()</code>), whose | 
 | 1169 |   declarations are visible in the nearest enclosing non-transparent | 
 | 1170 |   declaration context. This means that the lexical context of the | 
 | 1171 |   declaration (e.g., an enumerator) will be the | 
 | 1172 |   transparent <code>DeclContext</code> itself, as will the semantic | 
 | 1173 |   context, but the declaration will be visible in every outer context | 
 | 1174 |   up to and including the first non-transparent declaration context (since | 
 | 1175 |   transparent declaration contexts can be nested).</p> | 
 | 1176 |  | 
 | 1177 | <p>The transparent <code>DeclContexts</code> are:</p> | 
 | 1178 | <ul> | 
 | 1179 |   <li>Enumerations (but not C++0x "scoped enumerations"): | 
 | 1180 |     <pre> | 
 | 1181 | enum Color {  | 
 | 1182 |   Red,  | 
 | 1183 |   Green,  | 
 | 1184 |   Blue  | 
 | 1185 | }; | 
 | 1186 | // Red, Green, and Blue are in scope | 
 | 1187 |   </pre></li> | 
 | 1188 |   <li>C++ linkage specifications: | 
 | 1189 |   <pre> | 
 | 1190 | extern "C" { | 
 | 1191 |   void f(int); | 
 | 1192 |   void g(int); | 
 | 1193 | } | 
 | 1194 | // f and g are in scope | 
 | 1195 |   </pre></li> | 
 | 1196 |   <li>Anonymous unions and structs: | 
 | 1197 |     <pre> | 
 | 1198 | struct LookupTable { | 
 | 1199 |   bool IsVector; | 
 | 1200 |   union { | 
 | 1201 |     std::vector<Item> *Vector; | 
 | 1202 |     std::set<Item> *Set; | 
 | 1203 |   }; | 
 | 1204 | }; | 
 | 1205 |  | 
 | 1206 | LookupTable LT; | 
 | 1207 | LT.Vector = 0; // Okay: finds Vector inside the unnamed union | 
 | 1208 |     </pre> | 
 | 1209 |   </li> | 
 | 1210 |   <li>C++0x inline namespaces: | 
 | 1211 | <pre> | 
 | 1212 | namespace mylib { | 
 | 1213 |   inline namespace debug { | 
 | 1214 |     class X; | 
 | 1215 |   } | 
 | 1216 | } | 
 | 1217 | mylib::X *xp; // okay: mylib::X refers to mylib::debug::X | 
 | 1218 | </pre> | 
 | 1219 | </li> | 
 | 1220 | </ul> | 
 | 1221 |  | 
 | 1222 |  | 
 | 1223 | <h4 id="MultiDeclContext">Multiply-Defined Declaration Contexts</h4> | 
 | 1224 | <p>C++ namespaces have the interesting--and, so far, unique--property that  | 
 | 1225 | the namespace can be defined multiple times, and the declarations | 
 | 1226 | provided by each namespace definition are effectively merged (from | 
 | 1227 | the semantic point of view). For example, the following two code | 
 | 1228 | snippets are semantically indistinguishable:</p> | 
 | 1229 | <pre> | 
 | 1230 | // Snippet #1: | 
 | 1231 | namespace N { | 
 | 1232 |   void f(); | 
 | 1233 | } | 
 | 1234 | namespace N { | 
 | 1235 |   void f(int); | 
 | 1236 | } | 
 | 1237 |  | 
 | 1238 | // Snippet #2: | 
 | 1239 | namespace N { | 
 | 1240 |   void f(); | 
 | 1241 |   void f(int); | 
 | 1242 | } | 
 | 1243 | </pre> | 
 | 1244 |  | 
 | 1245 | <p>In Clang's representation, the source-centric view of declaration | 
 | 1246 |   contexts will actually have two separate <code>NamespaceDecl</code> | 
 | 1247 |   nodes in Snippet #1, each of which is a declaration context that | 
 | 1248 |   contains a single declaration of "f". However, the semantics-centric | 
 | 1249 |   view provided by name lookup into the namespace <code>N</code> for | 
 | 1250 |   "f" will return an <code>OverloadedFunctionDecl</code> that contains | 
 | 1251 |   both declarations of "f".</p> | 
 | 1252 |  | 
 | 1253 | <p><code>DeclContext</code> manages multiply-defined declaration | 
 | 1254 |   contexts internally. The | 
 | 1255 |   function <code>DeclContext::getPrimaryContext</code> retrieves the | 
 | 1256 |   "primary" context for a given <code>DeclContext</code> instance, | 
 | 1257 |   which is the <code>DeclContext</code> responsible for maintaining | 
 | 1258 |   the lookup table used for the semantics-centric view. Given the | 
 | 1259 |   primary context, one can follow the chain | 
 | 1260 |   of <code>DeclContext</code> nodes that define additional | 
 | 1261 |   declarations via <code>DeclContext::getNextContext</code>. Note that | 
 | 1262 |   these functions are used internally within the lookup and insertion | 
 | 1263 |   methods of the <code>DeclContext</code>, so the vast majority of | 
 | 1264 |   clients can ignore them.</p> | 
 | 1265 |  | 
 | 1266 | <!-- ======================================================================= --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1267 | <h3 id="CFG">The <tt>CFG</tt> class</h3> | 
 | 1268 | <!-- ======================================================================= --> | 
 | 1269 |  | 
 | 1270 | <p>The <tt>CFG</tt> class is designed to represent a source-level | 
 | 1271 | control-flow graph for a single statement (<tt>Stmt*</tt>).  Typically | 
 | 1272 | instances of <tt>CFG</tt> are constructed for function bodies (usually | 
 | 1273 | an instance of <tt>CompoundStmt</tt>), but can also be instantiated to | 
 | 1274 | represent the control-flow of any class that subclasses <tt>Stmt</tt>, | 
 | 1275 | which includes simple expressions.  Control-flow graphs are especially | 
 | 1276 | useful for performing | 
 | 1277 | <a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow- | 
 | 1278 | or path-sensitive</a> program analyses on a given function.</p> | 
 | 1279 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1280 | <!-- ============ --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1281 | <h4>Basic Blocks</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1282 | <!-- ============ --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1283 |  | 
 | 1284 | <p>Concretely, an instance of <tt>CFG</tt> is a collection of basic | 
 | 1285 | blocks.  Each basic block is an instance of <tt>CFGBlock</tt>, which | 
 | 1286 | simply contains an ordered sequence of <tt>Stmt*</tt> (each referring | 
 | 1287 | to statements in the AST).  The ordering of statements within a block | 
 | 1288 | indicates unconditional flow of control from one statement to the | 
 | 1289 | next.  <a href="#ConditionalControlFlow">Conditional control-flow</a> | 
 | 1290 | is represented using edges between basic blocks.  The statements | 
 | 1291 | within a given <tt>CFGBlock</tt> can be traversed using | 
 | 1292 | the <tt>CFGBlock::*iterator</tt> interface.</p> | 
 | 1293 |  | 
 | 1294 | <p> | 
| Ted Kremenek | 18e17e7 | 2007-10-18 22:50:52 +0000 | [diff] [blame] | 1295 | A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1296 | the control-flow graph it represents.  Each <tt>CFGBlock</tt> within a | 
 | 1297 | CFG is also uniquely numbered (accessible | 
 | 1298 | via <tt>CFGBlock::getBlockID()</tt>).  Currently the number is | 
 | 1299 | based on the ordering the blocks were created, but no assumptions | 
 | 1300 | should be made on how <tt>CFGBlock</tt>s are numbered other than their | 
 | 1301 | numbers are unique and that they are numbered from 0..N-1 (where N is | 
 | 1302 | the number of basic blocks in the CFG).</p> | 
 | 1303 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1304 | <!-- ===================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1305 | <h4>Entry and Exit Blocks</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1306 | <!-- ===================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1307 |  | 
 | 1308 | Each instance of <tt>CFG</tt> contains two special blocks: | 
 | 1309 | an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which | 
 | 1310 | has no incoming edges, and an <i>exit</i> block (accessible | 
 | 1311 | via <tt>CFG::getExit()</tt>), which has no outgoing edges.  Neither | 
 | 1312 | block contains any statements, and they serve the role of providing a | 
 | 1313 | clear entrance and exit for a body of code such as a function body. | 
 | 1314 | The presence of these empty blocks greatly simplifies the | 
 | 1315 | implementation of many analyses built on top of CFGs. | 
 | 1316 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1317 | <!-- ===================================================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1318 | <h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1319 | <!-- ===================================================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1320 |  | 
 | 1321 | <p>Conditional control-flow (such as those induced by if-statements | 
 | 1322 | and loops) is represented as edges between <tt>CFGBlock</tt>s. | 
 | 1323 | Because different C language constructs can induce control-flow, | 
 | 1324 | each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that | 
 | 1325 | represents the <i>terminator</i> of the block.  A terminator is simply | 
 | 1326 | the statement that caused the control-flow, and is used to identify | 
 | 1327 | the nature of the conditional control-flow between blocks.  For | 
 | 1328 | example, in the case of an if-statement, the terminator refers to | 
 | 1329 | the <tt>IfStmt</tt> object in the AST that represented the given | 
 | 1330 | branch.</p> | 
 | 1331 |  | 
 | 1332 | <p>To illustrate, consider the following code example:</p> | 
 | 1333 |  | 
 | 1334 | <code> | 
 | 1335 | int foo(int x) {<br> | 
 | 1336 |   x = x + 1;<br> | 
 | 1337 | <br> | 
 | 1338 |   if (x > 2) x++;<br> | 
 | 1339 |   else {<br> | 
 | 1340 |     x += 2;<br> | 
 | 1341 |     x *= 2;<br> | 
 | 1342 |   }<br> | 
 | 1343 | <br> | 
 | 1344 |   return x;<br> | 
 | 1345 | } | 
 | 1346 | </code> | 
 | 1347 |  | 
 | 1348 | <p>After invoking the parser+semantic analyzer on this code fragment, | 
 | 1349 | the AST of the body of <tt>foo</tt> is referenced by a | 
 | 1350 | single <tt>Stmt*</tt>.  We can then construct an instance | 
 | 1351 | of <tt>CFG</tt> representing the control-flow graph of this function | 
 | 1352 | body by single call to a static class method:</p> | 
 | 1353 |  | 
 | 1354 | <code> | 
 | 1355 |   Stmt* FooBody = ...<br> | 
 | 1356 |   CFG*  FooCFG = <b>CFG::buildCFG</b>(FooBody); | 
 | 1357 | </code> | 
 | 1358 |  | 
 | 1359 | <p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt> | 
 | 1360 | to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no | 
 | 1361 | longer needed.</p> | 
 | 1362 |  | 
 | 1363 | <p>Along with providing an interface to iterate over | 
 | 1364 | its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods | 
 | 1365 | that are useful for debugging and visualizing CFGs.  For example, the | 
 | 1366 | method | 
 | 1367 | <tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to | 
 | 1368 | standard error.  This is especially useful when one is using a | 
 | 1369 | debugger such as gdb.  For example, here is the output | 
 | 1370 | of <tt>FooCFG->dump()</tt>:</p> | 
 | 1371 |  | 
 | 1372 | <code> | 
 | 1373 |  [ B5 (ENTRY) ]<br> | 
 | 1374 |     Predecessors (0):<br> | 
 | 1375 |     Successors (1): B4<br> | 
 | 1376 | <br> | 
 | 1377 |  [ B4 ]<br> | 
 | 1378 |     1: x = x + 1<br> | 
 | 1379 |     2: (x > 2)<br> | 
 | 1380 |     <b>T: if [B4.2]</b><br> | 
 | 1381 |     Predecessors (1): B5<br> | 
 | 1382 |     Successors (2): B3 B2<br> | 
 | 1383 | <br> | 
 | 1384 |  [ B3 ]<br> | 
 | 1385 |     1: x++<br> | 
 | 1386 |     Predecessors (1): B4<br> | 
 | 1387 |     Successors (1): B1<br> | 
 | 1388 | <br> | 
 | 1389 |  [ B2 ]<br> | 
 | 1390 |     1: x += 2<br> | 
 | 1391 |     2: x *= 2<br> | 
 | 1392 |     Predecessors (1): B4<br> | 
 | 1393 |     Successors (1): B1<br> | 
 | 1394 | <br> | 
 | 1395 |  [ B1 ]<br> | 
 | 1396 |     1: return x;<br> | 
 | 1397 |     Predecessors (2): B2 B3<br> | 
 | 1398 |     Successors (1): B0<br> | 
 | 1399 | <br> | 
 | 1400 |  [ B0 (EXIT) ]<br> | 
 | 1401 |     Predecessors (1): B1<br> | 
 | 1402 |     Successors (0): | 
 | 1403 | </code> | 
 | 1404 |  | 
 | 1405 | <p>For each block, the pretty-printed output displays for each block | 
 | 1406 | the number of <i>predecessor</i> blocks (blocks that have outgoing | 
 | 1407 | control-flow to the given block) and <i>successor</i> blocks (blocks | 
 | 1408 | that have control-flow that have incoming control-flow from the given | 
 | 1409 | block).  We can also clearly see the special entry and exit blocks at | 
 | 1410 | the beginning and end of the pretty-printed output.  For the entry | 
 | 1411 | block (block B5), the number of predecessor blocks is 0, while for the | 
 | 1412 | exit block (block B0) the number of successor blocks is 0.</p> | 
 | 1413 |  | 
 | 1414 | <p>The most interesting block here is B4, whose outgoing control-flow | 
 | 1415 | represents the branching caused by the sole if-statement | 
 | 1416 | in <tt>foo</tt>.  Of particular interest is the second statement in | 
 | 1417 | the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed | 
 | 1418 | as <b><tt>if [B4.2]</tt></b>.  The second statement represents the | 
 | 1419 | evaluation of the condition of the if-statement, which occurs before | 
 | 1420 | the actual branching of control-flow.  Within the <tt>CFGBlock</tt> | 
 | 1421 | for B4, the <tt>Stmt*</tt> for the second statement refers to the | 
 | 1422 | actual expression in the AST for <b><tt>(x > 2)</tt></b>.  Thus | 
 | 1423 | pointers to subclasses of <tt>Expr</tt> can appear in the list of | 
 | 1424 | statements in a block, and not just subclasses of <tt>Stmt</tt> that | 
 | 1425 | refer to proper C statements.</p> | 
 | 1426 |  | 
 | 1427 | <p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt> | 
 | 1428 | object in the AST.  The pretty-printer outputs <b><tt>if | 
 | 1429 | [B4.2]</tt></b> because the condition expression of the if-statement | 
 | 1430 | has an actual place in the basic block, and thus the terminator is | 
 | 1431 | essentially | 
 | 1432 | <i>referring</i> to the expression that is the second statement of | 
 | 1433 | block B4 (i.e., B4.2).  In this manner, conditions for control-flow | 
 | 1434 | (which also includes conditions for loops and switch statements) are | 
 | 1435 | hoisted into the actual basic block.</p> | 
 | 1436 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1437 | <!-- ===================== --> | 
 | 1438 | <!-- <h4>Implicit Control-Flow</h4> --> | 
 | 1439 | <!-- ===================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1440 |  | 
 | 1441 | <!-- | 
 | 1442 | <p>A key design principle of the <tt>CFG</tt> class was to not require | 
 | 1443 | any transformations to the AST in order to represent control-flow. | 
 | 1444 | Thus the <tt>CFG</tt> does not perform any "lowering" of the | 
 | 1445 | statements in an AST: loops are not transformed into guarded gotos, | 
 | 1446 | short-circuit operations are not converted to a set of if-statements, | 
 | 1447 | and so on.</p> | 
 | 1448 | --> | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 1449 |  | 
| Chris Lattner | 7bad199 | 2008-11-16 21:48:07 +0000 | [diff] [blame] | 1450 |  | 
 | 1451 | <!-- ======================================================================= --> | 
 | 1452 | <h3 id="Constants">Constant Folding in the Clang AST</h3> | 
 | 1453 | <!-- ======================================================================= --> | 
 | 1454 |  | 
 | 1455 | <p>There are several places where constants and constant folding matter a lot to | 
 | 1456 | the Clang front-end.  First, in general, we prefer the AST to retain the source | 
 | 1457 | code as close to how the user wrote it as possible.  This means that if they | 
 | 1458 | wrote "5+4", we want to keep the addition and two constants in the AST, we don't | 
 | 1459 | want to fold to "9".  This means that constant folding in various ways turns | 
 | 1460 | into a tree walk that needs to handle the various cases.</p> | 
 | 1461 |  | 
 | 1462 | <p>However, there are places in both C and C++ that require constants to be | 
 | 1463 | folded.  For example, the C standard defines what an "integer constant | 
 | 1464 | expression" (i-c-e) is with very precise and specific requirements.  The | 
 | 1465 | language then requires i-c-e's in a lot of places (for example, the size of a | 
 | 1466 | bitfield, the value for a case statement, etc).  For these, we have to be able | 
 | 1467 | to constant fold the constants, to do semantic checks (e.g. verify bitfield size | 
 | 1468 | is non-negative and that case statements aren't duplicated).  We aim for Clang | 
 | 1469 | to be very pedantic about this, diagnosing cases when the code does not use an | 
 | 1470 | i-c-e where one is required, but accepting the code unless running with | 
 | 1471 | <tt>-pedantic-errors</tt>.</p> | 
 | 1472 |  | 
 | 1473 | <p>Things get a little bit more tricky when it comes to compatibility with | 
 | 1474 | real-world source code.  Specifically, GCC has historically accepted a huge | 
 | 1475 | superset of expressions as i-c-e's, and a lot of real world code depends on this | 
 | 1476 | unfortuate accident of history (including, e.g., the glibc system headers).  GCC | 
 | 1477 | accepts anything its "fold" optimizer is capable of reducing to an integer | 
 | 1478 | constant, which means that the definition of what it accepts changes as its | 
 | 1479 | optimizer does.  One example is that GCC accepts things like "case X-X:" even | 
 | 1480 | when X is a variable, because it can fold this to 0.</p> | 
 | 1481 |  | 
 | 1482 | <p>Another issue are how constants interact with the extensions we support, such | 
 | 1483 | as __builtin_constant_p, __builtin_inf, __extension__ and many others.  C99 | 
 | 1484 | obviously does not specify the semantics of any of these extensions, and the | 
 | 1485 | definition of i-c-e does not include them.  However, these extensions are often | 
 | 1486 | used in real code, and we have to have a way to reason about them.</p> | 
 | 1487 |  | 
 | 1488 | <p>Finally, this is not just a problem for semantic analysis.  The code | 
 | 1489 | generator and other clients have to be able to fold constants (e.g. to | 
 | 1490 | initialize global variables) and has to handle a superset of what C99 allows. | 
 | 1491 | Further, these clients can benefit from extended information.  For example, we | 
 | 1492 | know that "foo()||1" always evaluates to true, but we can't replace the | 
 | 1493 | expression with true because it has side effects.</p> | 
 | 1494 |  | 
 | 1495 | <!-- ======================= --> | 
 | 1496 | <h4>Implementation Approach</h4> | 
 | 1497 | <!-- ======================= --> | 
 | 1498 |  | 
 | 1499 | <p>After trying several different approaches, we've finally converged on a | 
 | 1500 | design (Note, at the time of this writing, not all of this has been implemented, | 
 | 1501 | consider this a design goal!).  Our basic approach is to define a single | 
 | 1502 | recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is | 
 | 1503 | implemented in <tt>AST/ExprConstant.cpp</tt>.  Given an expression with 'scalar' | 
 | 1504 | type (integer, fp, complex, or pointer) this method returns the following | 
 | 1505 | information:</p> | 
 | 1506 |  | 
 | 1507 | <ul> | 
 | 1508 | <li>Whether the expression is an integer constant expression, a general | 
 | 1509 |     constant that was folded but has no side effects, a general constant that | 
 | 1510 |     was folded but that does have side effects, or an uncomputable/unfoldable | 
 | 1511 |     value. | 
 | 1512 | </li> | 
 | 1513 | <li>If the expression was computable in any way, this method returns the APValue | 
 | 1514 |     for the result of the expression.</li> | 
 | 1515 | <li>If the expression is not evaluatable at all, this method returns | 
 | 1516 |     information on one of the problems with the expression.  This includes a | 
 | 1517 |     SourceLocation for where the problem is, and a diagnostic ID that explains | 
 | 1518 |     the problem.  The diagnostic should be have ERROR type.</li> | 
 | 1519 | <li>If the expression is not an integer constant expression, this method returns | 
 | 1520 |     information on one of the problems with the expression.  This includes a | 
 | 1521 |     SourceLocation for where the problem is, and a diagnostic ID that explains | 
 | 1522 |     the problem.  The diagnostic should be have EXTENSION type.</li> | 
 | 1523 | </ul> | 
 | 1524 |  | 
 | 1525 | <p>This information gives various clients the flexibility that they want, and we | 
 | 1526 | will eventually have some helper methods for various extensions.  For example, | 
 | 1527 | Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which | 
 | 1528 | calls Evaluate on the expression.  If the expression is not foldable, the error | 
 | 1529 | is emitted, and it would return true.  If the expression is not an i-c-e, the | 
 | 1530 | EXTENSION diagnostic is emitted.  Finally it would return false to indicate that | 
 | 1531 | the AST is ok.</p> | 
 | 1532 |  | 
 | 1533 | <p>Other clients can use the information in other ways, for example, codegen can | 
 | 1534 | just use expressions that are foldable in any way.</p> | 
 | 1535 |  | 
 | 1536 | <!-- ========== --> | 
 | 1537 | <h4>Extensions</h4> | 
 | 1538 | <!-- ========== --> | 
 | 1539 |  | 
| Chris Lattner | 552de0a | 2008-11-23 08:16:56 +0000 | [diff] [blame] | 1540 | <p>This section describes how some of the various extensions Clang supports  | 
| Chris Lattner | 7bad199 | 2008-11-16 21:48:07 +0000 | [diff] [blame] | 1541 | interacts with constant evaluation:</p> | 
 | 1542 |  | 
 | 1543 | <ul> | 
 | 1544 | <li><b><tt>__extension__</tt></b>: The expression form of this extension causes | 
 | 1545 |     any evaluatable subexpression to be accepted as an integer constant | 
 | 1546 |     expression.</li> | 
 | 1547 | <li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer | 
| Chris Lattner | 28daa53 | 2008-12-12 06:55:44 +0000 | [diff] [blame] | 1548 |     constant expression) if the operand is any evaluatable constant.  As a | 
 | 1549 |     special case, if <tt>__builtin_constant_p</tt> is the (potentially | 
 | 1550 |     parenthesized) condition of a conditional operator expression ("?:"), only | 
| Chris Lattner | 42b83dd | 2008-12-12 18:00:51 +0000 | [diff] [blame] | 1551 |     the true side of the conditional operator is considered, and it is evaluated | 
 | 1552 |     with full constant folding.</li> | 
| Chris Lattner | 7bad199 | 2008-11-16 21:48:07 +0000 | [diff] [blame] | 1553 | <li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an | 
 | 1554 |     integer constant expression, but we accept any constant as an "extension of | 
 | 1555 |     an extension".  This only evaluates one operand depending on which way the | 
 | 1556 |     condition evaluates.</li> | 
 | 1557 | <li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer | 
 | 1558 |     constant expression.</li> | 
 | 1559 | <li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a | 
 | 1560 |     floating-point literal.</li> | 
 | 1561 | <li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as | 
 | 1562 |     general constant expressions.</li> | 
 | 1563 | </ul> | 
 | 1564 |  | 
 | 1565 |  | 
 | 1566 |  | 
 | 1567 |  | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 1568 | </div> | 
 | 1569 | </body> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 1570 | </html> |