blob: 90835307b15ce3c3ca7a4d7a39b7e7fc5f0e6604 [file] [log] [blame]
Bill Wendling2c8293d2012-06-20 02:57:56 +00001.. _coding_standards:
2
3=====================
4LLVM Coding Standards
5=====================
6
7.. contents::
8 :local:
9
10Introduction
11============
12
13This document attempts to describe a few coding standards that are being used in
14the LLVM source tree. Although no coding standards should be regarded as
15absolute requirements to be followed in all instances, coding standards are
16particularly important for large-scale code bases that follow a library-based
17design (like LLVM).
18
19This document intentionally does not prescribe fixed standards for religious
20issues such as brace placement and space usage. For issues like this, follow
21the golden rule:
22
23.. _Golden Rule:
24
25 **If you are extending, enhancing, or bug fixing already implemented code,
26 use the style that is already being used so that the source is uniform and
27 easy to follow.**
28
29Note that some code bases (e.g. ``libc++``) have really good reasons to deviate
30from the coding standards. In the case of ``libc++``, this is because the
31naming and other conventions are dictated by the C++ standard. If you think
32there is a specific good reason to deviate from the standards here, please bring
33it up on the LLVMdev mailing list.
34
35There are some conventions that are not uniformly followed in the code base
36(e.g. the naming convention). This is because they are relatively new, and a
37lot of code was written before they were put in place. Our long term goal is
38for the entire codebase to follow the convention, but we explicitly *do not*
39want patches that do large-scale reformating of existing code. On the other
40hand, it is reasonable to rename the methods of a class if you're about to
41change it in some other way. Just do the reformating as a separate commit from
42the functionality change.
43
44The ultimate goal of these guidelines is the increase readability and
45maintainability of our common source base. If you have suggestions for topics to
46be included, please mail them to `Chris <mailto:sabre@nondot.org>`_.
47
48Mechanical Source Issues
49========================
50
51Source Code Formatting
52----------------------
53
54Commenting
55^^^^^^^^^^
56
57Comments are one critical part of readability and maintainability. Everyone
58knows they should comment their code, and so should you. When writing comments,
59write them as English prose, which means they should use proper capitalization,
60punctuation, etc. Aim to describe what the code is trying to do and why, not
61*how* it does it at a micro level. Here are a few critical things to document:
62
63.. _header file comment:
64
65File Headers
66""""""""""""
67
68Every source file should have a header on it that describes the basic purpose of
69the file. If a file does not have a header, it should not be checked into the
70tree. The standard header looks like this:
71
72.. code-block:: c++
73
74 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
75 //
76 // The LLVM Compiler Infrastructure
77 //
78 // This file is distributed under the University of Illinois Open Source
79 // License. See LICENSE.TXT for details.
80 //
81 //===----------------------------------------------------------------------===//
Michael J. Spencer06d99812012-10-01 19:59:21 +000082 ///
83 /// \file
84 /// \brief This file contains the declaration of the Instruction class, which is
85 /// the base class for all of the VM instructions.
86 ///
Bill Wendling2c8293d2012-06-20 02:57:56 +000087 //===----------------------------------------------------------------------===//
88
89A few things to note about this particular format: The "``-*- C++ -*-``" string
90on the first line is there to tell Emacs that the source file is a C++ file, not
91a C file (Emacs assumes ``.h`` files are C files by default).
92
93.. note::
94
95 This tag is not necessary in ``.cpp`` files. The name of the file is also
96 on the first line, along with a very short description of the purpose of the
97 file. This is important when printing out code and flipping though lots of
98 pages.
99
100The next section in the file is a concise note that defines the license that the
101file is released under. This makes it perfectly clear what terms the source
102code can be distributed under and should not be modified in any way.
103
Michael J. Spencer06d99812012-10-01 19:59:21 +0000104The main body is a ``doxygen`` comment describing the purpose of the file. It
105should have a ``\brief`` command that describes the file in one or two
106sentences. Any additional information should be separated by a blank line. If
107an algorithm is being implemented or something tricky is going on, a reference
108to the paper where it is published should be included, as well as any notes or
109*gotchas* in the code to watch out for.
Bill Wendling2c8293d2012-06-20 02:57:56 +0000110
111Class overviews
112"""""""""""""""
113
114Classes are one fundamental part of a good object oriented design. As such, a
115class definition should have a comment block that explains what the class is
116used for and how it works. Every non-trivial class is expected to have a
117``doxygen`` comment block.
118
119Method information
120""""""""""""""""""
121
122Methods defined in a class (as well as any global functions) should also be
123documented properly. A quick note about what it does and a description of the
124borderline behaviour is all that is necessary here (unless something
125particularly tricky or insidious is going on). The hope is that people can
126figure out how to use your interfaces without reading the code itself.
127
128Good things to talk about here are what happens when something unexpected
129happens: does the method return null? Abort? Format your hard disk?
130
131Comment Formatting
132^^^^^^^^^^^^^^^^^^
133
134In general, prefer C++ style (``//``) comments. They take less space, require
135less typing, don't have nesting problems, etc. There are a few cases when it is
136useful to use C style (``/* */``) comments however:
137
138#. When writing C code: Obviously if you are writing C code, use C style
139 comments.
140
141#. When writing a header file that may be ``#include``\d by a C source file.
142
143#. When writing a source file that is used by a tool that only accepts C style
144 comments.
145
146To comment out a large block of code, use ``#if 0`` and ``#endif``. These nest
147properly and are better behaved in general than C style comments.
148
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +0000149Doxygen Use in Documentation Comments
150^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
151
152Use the ``\file`` command to turn the standard file header into a file-level
153comment.
154
155Include descriptive ``\brief`` paragraphs for all public interfaces (public
156classes, member and non-member functions). Explain API use and purpose in
157``\brief`` paragraphs, don't just restate the information that can be inferred
158from the API name. Put detailed discussion into separate paragraphs.
159
160To refer to parameter names inside a paragraph, use the ``\p name`` command.
161Don't use the ``\arg name`` command since it starts a new paragraph that
162contains documentation for the parameter.
163
164Wrap non-inline code examples in ``\code ... \endcode``.
165
166To document a function parameter, start a new paragraph with the
167``\param name`` command. If the parameter is used as an out or an in/out
168parameter, use the ``\param [out] name`` or ``\param [in,out] name`` command,
169respectively.
170
171To describe function return value, start a new paragraph with the ``\returns``
172command.
173
174A minimal documentation comment:
175
176.. code-block:: c++
177
178 /// \brief Does foo and bar.
179 void fooBar(bool Baz);
180
181A documentation comment that uses all Doxygen features in a preferred way:
182
183.. code-block:: c++
184
185 /// \brief Does foo and bar.
186 ///
187 /// Does not do foo the usual way if \p Baz is true.
188 ///
189 /// Typical usage:
190 /// \code
191 /// fooBar(false, "quux", Res);
192 /// \endcode
193 ///
194 /// \param Quux kind of foo to do.
195 /// \param [out] Result filled with bar sequence on foo success.
196 ///
197 /// \returns true on success.
198 bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result);
199
200Don't duplicate the documentation comment in the header file and in the
201implementation file. Put the documentation comments for public APIs into the
202header file. Documentation comments for private APIs can go to the
203implementation file. In any case, implementation files can include additional
204comments (not necessarily in Doxygen markup) to explain implementation details
205as needed.
206
207Don't duplicate function or class name at the beginning of the comment.
208For humans it is obvious which function or class is being documented;
209automatic documentation processing tools are smart enough to bind the comment
210to the correct declaration.
211
212Wrong:
213
214.. code-block:: c++
215
216 // In Something.h:
217
218 /// Something - An abstraction for some complicated thing.
219 class Something {
220 public:
221 /// fooBar - Does foo and bar.
222 void fooBar();
223 };
224
225 // In Something.cpp:
226
227 /// fooBar - Does foo and bar.
228 void Something::fooBar() { ... }
229
230Correct:
231
232.. code-block:: c++
233
234 // In Something.h:
235
236 /// \brief An abstraction for some complicated thing.
237 class Something {
238 public:
239 /// \brief Does foo and bar.
240 void fooBar();
241 };
242
243 // In Something.cpp:
244
245 // Builds a B-tree in order to do foo. See paper by...
246 void Something::fooBar() { ... }
247
248It is not required to use additional Doxygen features, but sometimes it might
249be a good idea to do so.
250
251Consider:
252
253* adding comments to any narrow namespace containing a collection of
254 related functions or types;
255
256* using top-level groups to organize a collection of related functions at
257 namespace scope where the grouping is smaller than the namespace;
258
259* using member groups and additional comments attached to member
260 groups to organize within a class.
261
262For example:
263
264.. code-block:: c++
265
266 class Something {
267 /// \name Functions that do Foo.
268 /// @{
269 void fooBar();
270 void fooBaz();
271 /// @}
272 ...
273 };
274
Bill Wendling2c8293d2012-06-20 02:57:56 +0000275``#include`` Style
276^^^^^^^^^^^^^^^^^^
277
278Immediately after the `header file comment`_ (and include guards if working on a
279header file), the `minimal list of #includes`_ required by the file should be
280listed. We prefer these ``#include``\s to be listed in this order:
281
282.. _Main Module Header:
283.. _Local/Private Headers:
284
285#. Main Module Header
286#. Local/Private Headers
287#. ``llvm/*``
288#. ``llvm/Analysis/*``
289#. ``llvm/Assembly/*``
290#. ``llvm/Bitcode/*``
291#. ``llvm/CodeGen/*``
292#. ...
293#. ``llvm/Support/*``
294#. ``llvm/Config/*``
295#. System ``#include``\s
296
297and each category should be sorted by name.
298
299The `Main Module Header`_ file applies to ``.cpp`` files which implement an
300interface defined by a ``.h`` file. This ``#include`` should always be included
301**first** regardless of where it lives on the file system. By including a
302header file first in the ``.cpp`` files that implement the interfaces, we ensure
303that the header does not have any hidden dependencies which are not explicitly
304``#include``\d in the header, but should be. It is also a form of documentation
305in the ``.cpp`` file to indicate where the interfaces it implements are defined.
306
307.. _fit into 80 columns:
308
309Source Code Width
310^^^^^^^^^^^^^^^^^
311
312Write your code to fit within 80 columns of text. This helps those of us who
313like to print out code and look at your code in an ``xterm`` without resizing
314it.
315
316The longer answer is that there must be some limit to the width of the code in
317order to reasonably allow developers to have multiple files side-by-side in
318windows on a modest display. If you are going to pick a width limit, it is
319somewhat arbitrary but you might as well pick something standard. Going with 90
320columns (for example) instead of 80 columns wouldn't add any significant value
321and would be detrimental to printing out code. Also many other projects have
322standardized on 80 columns, so some people have already configured their editors
323for it (vs something else, like 90 columns).
324
325This is one of many contentious issues in coding standards, but it is not up for
326debate.
327
328Use Spaces Instead of Tabs
329^^^^^^^^^^^^^^^^^^^^^^^^^^
330
331In all cases, prefer spaces to tabs in source files. People have different
332preferred indentation levels, and different styles of indentation that they
333like; this is fine. What isn't fine is that different editors/viewers expand
334tabs out to different tab stops. This can cause your code to look completely
335unreadable, and it is not worth dealing with.
336
337As always, follow the `Golden Rule`_ above: follow the style of
338existing code if you are modifying and extending it. If you like four spaces of
339indentation, **DO NOT** do that in the middle of a chunk of code with two spaces
340of indentation. Also, do not reindent a whole source file: it makes for
341incredible diffs that are absolutely worthless.
342
343Indent Code Consistently
344^^^^^^^^^^^^^^^^^^^^^^^^
345
346Okay, in your first year of programming you were told that indentation is
347important. If you didn't believe and internalize this then, now is the time.
348Just do it.
349
350Compiler Issues
351---------------
352
353Treat Compiler Warnings Like Errors
354^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
355
356If your code has compiler warnings in it, something is wrong --- you aren't
357casting values correctly, you have "questionable" constructs in your code, or
358you are doing something legitimately wrong. Compiler warnings can cover up
359legitimate errors in output and make dealing with a translation unit difficult.
360
361It is not possible to prevent all warnings from all compilers, nor is it
362desirable. Instead, pick a standard compiler (like ``gcc``) that provides a
363good thorough set of warnings, and stick to it. At least in the case of
364``gcc``, it is possible to work around any spurious errors by changing the
365syntax of the code slightly. For example, a warning that annoys me occurs when
366I write code like this:
367
368.. code-block:: c++
369
370 if (V = getValue()) {
371 ...
372 }
373
374``gcc`` will warn me that I probably want to use the ``==`` operator, and that I
375probably mistyped it. In most cases, I haven't, and I really don't want the
376spurious errors. To fix this particular problem, I rewrite the code like
377this:
378
379.. code-block:: c++
380
381 if ((V = getValue())) {
382 ...
383 }
384
385which shuts ``gcc`` up. Any ``gcc`` warning that annoys you can be fixed by
386massaging the code appropriately.
387
388Write Portable Code
389^^^^^^^^^^^^^^^^^^^
390
391In almost all cases, it is possible and within reason to write completely
392portable code. If there are cases where it isn't possible to write portable
393code, isolate it behind a well defined (and well documented) interface.
394
395In practice, this means that you shouldn't assume much about the host compiler
396(and Visual Studio tends to be the lowest common denominator). If advanced
397features are used, they should only be an implementation detail of a library
398which has a simple exposed API, and preferably be buried in ``libSystem``.
399
400Do not use RTTI or Exceptions
401^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
402
403In an effort to reduce code and executable size, LLVM does not use RTTI
404(e.g. ``dynamic_cast<>;``) or exceptions. These two language features violate
405the general C++ principle of *"you only pay for what you use"*, causing
406executable bloat even if exceptions are never used in the code base, or if RTTI
407is never used for a class. Because of this, we turn them off globally in the
408code.
409
410That said, LLVM does make extensive use of a hand-rolled form of RTTI that use
411templates like `isa<>, cast<>, and dyn_cast<> <ProgrammersManual.html#isa>`_.
412This form of RTTI is opt-in and can be added to any class. It is also
413substantially more efficient than ``dynamic_cast<>``.
414
415.. _static constructor:
416
417Do not use Static Constructors
418^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
419
420Static constructors and destructors (e.g. global variables whose types have a
421constructor or destructor) should not be added to the code base, and should be
422removed wherever possible. Besides `well known problems
423<http://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_ where the order of
424initialization is undefined between globals in different source files, the
425entire concept of static constructors is at odds with the common use case of
426LLVM as a library linked into a larger application.
427
428Consider the use of LLVM as a JIT linked into another application (perhaps for
429`OpenGL, custom languages <http://llvm.org/Users.html>`_, `shaders in movies
430<http://llvm.org/devmtg/2010-11/Gritz-OpenShadingLang.pdf>`_, etc). Due to the
431design of static constructors, they must be executed at startup time of the
432entire application, regardless of whether or how LLVM is used in that larger
433application. There are two problems with this:
434
435* The time to run the static constructors impacts startup time of applications
436 --- a critical time for GUI apps, among others.
437
438* The static constructors cause the app to pull many extra pages of memory off
439 the disk: both the code for the constructor in each ``.o`` file and the small
440 amount of data that gets touched. In addition, touched/dirty pages put more
441 pressure on the VM system on low-memory machines.
442
443We would really like for there to be zero cost for linking in an additional LLVM
444target or other library into an application, but static constructors violate
445this goal.
446
447That said, LLVM unfortunately does contain static constructors. It would be a
448`great project <http://llvm.org/PR11944>`_ for someone to purge all static
449constructors from LLVM, and then enable the ``-Wglobal-constructors`` warning
450flag (when building with Clang) to ensure we do not regress in the future.
451
452Use of ``class`` and ``struct`` Keywords
453^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
454
455In C++, the ``class`` and ``struct`` keywords can be used almost
456interchangeably. The only difference is when they are used to declare a class:
457``class`` makes all members private by default while ``struct`` makes all
458members public by default.
459
460Unfortunately, not all compilers follow the rules and some will generate
461different symbols based on whether ``class`` or ``struct`` was used to declare
462the symbol. This can lead to problems at link time.
463
464So, the rule for LLVM is to always use the ``class`` keyword, unless **all**
465members are public and the type is a C++ `POD
466<http://en.wikipedia.org/wiki/Plain_old_data_structure>`_ type, in which case
467``struct`` is allowed.
468
469Style Issues
470============
471
472The High-Level Issues
473---------------------
474
475A Public Header File **is** a Module
476^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
477
478C++ doesn't do too well in the modularity department. There is no real
479encapsulation or data hiding (unless you use expensive protocol classes), but it
480is what we have to work with. When you write a public header file (in the LLVM
481source tree, they live in the top level "``include``" directory), you are
482defining a module of functionality.
483
484Ideally, modules should be completely independent of each other, and their
485header files should only ``#include`` the absolute minimum number of headers
486possible. A module is not just a class, a function, or a namespace: it's a
487collection of these that defines an interface. This interface may be several
488functions, classes, or data structures, but the important issue is how they work
489together.
490
491In general, a module should be implemented by one or more ``.cpp`` files. Each
492of these ``.cpp`` files should include the header that defines their interface
493first. This ensures that all of the dependences of the module header have been
494properly added to the module header itself, and are not implicit. System
495headers should be included after user headers for a translation unit.
496
497.. _minimal list of #includes:
498
499``#include`` as Little as Possible
500^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
501
502``#include`` hurts compile time performance. Don't do it unless you have to,
503especially in header files.
504
505But wait! Sometimes you need to have the definition of a class to use it, or to
506inherit from it. In these cases go ahead and ``#include`` that header file. Be
507aware however that there are many cases where you don't need to have the full
508definition of a class. If you are using a pointer or reference to a class, you
509don't need the header file. If you are simply returning a class instance from a
510prototyped function or method, you don't need it. In fact, for most cases, you
511simply don't need the definition of a class. And not ``#include``\ing speeds up
512compilation.
513
514It is easy to try to go too overboard on this recommendation, however. You
515**must** include all of the header files that you are using --- you can include
516them either directly or indirectly through another header file. To make sure
517that you don't accidentally forget to include a header file in your module
518header, make sure to include your module header **first** in the implementation
519file (as mentioned above). This way there won't be any hidden dependencies that
520you'll find out about later.
521
522Keep "Internal" Headers Private
523^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
524
525Many modules have a complex implementation that causes them to use more than one
526implementation (``.cpp``) file. It is often tempting to put the internal
527communication interface (helper classes, extra functions, etc) in the public
528module header file. Don't do this!
529
530If you really need to do something like this, put a private header file in the
531same directory as the source files, and include it locally. This ensures that
532your private interface remains private and undisturbed by outsiders.
533
534.. note::
535
536 It's okay to put extra implementation methods in a public class itself. Just
537 make them private (or protected) and all is well.
538
539.. _early exits:
540
541Use Early Exits and ``continue`` to Simplify Code
542^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
543
544When reading code, keep in mind how much state and how many previous decisions
545have to be remembered by the reader to understand a block of code. Aim to
546reduce indentation where possible when it doesn't make it more difficult to
547understand the code. One great way to do this is by making use of early exits
548and the ``continue`` keyword in long loops. As an example of using an early
549exit from a function, consider this "bad" code:
550
551.. code-block:: c++
552
Andrew Tricke9f59882012-09-20 17:02:04 +0000553 Value *doSomething(Instruction *I) {
Bill Wendling2c8293d2012-06-20 02:57:56 +0000554 if (!isa<TerminatorInst>(I) &&
Andrew Tricke9f59882012-09-20 17:02:04 +0000555 I->hasOneUse() && doOtherThing(I)) {
Bill Wendling2c8293d2012-06-20 02:57:56 +0000556 ... some long code ....
557 }
558
559 return 0;
560 }
561
562This code has several problems if the body of the ``'if'`` is large. When
563you're looking at the top of the function, it isn't immediately clear that this
564*only* does interesting things with non-terminator instructions, and only
565applies to things with the other predicates. Second, it is relatively difficult
566to describe (in comments) why these predicates are important because the ``if``
567statement makes it difficult to lay out the comments. Third, when you're deep
568within the body of the code, it is indented an extra level. Finally, when
569reading the top of the function, it isn't clear what the result is if the
570predicate isn't true; you have to read to the end of the function to know that
571it returns null.
572
573It is much preferred to format the code like this:
574
575.. code-block:: c++
576
Andrew Tricke9f59882012-09-20 17:02:04 +0000577 Value *doSomething(Instruction *I) {
Bill Wendling2c8293d2012-06-20 02:57:56 +0000578 // Terminators never need 'something' done to them because ...
579 if (isa<TerminatorInst>(I))
580 return 0;
581
582 // We conservatively avoid transforming instructions with multiple uses
583 // because goats like cheese.
584 if (!I->hasOneUse())
585 return 0;
586
587 // This is really just here for example.
Andrew Tricke9f59882012-09-20 17:02:04 +0000588 if (!doOtherThing(I))
Bill Wendling2c8293d2012-06-20 02:57:56 +0000589 return 0;
590
591 ... some long code ....
592 }
593
594This fixes these problems. A similar problem frequently happens in ``for``
595loops. A silly example is something like this:
596
597.. code-block:: c++
598
599 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
600 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(II)) {
601 Value *LHS = BO->getOperand(0);
602 Value *RHS = BO->getOperand(1);
603 if (LHS != RHS) {
604 ...
605 }
606 }
607 }
608
609When you have very, very small loops, this sort of structure is fine. But if it
610exceeds more than 10-15 lines, it becomes difficult for people to read and
611understand at a glance. The problem with this sort of code is that it gets very
612nested very quickly. Meaning that the reader of the code has to keep a lot of
613context in their brain to remember what is going immediately on in the loop,
614because they don't know if/when the ``if`` conditions will have ``else``\s etc.
615It is strongly preferred to structure the loop like this:
616
617.. code-block:: c++
618
619 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
620 BinaryOperator *BO = dyn_cast<BinaryOperator>(II);
621 if (!BO) continue;
622
623 Value *LHS = BO->getOperand(0);
624 Value *RHS = BO->getOperand(1);
625 if (LHS == RHS) continue;
626
627 ...
628 }
629
630This has all the benefits of using early exits for functions: it reduces nesting
631of the loop, it makes it easier to describe why the conditions are true, and it
632makes it obvious to the reader that there is no ``else`` coming up that they
633have to push context into their brain for. If a loop is large, this can be a
634big understandability win.
635
636Don't use ``else`` after a ``return``
637^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
638
639For similar reasons above (reduction of indentation and easier reading), please
640do not use ``'else'`` or ``'else if'`` after something that interrupts control
641flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For
642example, this is *bad*:
643
644.. code-block:: c++
645
646 case 'J': {
647 if (Signed) {
648 Type = Context.getsigjmp_bufType();
649 if (Type.isNull()) {
650 Error = ASTContext::GE_Missing_sigjmp_buf;
651 return QualType();
652 } else {
653 break;
654 }
655 } else {
656 Type = Context.getjmp_bufType();
657 if (Type.isNull()) {
658 Error = ASTContext::GE_Missing_jmp_buf;
659 return QualType();
Meador Inged65ebce2012-06-20 23:48:01 +0000660 } else {
Bill Wendling2c8293d2012-06-20 02:57:56 +0000661 break;
Meador Inged65ebce2012-06-20 23:48:01 +0000662 }
Bill Wendling2c8293d2012-06-20 02:57:56 +0000663 }
664 }
Bill Wendling2c8293d2012-06-20 02:57:56 +0000665
666It is better to write it like this:
667
668.. code-block:: c++
669
670 case 'J':
671 if (Signed) {
672 Type = Context.getsigjmp_bufType();
673 if (Type.isNull()) {
674 Error = ASTContext::GE_Missing_sigjmp_buf;
675 return QualType();
676 }
677 } else {
678 Type = Context.getjmp_bufType();
679 if (Type.isNull()) {
680 Error = ASTContext::GE_Missing_jmp_buf;
681 return QualType();
682 }
683 }
684 break;
685
686Or better yet (in this case) as:
687
688.. code-block:: c++
689
690 case 'J':
691 if (Signed)
692 Type = Context.getsigjmp_bufType();
693 else
694 Type = Context.getjmp_bufType();
695
696 if (Type.isNull()) {
697 Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
698 ASTContext::GE_Missing_jmp_buf;
699 return QualType();
700 }
701 break;
702
703The idea is to reduce indentation and the amount of code you have to keep track
704of when reading the code.
705
706Turn Predicate Loops into Predicate Functions
707^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
708
709It is very common to write small loops that just compute a boolean value. There
710are a number of ways that people commonly write these, but an example of this
711sort of thing is:
712
713.. code-block:: c++
714
715 bool FoundFoo = false;
716 for (unsigned i = 0, e = BarList.size(); i != e; ++i)
717 if (BarList[i]->isFoo()) {
718 FoundFoo = true;
719 break;
720 }
721
722 if (FoundFoo) {
723 ...
724 }
725
726This sort of code is awkward to write, and is almost always a bad sign. Instead
727of this sort of loop, we strongly prefer to use a predicate function (which may
728be `static`_) that uses `early exits`_ to compute the predicate. We prefer the
729code to be structured like this:
730
731.. code-block:: c++
732
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +0000733 /// \returns true if the specified list has an element that is a foo.
Andrew Trick331e8fb2012-09-20 02:01:06 +0000734 static bool containsFoo(const std::vector<Bar*> &List) {
Bill Wendling2c8293d2012-06-20 02:57:56 +0000735 for (unsigned i = 0, e = List.size(); i != e; ++i)
736 if (List[i]->isFoo())
737 return true;
738 return false;
739 }
740 ...
741
Andrew Trick331e8fb2012-09-20 02:01:06 +0000742 if (containsFoo(BarList)) {
Bill Wendling2c8293d2012-06-20 02:57:56 +0000743 ...
744 }
745
746There are many reasons for doing this: it reduces indentation and factors out
747code which can often be shared by other code that checks for the same predicate.
748More importantly, it *forces you to pick a name* for the function, and forces
749you to write a comment for it. In this silly example, this doesn't add much
750value. However, if the condition is complex, this can make it a lot easier for
751the reader to understand the code that queries for this predicate. Instead of
752being faced with the in-line details of how we check to see if the BarList
753contains a foo, we can trust the function name and continue reading with better
754locality.
755
756The Low-Level Issues
757--------------------
758
759Name Types, Functions, Variables, and Enumerators Properly
760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
761
762Poorly-chosen names can mislead the reader and cause bugs. We cannot stress
763enough how important it is to use *descriptive* names. Pick names that match
764the semantics and role of the underlying entities, within reason. Avoid
765abbreviations unless they are well known. After picking a good name, make sure
766to use consistent capitalization for the name, as inconsistency requires clients
767to either memorize the APIs or to look it up to find the exact spelling.
768
769In general, names should be in camel case (e.g. ``TextFileReader`` and
770``isLValue()``). Different kinds of declarations have different rules:
771
772* **Type names** (including classes, structs, enums, typedefs, etc) should be
773 nouns and start with an upper-case letter (e.g. ``TextFileReader``).
774
775* **Variable names** should be nouns (as they represent state). The name should
776 be camel case, and start with an upper case letter (e.g. ``Leader`` or
777 ``Boats``).
778
779* **Function names** should be verb phrases (as they represent actions), and
780 command-like function should be imperative. The name should be camel case,
781 and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
782
783* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
784 follow the naming conventions for types. A common use for enums is as a
785 discriminator for a union, or an indicator of a subclass. When an enum is
786 used for something like this, it should have a ``Kind`` suffix
787 (e.g. ``ValueKind``).
788
789* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
790 should start with an upper-case letter, just like types. Unless the
791 enumerators are defined in their own small namespace or inside a class,
792 enumerators should have a prefix corresponding to the enum declaration name.
793 For example, ``enum ValueKind { ... };`` may contain enumerators like
794 ``VK_Argument``, ``VK_BasicBlock``, etc. Enumerators that are just
795 convenience constants are exempt from the requirement for a prefix. For
796 instance:
797
798 .. code-block:: c++
799
800 enum {
801 MaxSize = 42,
802 Density = 12
803 };
804
805As an exception, classes that mimic STL classes can have member names in STL's
806style of lower-case words separated by underscores (e.g. ``begin()``,
807``push_back()``, and ``empty()``).
808
809Here are some examples of good and bad names:
810
Meador Ingee3c9ccd2012-06-20 23:57:00 +0000811.. code-block:: c++
Bill Wendling2c8293d2012-06-20 02:57:56 +0000812
813 class VehicleMaker {
814 ...
815 Factory<Tire> F; // Bad -- abbreviation and non-descriptive.
816 Factory<Tire> Factory; // Better.
817 Factory<Tire> TireFactory; // Even better -- if VehicleMaker has more than one
818 // kind of factories.
819 };
820
821 Vehicle MakeVehicle(VehicleType Type) {
822 VehicleMaker M; // Might be OK if having a short life-span.
823 Tire tmp1 = M.makeTire(); // Bad -- 'tmp1' provides no information.
824 Light headlight = M.makeLight("head"); // Good -- descriptive.
825 ...
826 }
827
828Assert Liberally
829^^^^^^^^^^^^^^^^
830
831Use the "``assert``" macro to its fullest. Check all of your preconditions and
832assumptions, you never know when a bug (not necessarily even yours) might be
833caught early by an assertion, which reduces debugging time dramatically. The
834"``<cassert>``" header file is probably already included by the header files you
835are using, so it doesn't cost anything to use it.
836
837To further assist with debugging, make sure to put some kind of error message in
838the assertion statement, which is printed if the assertion is tripped. This
839helps the poor debugger make sense of why an assertion is being made and
840enforced, and hopefully what to do about it. Here is one complete example:
841
842.. code-block:: c++
843
844 inline Value *getOperand(unsigned i) {
Jakub Staszakbfa43c02012-09-30 20:42:13 +0000845 assert(i < Operands.size() && "getOperand() out of range!");
Bill Wendling2c8293d2012-06-20 02:57:56 +0000846 return Operands[i];
847 }
848
849Here are more examples:
850
851.. code-block:: c++
852
853 assert(Ty->isPointerType() && "Can't allocate a non pointer type!");
854
855 assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
856
857 assert(idx < getNumSuccessors() && "Successor # out of range!");
858
859 assert(V1.getType() == V2.getType() && "Constant types must be identical!");
860
861 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
862
863You get the idea.
864
Jordan Rose715672c2012-10-26 22:08:46 +0000865In the past, asserts were used to indicate a piece of code that should not be
866reached. These were typically of the form:
Bill Wendling2c8293d2012-06-20 02:57:56 +0000867
868.. code-block:: c++
869
Jordan Rose715672c2012-10-26 22:08:46 +0000870 assert(0 && "Invalid radix for integer literal");
Bill Wendling2c8293d2012-06-20 02:57:56 +0000871
Jordan Rose715672c2012-10-26 22:08:46 +0000872This has a few issues, the main one being that some compilers might not
873understand the assertion, or warn about a missing return in builds where
874assertions are compiled out.
875
876Today, we have something much better: ``llvm_unreachable``:
Bill Wendling2c8293d2012-06-20 02:57:56 +0000877
878.. code-block:: c++
879
Jordan Rose715672c2012-10-26 22:08:46 +0000880 llvm_unreachable("Invalid radix for integer literal");
881
882When assertions are enabled, this will print the message if it's ever reached
883and then exit the program. When assertions are disabled (i.e. in release
884builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating
885code for this branch. If the compiler does not support this, it will fall back
886to the "abort" implementation.
Bill Wendling2c8293d2012-06-20 02:57:56 +0000887
888Another issue is that values used only by assertions will produce an "unused
889value" warning when assertions are disabled. For example, this code will warn:
890
891.. code-block:: c++
892
893 unsigned Size = V.size();
894 assert(Size > 42 && "Vector smaller than it should be");
895
896 bool NewToSet = Myset.insert(Value);
897 assert(NewToSet && "The value shouldn't be in the set yet");
898
899These are two interesting different cases. In the first case, the call to
900``V.size()`` is only useful for the assert, and we don't want it executed when
901assertions are disabled. Code like this should move the call into the assert
902itself. In the second case, the side effects of the call must happen whether
903the assert is enabled or not. In this case, the value should be cast to void to
904disable the warning. To be specific, it is preferred to write the code like
905this:
906
907.. code-block:: c++
908
909 assert(V.size() > 42 && "Vector smaller than it should be");
910
911 bool NewToSet = Myset.insert(Value); (void)NewToSet;
912 assert(NewToSet && "The value shouldn't be in the set yet");
913
914Do Not Use ``using namespace std``
915^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
916
917In LLVM, we prefer to explicitly prefix all identifiers from the standard
918namespace with an "``std::``" prefix, rather than rely on "``using namespace
919std;``".
920
921In header files, adding a ``'using namespace XXX'`` directive pollutes the
922namespace of any source file that ``#include``\s the header. This is clearly a
923bad thing.
924
925In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
926rule, but is still important. Basically, using explicit namespace prefixes
927makes the code **clearer**, because it is immediately obvious what facilities
928are being used and where they are coming from. And **more portable**, because
929namespace clashes cannot occur between LLVM code and other namespaces. The
930portability rule is important because different standard library implementations
931expose different symbols (potentially ones they shouldn't), and future revisions
932to the C++ standard will add more symbols to the ``std`` namespace. As such, we
933never use ``'using namespace std;'`` in LLVM.
934
935The exception to the general rule (i.e. it's not an exception for the ``std``
936namespace) is for implementation files. For example, all of the code in the
937LLVM project implements code that lives in the 'llvm' namespace. As such, it is
938ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
939llvm;'`` directive at the top, after the ``#include``\s. This reduces
940indentation in the body of the file for source editors that indent based on
941braces, and keeps the conceptual context cleaner. The general form of this rule
942is that any ``.cpp`` file that implements code in any namespace may use that
943namespace (and its parents'), but should not use any others.
944
945Provide a Virtual Method Anchor for Classes in Headers
946^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
947
948If a class is defined in a header file and has a vtable (either it has virtual
949methods or it derives from classes with virtual methods), it must always have at
950least one out-of-line virtual method in the class. Without this, the compiler
951will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
952header, bloating ``.o`` file sizes and increasing link times.
953
David Blaikie67bf4292012-09-21 17:47:36 +0000954Don't use default labels in fully covered switches over enumerations
955^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
956
957``-Wswitch`` warns if a switch, without a default label, over an enumeration
958does not cover every enumeration value. If you write a default label on a fully
959covered switch over an enumeration then the ``-Wswitch`` warning won't fire
960when new elements are added to that enumeration. To help avoid adding these
961kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is
962off by default but turned on when building LLVM with a version of Clang that
963supports the warning.
964
965A knock-on effect of this stylistic requirement is that when building LLVM with
David Blaikieb890e9f2012-09-21 18:03:02 +0000966GCC you may get warnings related to "control may reach end of non-void function"
David Blaikie67bf4292012-09-21 17:47:36 +0000967if you return from each case of a covered switch-over-enum because GCC assumes
David Blaikieb890e9f2012-09-21 18:03:02 +0000968that the enum expression may take any representable value, not just those of
969individual enumerators. To suppress this warning, use ``llvm_unreachable`` after
970the switch.
David Blaikie67bf4292012-09-21 17:47:36 +0000971
Craig Topper88b5a2b2012-09-18 04:43:40 +0000972Use ``LLVM_DELETED_FUNCTION`` to mark uncallable methods
973^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
974
975Prior to C++11, a common pattern to make a class uncopyable was to declare an
976unimplemented copy constructor and copy assignment operator and make them
977private. This would give a compiler error for accessing a private method or a
978linker error because it wasn't implemented.
979
Dmitri Gribenkoe3f14592012-09-18 14:00:58 +0000980With C++11, we can mark methods that won't be implemented with ``= delete``.
Craig Topper88b5a2b2012-09-18 04:43:40 +0000981This will trigger a much better error message and tell the compiler that the
982method will never be implemented. This enables other checks like
983``-Wunused-private-field`` to run correctly on classes that contain these
984methods.
985
986To maintain compatibility with C++03, ``LLVM_DELETED_FUNCTION`` should be used
Dmitri Gribenkoe3f14592012-09-18 14:00:58 +0000987which will expand to ``= delete`` if the compiler supports it. These methods
Craig Topper88b5a2b2012-09-18 04:43:40 +0000988should still be declared private. Example of the uncopyable pattern:
989
990.. code-block:: c++
991
992 class DontCopy {
993 private:
994 DontCopy(const DontCopy&) LLVM_DELETED_FUNCTION;
995 DontCopy &operator =(const DontCopy&) LLVM_DELETED_FUNCTION;
996 public:
997 ...
998 };
999
Bill Wendling2c8293d2012-06-20 02:57:56 +00001000Don't evaluate ``end()`` every time through a loop
1001^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1002
1003Because C++ doesn't have a standard "``foreach``" loop (though it can be
1004emulated with macros and may be coming in C++'0x) we end up writing a lot of
1005loops that manually iterate from begin to end on a variety of containers or
1006through other data structures. One common mistake is to write a loop in this
1007style:
1008
1009.. code-block:: c++
1010
1011 BasicBlock *BB = ...
1012 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
1013 ... use I ...
1014
1015The problem with this construct is that it evaluates "``BB->end()``" every time
1016through the loop. Instead of writing the loop like this, we strongly prefer
1017loops to be written so that they evaluate it once before the loop starts. A
1018convenient way to do this is like so:
1019
1020.. code-block:: c++
1021
1022 BasicBlock *BB = ...
1023 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1024 ... use I ...
1025
1026The observant may quickly point out that these two loops may have different
1027semantics: if the container (a basic block in this case) is being mutated, then
1028"``BB->end()``" may change its value every time through the loop and the second
1029loop may not in fact be correct. If you actually do depend on this behavior,
1030please write the loop in the first form and add a comment indicating that you
1031did it intentionally.
1032
1033Why do we prefer the second form (when correct)? Writing the loop in the first
1034form has two problems. First it may be less efficient than evaluating it at the
1035start of the loop. In this case, the cost is probably minor --- a few extra
1036loads every time through the loop. However, if the base expression is more
1037complex, then the cost can rise quickly. I've seen loops where the end
1038expression was actually something like: "``SomeMap[x]->end()``" and map lookups
1039really aren't cheap. By writing it in the second form consistently, you
1040eliminate the issue entirely and don't even have to think about it.
1041
1042The second (even bigger) issue is that writing the loop in the first form hints
1043to the reader that the loop is mutating the container (a fact that a comment
1044would handily confirm!). If you write the loop in the second form, it is
1045immediately obvious without even looking at the body of the loop that the
1046container isn't being modified, which makes it easier to read the code and
1047understand what it does.
1048
1049While the second form of the loop is a few extra keystrokes, we do strongly
1050prefer it.
1051
1052``#include <iostream>`` is Forbidden
1053^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1054
1055The use of ``#include <iostream>`` in library files is hereby **forbidden**,
1056because many common implementations transparently inject a `static constructor`_
1057into every translation unit that includes it.
1058
1059Note that using the other stream headers (``<sstream>`` for example) is not
1060problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
1061provides various APIs that are better performing for almost every use than
1062``std::ostream`` style APIs.
1063
1064.. note::
1065
1066 New code should always use `raw_ostream`_ for writing, or the
1067 ``llvm::MemoryBuffer`` API for reading files.
1068
1069.. _raw_ostream:
1070
1071Use ``raw_ostream``
1072^^^^^^^^^^^^^^^^^^^
1073
1074LLVM includes a lightweight, simple, and efficient stream implementation in
1075``llvm/Support/raw_ostream.h``, which provides all of the common features of
1076``std::ostream``. All new code should use ``raw_ostream`` instead of
1077``ostream``.
1078
1079Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
1080declared as ``class raw_ostream``. Public headers should generally not include
1081the ``raw_ostream`` header, but use forward declarations and constant references
1082to ``raw_ostream`` instances.
1083
1084Avoid ``std::endl``
1085^^^^^^^^^^^^^^^^^^^
1086
1087The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
1088the output stream specified. In addition to doing this, however, it also
1089flushes the output stream. In other words, these are equivalent:
1090
1091.. code-block:: c++
1092
1093 std::cout << std::endl;
1094 std::cout << '\n' << std::flush;
1095
1096Most of the time, you probably have no reason to flush the output stream, so
1097it's better to use a literal ``'\n'``.
1098
1099Microscopic Details
1100-------------------
1101
1102This section describes preferred low-level formatting guidelines along with
1103reasoning on why we prefer them.
1104
1105Spaces Before Parentheses
1106^^^^^^^^^^^^^^^^^^^^^^^^^
1107
1108We prefer to put a space before an open parenthesis only in control flow
1109statements, but not in normal function call expressions and function-like
1110macros. For example, this is good:
1111
1112.. code-block:: c++
1113
1114 if (x) ...
1115 for (i = 0; i != 100; ++i) ...
1116 while (llvm_rocks) ...
1117
1118 somefunc(42);
1119 assert(3 != 4 && "laws of math are failing me");
1120
1121 a = foo(42, 92) + bar(x);
1122
1123and this is bad:
1124
1125.. code-block:: c++
1126
1127 if(x) ...
1128 for(i = 0; i != 100; ++i) ...
1129 while(llvm_rocks) ...
1130
1131 somefunc (42);
1132 assert (3 != 4 && "laws of math are failing me");
1133
1134 a = foo (42, 92) + bar (x);
1135
1136The reason for doing this is not completely arbitrary. This style makes control
1137flow operators stand out more, and makes expressions flow better. The function
1138call operator binds very tightly as a postfix operator. Putting a space after a
1139function name (as in the last example) makes it appear that the code might bind
1140the arguments of the left-hand-side of a binary operator with the argument list
1141of a function and the name of the right side. More specifically, it is easy to
1142misread the "``a``" example as:
1143
1144.. code-block:: c++
1145
1146 a = foo ((42, 92) + bar) (x);
1147
1148when skimming through the code. By avoiding a space in a function, we avoid
1149this misinterpretation.
1150
1151Prefer Preincrement
1152^^^^^^^^^^^^^^^^^^^
1153
1154Hard fast rule: Preincrement (``++X``) may be no slower than postincrement
1155(``X++``) and could very well be a lot faster than it. Use preincrementation
1156whenever possible.
1157
1158The semantics of postincrement include making a copy of the value being
1159incremented, returning it, and then preincrementing the "work value". For
1160primitive types, this isn't a big deal. But for iterators, it can be a huge
1161issue (for example, some iterators contains stack and set objects in them...
1162copying an iterator could invoke the copy ctor's of these as well). In general,
1163get in the habit of always using preincrement, and you won't have a problem.
1164
1165
1166Namespace Indentation
1167^^^^^^^^^^^^^^^^^^^^^
1168
1169In general, we strive to reduce indentation wherever possible. This is useful
1170because we want code to `fit into 80 columns`_ without wrapping horribly, but
1171also because it makes it easier to understand the code. Namespaces are a funny
1172thing: they are often large, and we often desire to put lots of stuff into them
1173(so they can be large). Other times they are tiny, because they just hold an
1174enum or something similar. In order to balance this, we use different
1175approaches for small versus large namespaces.
1176
1177If a namespace definition is small and *easily* fits on a screen (say, less than
117835 lines of code), then you should indent its body. Here's an example:
1179
1180.. code-block:: c++
1181
1182 namespace llvm {
1183 namespace X86 {
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +00001184 /// \brief An enum for the x86 relocation codes. Note that
Bill Wendling2c8293d2012-06-20 02:57:56 +00001185 /// the terminology here doesn't follow x86 convention - word means
1186 /// 32-bit and dword means 64-bit.
1187 enum RelocationType {
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +00001188 /// \brief PC relative relocation, add the relocated value to
Bill Wendling2c8293d2012-06-20 02:57:56 +00001189 /// the value already in memory, after we adjust it for where the PC is.
1190 reloc_pcrel_word = 0,
1191
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +00001192 /// \brief PIC base relative relocation, add the relocated value to
1193 /// the value already in memory, after we adjust it for where the
Bill Wendling2c8293d2012-06-20 02:57:56 +00001194 /// PIC base is.
1195 reloc_picrel_word = 1,
1196
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +00001197 /// \brief Absolute relocation, just add the relocated value to the
1198 /// value already in memory.
Bill Wendling2c8293d2012-06-20 02:57:56 +00001199 reloc_absolute_word = 2,
1200 reloc_absolute_dword = 3
1201 };
1202 }
1203 }
1204
1205Since the body is small, indenting adds value because it makes it very clear
1206where the namespace starts and ends, and it is easy to take the whole thing in
1207in one "gulp" when reading the code. If the blob of code in the namespace is
1208larger (as it typically is in a header in the ``llvm`` or ``clang`` namespaces),
1209do not indent the code, and add a comment indicating what namespace is being
1210closed. For example:
1211
1212.. code-block:: c++
1213
1214 namespace llvm {
1215 namespace knowledge {
1216
Dmitri Gribenkob8f2d822012-10-20 13:27:43 +00001217 /// This class represents things that Smith can have an intimate
Bill Wendling2c8293d2012-06-20 02:57:56 +00001218 /// understanding of and contains the data associated with it.
1219 class Grokable {
1220 ...
1221 public:
1222 explicit Grokable() { ... }
1223 virtual ~Grokable() = 0;
1224
1225 ...
1226
1227 };
1228
1229 } // end namespace knowledge
1230 } // end namespace llvm
1231
1232Because the class is large, we don't expect that the reader can easily
1233understand the entire concept in a glance, and the end of the file (where the
1234namespaces end) may be a long ways away from the place they open. As such,
1235indenting the contents of the namespace doesn't add any value, and detracts from
1236the readability of the class. In these cases it is best to *not* indent the
1237contents of the namespace.
1238
1239.. _static:
1240
1241Anonymous Namespaces
1242^^^^^^^^^^^^^^^^^^^^
1243
1244After talking about namespaces in general, you may be wondering about anonymous
1245namespaces in particular. Anonymous namespaces are a great language feature
1246that tells the C++ compiler that the contents of the namespace are only visible
1247within the current translation unit, allowing more aggressive optimization and
1248eliminating the possibility of symbol name collisions. Anonymous namespaces are
1249to C++ as "static" is to C functions and global variables. While "``static``"
1250is available in C++, anonymous namespaces are more general: they can make entire
1251classes private to a file.
1252
1253The problem with anonymous namespaces is that they naturally want to encourage
1254indentation of their body, and they reduce locality of reference: if you see a
1255random function definition in a C++ file, it is easy to see if it is marked
1256static, but seeing if it is in an anonymous namespace requires scanning a big
1257chunk of the file.
1258
1259Because of this, we have a simple guideline: make anonymous namespaces as small
1260as possible, and only use them for class declarations. For example, this is
1261good:
1262
1263.. code-block:: c++
1264
1265 namespace {
1266 class StringSort {
1267 ...
1268 public:
1269 StringSort(...)
1270 bool operator<(const char *RHS) const;
1271 };
1272 } // end anonymous namespace
1273
Andrew Trick331e8fb2012-09-20 02:01:06 +00001274 static void runHelper() {
Bill Wendling2c8293d2012-06-20 02:57:56 +00001275 ...
1276 }
1277
1278 bool StringSort::operator<(const char *RHS) const {
1279 ...
1280 }
1281
1282This is bad:
1283
1284.. code-block:: c++
1285
1286 namespace {
1287 class StringSort {
1288 ...
1289 public:
1290 StringSort(...)
1291 bool operator<(const char *RHS) const;
1292 };
1293
Andrew Trick331e8fb2012-09-20 02:01:06 +00001294 void runHelper() {
Bill Wendling2c8293d2012-06-20 02:57:56 +00001295 ...
1296 }
1297
1298 bool StringSort::operator<(const char *RHS) const {
1299 ...
1300 }
1301
1302 } // end anonymous namespace
1303
Andrew Trick331e8fb2012-09-20 02:01:06 +00001304This is bad specifically because if you're looking at "``runHelper``" in the middle
Bill Wendling2c8293d2012-06-20 02:57:56 +00001305of a large C++ file, that you have no immediate way to tell if it is local to
1306the file. When it is marked static explicitly, this is immediately obvious.
1307Also, there is no reason to enclose the definition of "``operator<``" in the
1308namespace just because it was declared there.
1309
1310See Also
1311========
1312
1313A lot of these comments and recommendations have been culled for other sources.
1314Two particularly important books for our work are:
1315
1316#. `Effective C++
1317 <http://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
1318 by Scott Meyers. Also interesting and useful are "More Effective C++" and
1319 "Effective STL" by the same author.
1320
1321#. `Large-Scale C++ Software Design
1322 <http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620/ref=sr_1_1>`_
1323 by John Lakos
1324
1325If you get some free time, and you haven't read them: do so, you might learn
1326something.