Make TermGenerator reference count Stopper too
[xapian.git] / xapian-core / HACKING
blobf271fbbc2bc6be1da3c6f4a328ea24fc0bdac86d
1 Instructions for hacking on Xapian
2 ==================================
4 .. contents:: Table of contents
6 This file is aimed to help developers get started with working on
7 Xapian.  The documentation contains a section covering various internal
8 aspects of the library - this can also be found on the Xapian website
9 <https://xapian.org/>.
11 Extra options to give to configure
12 ==================================
14 Note: Non-developer configure options are described in INSTALL
16 You will probably want to use some of these if you're going to be developing
17 Xapian.
19 --enable-assertions
20         This enables compiling of assertion code which will throw
21         Xapian::AssertionError if the code detects violating of
22         preconditions, postconditions, or fails other consistency checks.
24 --enable-assertions=partial
25         This option enables a subset of the assertions enabled by
26         "--enable-assertions", but not the most expensive.  The intention is
27         that it should be suitable for use in a real-world system for tracking
28         down problems without imposing too much of an overhead (but note that
29         we haven't yet performed timings to measure the overhead...)
31 --enable-log
32         This enables compiling code into the library which generates verbose
33         debugging messages.  See "Debugging Messages", below.
35 --enable-log=profile
36         In 1.2.0 and earlier, this used to use the debug logging macros to
37         report to stderr how long each method takes to execute.  This feature
38         was removed in 1.2.1 - you are likely to get better results using
39         dedicated profiling tools - for more information see:
40         https://trac.xapian.org/wiki/ProfilingXapian
42 --enable-maintainer-mode
43         This tells configure to enable make dependencies for regenerating build
44         system files (such as configure, Makefile.in, and Makefile) and other
45         generated files (such as the stemmers and query parser) when required.
46         These are disabled by default as some make programs try to rebuild them
47         when it's not appropriate (e.g. BSD make doesn't handle VPATH except
48         for implicit rules).  For this reason, we recommend GNU make if you
49         enable maintainer mode.  You'll also need a non-cross-compiling C
50         compiler for compiling the Lemon parser generator and the Snowball
51         stemming algorithm compiler.  The configure script will attempt to
52         locate one, but you can override this autodetection by passing
53         CC_FOR_BUILD on the command line like so::
55         ./configure CC_FOR_BUILD=/opt/bin/gcc
57 --enable-documentation
58         This tells configure to enable make dependencies for regenerating
59         documentation files.  By default it uses the same setting as
60         --enable-maintainer-mode.
62 Debugging Messages
63 ==================
65 If you configure with --enable-log, lots of places in the code generate
66 debugging messages to tell us what they're up to - this information can be
67 very useful for debugging both the Xapian library and code which uses it.  But
68 the quantity of information generated is potentially vast so there's a
69 mechanism to allow you to select where to store the log and which types of
70 message you're interested by setting environment variables.  You can:
72  * set XAPIAN_DEBUG_LOG to be the path to a file that you would like debugging
73    output to be appended to, or to the special value ``-`` to indicate that you
74    would like debugging output to be sent to stderr.  Unless XAPIAN_DEBUG_LOG
75    is set, no debug logging will be performed.  Occurrences of %p in
76    XAPIAN_DEBUG_LOG will be replaced with the current process-id.
78  * set XAPIAN_DEBUG_FLAGS to a string of capital letters indicating the types
79    of debugging message you would like to display (the default is to log calls
80    to API functions and methods).  These letters are shown in the first column
81    of the log output, and are also listed in ``common/debuglog.h``.  If the
82    first character is ``-``, then the letters indicate those categories of
83    message *not* be shown instead.  As a consequence of this, setting
84    ``XAPIAN_DEBUG_FLAGS=-`` will give you all debugging messages.
86 These environment variables only have any effect if you ran configure with the
87 --enable-log option.
89 The format is::
91     <message type> <pid> [<this>] <message>
93 For example::
95     A 16747 [0x57ad1e0] void Xapian::Query::Internal::validate_query()
97 Each nested call adds another space before the ``[`` so you can easily see
98 which function call and return messages correspond.
100 Debugging memory allocations
101 ============================
103 The testsuite can make use of valgrind 3.3.0 or newer to check for memory
104 leaks, reads from uninitialised memory, and some other bugs during tests.
106 Valgrind doesn't support every platform, but Xapian contains very little
107 platform specific code (and most of what there is is Microsoft Windows
108 specific) so even just testing with valgrind on one platform gives good
109 coverage.
111 If you have a new enough version of valgrind installed, it's automatically
112 detected by configure and used when running the testsuite.  The testsuite runs
113 more slowly under valgrind, so if you wish to disable this auto-detection you
114 can run configure with:
116 ./configure VALGRIND=
118 Or you can disable use of valgrind during a particular run of "make check"
119 like so:
121 make check VALGRIND=
123 Or disable it while running a test directly (under sh or bash):
125 VALGRIND= ./runtest ./apitest
127 Running test programs
128 =====================
130 To run all tests, use ``make check``.  You can also run just the subset of
131 tests which exercise the inmemory, remote progserver, remote TCP,
132 multi-database, glass, or chert backends using ``make check-inmemory``,
133 ``make check-remoteprog``, ``make check-remotetcp``, ``make check-multi``,
134 ``make check-glass``, or ``make check-chert``
135 respectively.
137 Also, ``make check-remote`` will run the tests on both variants of the remote
138 backend, and ``make check-none`` will run those tests which don't use any
139 backend.  These are handy shortcuts when doing development work on a particular
140 backend.
142 The runtest script (in the tests subdirectory) takes care of the details of
143 running the test programs (including setting up the environment so they work
144 when srcdir != builddir and handling libtool dynamically linked binaries).  To
145 run a test program by hand (rather than via make) just use:
147 ./runtest ./apitest
149 You can specify options and arguments.  Individual test programs optionally
150 take one or more test names as arguments, and you can also pass ``-v`` to get
151 more verbose output from failing tests, e.g.:
153 ./runtest ./apitest -v deldoc1
155 If the number of the test is omitted, all tests with that basename are run,
156 so to run deldoc1, deldoc2, etc:
158 ./runtest ./apitest deldoc
160 You can also use runtest to run a test program under gdb (or most other tools):
162 ./runtest gdb ./apitest -v deldoc1
163 ./runtest valgrind ./apitest -v deldoc1
165 Some test programs take special arguments - for example, you can restrict
166 apitest to the chert backend using ``-bchert``.
168 There are a few environmental variables which the testsuite harness checks for
169 which you might find useful:
171   XAPIAN_TESTSUITE_SIG_DFL:
172     By default, the testsuite harness catches signals and handles them
173     gracefully - the current test is failed, and the testsuite moves onto the
174     next test.  If you want to suppress this (some debugging tools may work
175     better if the signal is not caught) set the environment variable
176     XAPIAN_TESTSUITE_SIG_DFL to any value to prevent the testsuite harness
177     from installing its own signal handling.
179   XAPIAN_TESTSUITE_OUTPUT:
180     By default, the testsuite harness uses ANSI escape sequences to give
181     colour output if stdout is a tty.  You can disable this feature by setting
182     XAPIAN_TESTSUITE_OUTPUT=plain (alternatively, piping the output (e.g.
183     through ``cat`` or ``more``) will have the same effect).  Auto-detection
184     can be explicitly specified with XAPIAN_TESTSUITE_OUTPUT=auto (or empty).
185     Any other value forces the use of colour.  Colour output is always disabled
186     on Microsoft Windows, so XAPIAN_TESTSUITE_OUTPUT has no effect there.
188   XAPIAN_TESTSUITE_LD_PRELOAD:
189     The runtest script will add this to LD_PRELOAD if it is set, allowing you
190     to easily load LD_PRELOAD libraries when running the testsuite.  The
191     original intended use was to allow use of libeatmydata
192     (https://www.flamingspork.com/projects/libeatmydata/) which makes fsync
193     and related calls no-ops, but configure now checks for the eatmydata
194     wrapper script and this is used automatically.  However, there may be
195     other LD_PRELOAD libraries which are useful, so we've left the machinery
196     in place.
198 Speeding up the testsuite with eatmydata
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201 The testsuite does a lot of small database operations, and the calls to fsync,
202 fdatasync, etc which Xapian makes by default can slow down testsuite runs
203 substantially.  There's a handy LD_PRELOAD library called eatmydata
204 (http://www.flamingspork.com/projects/libeatmydata/), which can help here, by
205 turning fsync and related calls into no-ops.
207 You need a version of eatmydata with the eatmydata wrapper script (version 37
208 or newer), and then configure should auto-detect it and it'll get used when
209 running the testsuite (via runtest).  If you wish to disable this
210 auto-detection for some reason, you can run configure with:
212 ./configure EATMYDATA=
214 Or you can disable use of eatmydata during a particular run of "make check"
215 like so:
217 make check EATMYDATA=
219 Or disable it while running a test directly (under sh or bash):
221 EATMYDATA= ./runtest ./apitest
223 Using various debugging, profiling, and leak-finding tools
224 ==========================================================
226 GCC's libstdc++ supports a debug mode, which checks for various misuses of
227 the STL - to enable this, define _GLIBCXX_DEBUG when building Xapian:
229   ./configure CPPFLAGS=-D_GLIBCXX_DEBUG
231 For documentation of this option, see:
232 http://gcc.gnu.org/onlinedocs/libstdc++/debug.html
234 Note: all C++ code must be compiled with this defined or you'll get problems.
235 Xapian's API headers include a check that the same setting is used when
236 building code using Xapian as was used to build Xapian.
238 To use valgrind (http://www.valgrind.org/), no special build options are
239 required, but make sure you compile with debugging information (on by default
240 for GCC) and the valgrind documentation recommends disabling optimisation (with
241 optimisation, line numbers in error messages can be confusing due to code
242 inlining, etc):
244   ./configure CXXFLAGS='-O0 -g'
246 To use gdb (http://www.gnu.org/software/gdb/), no special build options are
247 required, but make sure you compile with debugging information (on by default
248 for GCC).  You'll probably find debugging easier if you compile without
249 optimisation (with optimisation, line numbers in error messages can be
250 confusing due to code inlining, etc, and the values of some variables can't be
251 printed because they've been eliminated from the code completely):
253   ./configure CXXFLAGS='-O0 -g'
255 To enable profiling for gprof:
257   ./configure CXXFLAGS=-pg LDFLAGS=-pg
259 To use Purify (a proprietary tool):
261   ./configure CXXLD='purify c++' --disable-shared
263 To use Insure (another proprietary tool):
265   ./configure CXX=insure
267 To use lcov (at least version 1.10) to generate a test coverage report (see
268 `lcov.xapian.org <http://lcov.xapian.org/>`_ for reports) there are two make
269 targets:
271   * coverage-reconfigure: reruns configure in the source tree.  See
272     Makefile.am for details of the configure options used and why they
273     are needed.
274   
275   * coverage-check: runs "make check" and generates an HTML report in a
276     directory called "lcov".  You can specify extra arguments to pass to the
277     ``genhtml`` tool using GENHTML_ARGS, like so::
279     make coverage-check GENHTML_ARGS=--html-gzip
281 If you have runes for using other tools, please add them above, or send them
282 to us so we can.
284 Snapshots
285 =========
287 If you want to try unreleased Xapian code, you can fetch it from our git
288 repository.  For convenience, we also provide bootstrapped tarballs (much like
289 the sourcecode download for any release version) which get built every 20
290 minutes if there have been any changes checked in.  These tarballs need to
291 pass "make distcheck" to be automatically uploaded, so using them will help
292 to assure that you don't pick a "bad" version.  The snapshots are available
293 from the "Bleeding Edge" page of the Xapian website.
295 Building from git
296 =================
298 When building from a git checkout, we *strongly* recommend that you use
299 the ``bootstrap`` script in the top level directory to set up the tree ready
300 for building.  This script will check which directories you have checked out,
301 so you can bootstrap a partial tree.  You can also ``touch .nobootstrap`` in
302 a subdirectory to tell bootstrap to ignore it.
304 You will need the following tools installed to build from git:
306 * GNU m4 (for autoconf)
307 * perl 5 (for automake; also for various maintainer scripts)
308 * python >= 2.3 (for generating the Python bindings)
309 * GNU make (or another make which support VPATH for explicit rules)
310 * GNU bison (for building SWIG, used for generating the bindings)
311 * Tcl (to generate unicode/unicode-data.cc)
313 For a recent version of Debian or Ubuntu, this command should ensure you have
314 all the necessary tools and libraries::
316     apt-get install build-essential m4 perl python zlib1g-dev uuid-dev wget bison tcl
318 If you want to build Omega, you'll also need::
320     apt-get install libpcre3-dev libmagic-dev
322 On Fedora, the uuid library can be installed by doing::
324     yum install libuuid-devel
326 On Mac OS X, if you're using macports you'll want the following:
328   * file (magic.h in configure)
330 If you're using homebrew you'll want the following::
332     brew install libmagic pcre
334 If you're doing much development work, you'll probably also want the following
335 tools installed:
337 * valgrind for better testsuite error finding
338 * ccache for faster rebuilds
339 * eatmydata for faster testsuite runs
341 The repository does not contain any automatically generated files
342 (such as configure, Makefile.in, Snowball-generated stemmers, Lemon-generated
343 parsers, SWIG-generated code, etc) because experience shows it's best to keep
344 these out of version control.  To avoid requiring you to install the correct
345 versions of the tools required, we either include the source to these tools in
346 the repo directly (in the case of Snowball and Lemon), or the bootstrap script
347 will download them as tarballs (autoconf, automake, libtool) or
348 from git (SWIG), build them, and install them within the source tree.
350 To download source tarballs, bootstrap will use wget, curl or lwp-request if
351 installed.  If not, it will give an error telling you the URL to download from
352 by hand and where to copy the file to.
354 Bootstrap will then run autoreconf on each of the checked-out subdirectories,
355 and generate a top-level configure script.  This configure script allows you to
356 configure xapian-core and any other modules you've checked out with single
357 simple command, such that the other modules link against the uninstalled
358 xapian-core (which is very handy for development work and a bit fiddly to set
359 up by hand).  It automatically passes --enable-maintainer-mode to the
360 subprojects so that the autotools will be rerun if configure.ac, Makefile.am,
361 etc are modified.
363 The bootstrap script doesn't care what the current directory is.  The top-level
364 configure script generated by it supports building in a separate directory to
365 the sources: simply create the directory you want to build in, and then run the
366 configure script from inside that directory.  For example, to build in a
367 directory called "build" (starting in the top level source directory)::
369   ./bootstrap
370   mkdir build
371   cd build
372   ../configure
374 When running bootstrap, if you need to add any extra macro directories to the
375 path searched by aclocal (which is part of automake), you can do this by
376 specifying these in the ACLOCAL_FLAGS environment variable, e.g.::
378   ACLOCAL_FLAGS=-I/extra/macro/directory ./bootstrap
380 If you wish to prevent bootstrap from downloading and building the autotools
381 pass the --without-autotools option.  You can force it to delete the downloaded
382 and installed versions by passing --clean.
384 If you are tracking development in git, there will sometimes be changes
385 to the build system sources which require regeneration of the generated
386 makefiles and associated machinery.  We aim to make the build system
387 automatically regenerate the necessary files, but in the event that a build
388 fails after an update, it may be worth re-running the bootstrap script to
389 regenerate the build system from scratch, before looking for the cause of the
390 error elsewhere.
392 Tools required to build documentation
393 -------------------------------------
395 If you want to be able to build distribution tarballs (with "make dist") then
396 you'll also need some further tools.  If you don't want to have to install all
397 these tools, then pass --disable-documentation to configure to disable these
398 rules (the default state of this follows the setting of
399 --enable-maintainer-mode, so in a non-maintainer-mode tree, you can pass
400 --enable-documentation to enable these rules).  Without the documentation,
401 "make dist" will fail (to prevent accidentally distributing tarballs without
402 documentation), but you can configure and build.
404 The documentation tools are:
406 * doxygen (v1.8.8 is used for 1.3.x snapshots and releases; 1.7.6.1 fails to
407   process trunk after PL2Weight was added).
408 * dot (part of Graphviz.  Doxygen's DOT_MULTI_TARGETS option apparently needs
409   ">1.8.10")
410 * help2man
411 * rst2html or rst2html.py (in python-docutils on Debian/Ubuntu)
412 * pngcrush (optional - used to reduce the size of PNG files in the HTML
413   apidocs)
414 * sphinx-doc (in python-sphinx and python3-sphinx on Debian/Ubuntu, or as
415   sphinx via pip install)
417 For a recent version of Debian or Ubuntu, this command should install all the
418 required documentation tools::
420     apt-get install doxygen graphviz help2man python-docutils pngcrush python-sphinx python3-sphinx
422 Documentation builds on OS X
423 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
425 On Mac OS X, if you're using homebrew, you'll want the following::
427     brew install doxygen help2man graphviz pngcrush
429 (Ensure you're up to date with brew, as earlier packaging of graphviz
430 didn't properly install dot.)
432 You also need sphinx and docutils, which are python packages; you can
433 install them via pip::
435     pip install sphinx docutils
437 You may find it easier to use homebrew to install python first, so
438 these packages are separate from the system python::
440     brew install python
442 If you install both python (v2) and python3 (v3) via homebrew, you
443 will be able to build bindings for both; you'll then need to install
444 sphinx for python3::
446     pip3 install sphinx
448 PDF versions of docs
449 ~~~~~~~~~~~~~~~~~~~~
451 As of 1.3.2, we no longer build PDF versions of the API docs by default, but
452 you can build them yourself with::
454     make -C docs apidoc.pdf
456 Additional tools are needed for these:
458 * gs (part of Ghostscript)
459 * pdflatex (in texlive-latex-base on Debian/Ubuntu)
460 * epstopdf (in texlive-extra-utils on Debian/Ubuntu)
461 * makeindex (in texlive-binaries on Debian/Ubuntu, or texlive-base-bin for older releases)
463 Note that pdflatex, epstopdf, gs, and makeindex must all currently be on your
464 path (as specified by the environmental variable PATH), since doxygen will look
465 for them there.
467 For a recent version of Debian or Ubuntu, this command should install these
468 extra tools::
470     apt-get install ghostscript texlive-latex-base texlive-extra-utils texlive-binaries texlive-fonts-extra texlive-fonts-recommended texlive-latex-extra texlive-latex-recommended
472 On Mac OS X, if you're using macports you'll want the following:
474   * texlive (pdflatex during build)
475   * texlive-basic (for makeindex in configure)
476   * texlive-latex-extra (latex style)
478 Alternatively, you can install MacTeX from http://www.tug.org/mactex/ instead
479 of texlive, texlive-basic and texlive-latex-extra.
481 The homebrew texlive package only supports 32 bit systems, so even if you're
482 using homebrew, you'll probably want to install MacTeX from
483 http://www.tug.org/mactex/ instead.
485 Autotools versions
486 ------------------
488 * autoconf 2.68 is used to generate snapshots and releases.
490   autoconf 2.64 is a hard minimum requirement.
492   autoconf 2.60 is required for docdir support and AC_TYPE_SSIZE_T.
494   autoconf 2.62 generates faster configure scripts and warns about unrecognised
495   options passed to configure.
497   autoconf 2.63 fixes a regression in AC_C_BIGENDIAN introduced in 2.62
498   (Omega uses this macro).
500   autoconf 2.64 generates smaller configure scripts by using shell functions.
502 * automake 1.15 is used to generate snapshots and releases.
504   automake 1.12.2 is a hard minimum requirement.  This version fixes a
505   security issue (CVE-2012-3386) in the generated `make distcheck` rules.
507   automake 1.12 is needed to support using LOG_COMPILER to specify a testsuite
508   driver (used by xapian-bindings).
510 * libtool 2.4.6 is used to generate snapshots and releases.
512   libtool 2.2.8 is the current hard minimum requirement.
514   libtool 2.2 is required for us to be able to override link_all_deplibs_CXX
515   and sys_lib_dlsearch_path_spec in configure.  It also fixes some
516   long-standing issues and is significantly faster.
518 Please tell us if you find that newer versions of any of these tools work or
519 fail to work.
521 There is a good GNU autotools tutorial at
522 <http://www.lrde.epita.fr/~adl/autotools.html>.
524 Building from git on Windows with MSVC
525 --------------------------------------
527 The windows build process is maintained in the xapian-maintainer-tools
528 directory in the Xapian git repository.  See the win32msvc/README file in that
529 directory for details of how to build from git.
531 Using a Vagrant-driven Ubuntu virtual machine
532 ---------------------------------------------
534 Note: Vagrant support is experimental. Please report bugs in the
535 normal fashion, to https://trac.xapian.org/newticket, or ask for help
536 on the #xapian IRC channel on Freenode.
538 If you have Vagrant (http://www.vagrantup.com/, tested on version
539 1.5.2) and VirtualBox (https://www.virtualbox.org/, tested on version
540 4.3.10) installed, `vagrant up` will make a virtual machine suitable
541 for developing Xapian:
543  * Ubuntu 13.04 with all packages needed to build Xapian and its
544    documentation
546  * eatmydata (to speed up test runs) and valgrind (for debugging
547    memory allocations) both also installed
549  * source code from this checkout in /vagrant; edit it on your host
550    operating system and changes are reflected in the VM. The source
551    tree is bootstrapped automatically (ensuring that the right
552    versions of the build tools are available on the VM)
554  * build tree in /home/vagrant/build, configured to install into
555    /home/vagrant/install, with maintainer mode and documentation
556    both enabled
558 Setting up can take a long time, as it downloads a minimal base box
559 and then installs all the required packages; once this is done you
560 don't have to wait so long if you need to reprovision the VM. (Once
561 Ubuntu 14.04 is released the plan is to build our own base box with
562 these packages already installed, which should make the process much
563 faster.)
565 `vagrant ssh` will log you into the VM, and you can type `cd build &&
566 make` to build Xapian. `make check` will run the tests.
568 (As noted above, in maintainer mode most changes that require
569 reconfiguration will happen automatically. If you need to do it by
570 hand you can either run the configure command yourself, or you can run
571 `vagrant provision`, which also checks for any system package
572 updates.)
574 The VM has a single 64 bit virtual processor, with 384M of memory; it
575 takes about 8G of disk space once up and running.
577 Use of C++ Features
578 ===================
580 * As of Xapian 1.3.3, a compiler with decent support for C++11 is required to
581   build Xapian.  We currently aim to allow users to use a non-C++11 compiler
582   to build code which uses Xapian.
584   There are now several compilers with good C++11 support, but there are a
585   few shortfalls in commonly deployed versions of most of them.  Often we can
586   work around this, and we should do where the effort is low compared to the
587   gain (so a compiler version which is widely used is more worth supporting
588   than one which is hardly used by anyone).
590   However, we shouldn't have to jump through hoops to cater for compilers where
591   their authors aren't putting in the effort to keep up with the language
592   standards.
594   Please avoid the following C++11 features for the time being:
596   * ``std::to_string()`` - this is completely missing on current versions of
597     mingw and cygwin - in the library, you can ``#include "str.h"`` and then
598     use the ``str()`` function instead for most cases.  This is also usually
599     faster than ``std::to_string()``.
601 * C++ features we currently assume:
603   * We assume <sstream> is available.  GCC < 2.95.3 didn't have it but GCC
604     2.95.3 includes a backported version.  We aren't aware of any other
605     compilers still in use which lack it.
607   * Non-".h" versions of standard ISO C++ headers (e.g. ``#include <list>``
608     rather than ``#include <list.h>``).  We aren't aware of any compiler still
609     in use which lacks these, and GCC 4.3 no longer has the old versions.  If
610     there are any, we could add a directory full of forwarding headers to work
611     around this issue.
613   * Standard header ``<limits>`` (for ``numeric_limits<>``) - for GCC, this was
614     added in GCC 3.0.
616   * Standard header ``<streambuf>`` (GCC < 3.0 only has ``<streambuf.h>``).
618   * Working auto_ptr in header ``<memory>`` (some old version of some compiler
619     had a buggy implementation - the details are lost to history, but it may
620     have been GCC 2.95, or perhaps EGCS).
622 * RTTI (dynamic_cast<>, typeid, etc):  Needing to use RTTI features in the
623   library most likely indicates a design flaw, and you should avoid use
624   of these features.  Where necessary, you can use a technique similar to
625   Database::as_networkdatabase() to replace dynamic_cast<>.
627 * Exceptions: In hindsight, throwing exceptions in the library seems to have
628   been a poor design decision.  GCC on Solaris can't cope with exceptions in
629   shared libraries (though it appears this may have been fixed in more recent
630   versions), and we've also had test failures on other platforms which only
631   occur with shared libraries - possibly with a similar cause.  Exceptions can
632   also be a pain to handle elegantly in the bindings.  We intend to investigate
633   modifying the library to return error codes internally, and then offering the
634   user the choice of exception throwing or error code returning API methods
635   (with the exception being thrown by an inlined wrapper in the externally
636   visible header files).  With this in mind, please don't complicate the
637   internal handling of exceptions...
639 * "using namespace std;" and "using std::XXX;" - it's OK to use these in
640   applications, library code, and internal library headers.  But in externally
641   visible headers (such as anything included by "#include <xapian.h>") you MUST
642   use explicit "std::" qualifiers - it's not acceptable to pull anything from
643   namespace std into the namespace of an application which uses Xapian.
645 * Use C++ style casts (static_cast<>, reinterpret_cast<>, and const_cast<>)
646   or constructor-syntax (e.g. ``double(value)``) in preference to C style
647   casts.  The syntax of the C++ casts is ugly, but they do make the intent much
648   clearer which is definitely a good thing.
650 * std::pair<> with an STL class as one (or both) of the members can produce
651   very long symbols (over 4KB!) after name mangling - long enough to overflow
652   the size limits of some vendor compilers or toolchains (so this can affect
653   GCC if it is using the system ld or as).  Even where the compiler works, the
654   symbol bloat in an unstripped build is probably best avoided, so it's
655   preferable to use a simple two member struct instead.  The code is probably
656   more readable anyway, and easier to extend if more members are needed later.
658 * We try to avoid putting the full definition of virtual methods in header
659   files.  This is because current compilers can't (as far as we know) inline
660   virtual methods, so putting the definition in the header file simply slows
661   down compilation (and, because method definitions often require further
662   header files to be included, this can result in many more files needing
663   recompilation after a change to a header file than is really necessary).
664   Just put the declaration in the header file, and put the definition in a .cc
665   file with the same basename.
667 Include ordering for source files
668 ---------------------------------
670 To help us move towards a consistent ordering of #include lines in source
671 files, please follow the following policy when ordering them:
673 * #include <config.h> should be first, and use <> not "" (as recommended by the
674   autoconf manual).  Always include config.h from C/C++ source files, but don't
675   include it from header files - the autoconf manual recommends that it should
676   be included first, so including it from headers is either redundant, or may
677   hide a missing config.h include in the source file the header was included
678   from (better to get an error in this case).
680 * The header corresponding to the source file should be next. This means that
681   compilation of the library ensures that each header with a corresponding
682   source file is "self supporting" (i.e. it implicitly or explicitly includes
683   all of the headers it requires).
685 * External xapian-core headers, alphabetically. When included from other
686   external headers, use <> to reduce problems with finding headers in the
687   user's source tree by mistake. In sources and internal headers, use "" (?) -
688   practically this makes no difference as we have -I for srcdir and builddir,
689   but <> suggests installed header files so "" seems more natural).
691 * Internal headers, alphabetically (using "").
693 * "Safe" versions of library headers (include these first to avoid issues if
694   other library headers include the ones we want to wrap). Use "" and order
695   alphabetically.
697 * Library headers, alphabetically.
699 * Standard C++ headers, alphabetically. Use the modern (no .h suffix) names.
701 C++ Portability Issues
702 ======================
704 Web Resources
705 -------------
707 The "C++ FAQ Lite" covers many frequently asked C++ questions:
708 http://www.parashift.com/c++-faq-lite/
710 Header Portability Issues
711 -------------------------
713 <fcntl.h>:
714 ----------
716 Don't directly '#include <fcntl.h>' - instead '#include "safefcntl.h"'.
718 The main reason for this is that when using certain compilers on certain
719 versions of Solaris, fcntl.h does '#define open open64'.  Sadly this breaks C++
720 code which has methods called open (as we do).  There's a cunning workaround
721 for this problem in common/safefcntl.h.
723 Also, safefcntl.h ensures the O_BINARY is defined (to 0 if not required) so
724 calls to open() and creat() can specify O_BINARY unconditionally for the
725 benefit of platforms which discriminate between text and binary files.
727 <windows.h>:
728 ------------
730 Don't directly '#include <windows.h>' - instead '#include "safewindows.h"'
731 which reduces the bloat of header files included and prevents some of the
732 more egregious namespace pollution.  It also defines any constants we need
733 which might be missing in older versions of the mingw headers.
735 <winsock2.h>:
736 -------------
738 Don't directly '#include <winsock2.h>' - instead '#include "safewinsock2.h"'.
739 This ensure that safewindows.h is included before <winsock2.h> to avoid
740 winsock2.h including windows.h without our namespace pollution reducing
741 workarounds.
743 <errno.h>:
744 ----------
746 Don't directly '#include <errno.h>' - instead '#include "safeerrno.h"' which
747 works around a problem with Compaq's C++ compiler.
749 <sys/select.h>:
750 ---------------
752 Don't directly '#include <sys/select.h>' - instead '#include "safesysselect.h"'
753 which supports older UNIX platforms which predate POSIX 1003.1-2001 and works
754 around a problem on Solaris.
756 <sys/socket.h>:
757 ---------------
759 Don't directly '#include <sys/socket.h>' - instead '#include "safesyssocket.h"'
760 which supports older UNIX platforms which predate POSIX 1003.1-2001 and works
761 on Windows too.
763 <sys/stat.h>:
764 -------------
766 Don't directly '#include <sys/stat.h>' - instead '#include "safesysstat.h"'
767 which under MSVC enables stat to work on files > 2GB, defines the missing
768 POSIX macros S_ISDIR and S_ISREG, pulls in <direct.h> for mkdir() (which is
769 provided by sys/stat.h under UNIX) and provides a compatibility wrapper for
770 mkdir() which takes 2 arguments (so code using mkdir can always just pass
771 two arguments).
773 <sys/wait.h>:
774 -------------
776 To get `WEXITSTATUS` or `WIFEXITED` defined, '#include "safesyswait.h"'.
777 Note that this won't provide `waitpid()`, etc on Microsoft Windows, since
778 these functions are only really useful to use when `fork()` is available.
780 <unistd.h>:
781 -----------
783 Don't directly '#include <unistd.h>' - instead '#include "safeunistd.h"'
784 - MSVC doesn't even HAVE unistd.h!
786 The various "safe" headers are maintained in xapian-core/common, but also used
787 by Omega.  Currently bootstrap sorts out setting up a copy of this subdirectory
788 via a secondary git checkout.
790 Warning-Free Compilation
791 ------------------------
793 Compiling without warnings on every platform is our goal, though it's not
794 always possible to achieve.  For example, some GCC 3.x compilers produce the
795 occasional bogus warning (e.g.  warning that a variable may be used
796 uninitialised, despite it being initialised at the point of declaration!)
798 You should consider configure-ing with:
800 ./configure CXXFLAGS=-Werror
802 when doing development work on Xapian.  This promotes warnings to errors,
803 which should ensure you at least don't introduce new warnings for the compiler
804 you're using.
806 If you configure with --enable-maintainer-mode, and are using GCC 4.1 or newer,
807 this is done for you automatically.  This is intended to be an aid rather than
808 a form of automated punishment - it's all too easy to miss a new warning as
809 once a file is compiled, you don't see it unless you modify that file or one of
810 its dependencies.
812 With Intel's C++ compiler, --enable-maintainer-mode also enables -Werror.
813 If you know the equivalent of -Werror for other compilers, please add a note
814 here, or tell us so that we can add a note.
816 Miscellaneous Portability Issues
817 --------------------------------
819 Make sure that the last line of any source file ends with a linefeed character
820 since it's undefined behaviour if it doesn't (most compilers accept it, though
821 at least GCC gives a warning).
823 Branch Prediction Hints
824 =======================
826 For compilers which support ``__builtin_expect()`` (GCC >= 3.0 and some others)
827 you can provide manual hints to assist branch prediction.  We've wrapped these
828 in macros which evaluate to just their argument for compilers which don't
829 support ``__builtin_expect()__``.
831 Within the xapian-core library code, you can mark the expressions in ``if`` and
832 ``while`` statements as ``rare`` (if the condition is rarely true) or ``usual``
833 (if the condition is usually true).
835 For example::
837     if (rare(something_unusual())) deal_with_it();
839     while (usual(!end_condition()) keep_going();
841 It's easy to make incorrect assumptions about where hotspots are and which
842 branches are usually taken or not, so except for really obvious cases (such
843 as ``if (!consistency_check()) throw_exception();``) you should benchmark
844 that new ``rare`` and ``usual`` hints help rather than hinder before committing
845 them to the repository.  It's also likely to be a waste of effort to add them
846 outside of areas of code which are executed very frequently.
848 Don't expect miracles - the first 15 uses added saved approximately 1%.
850 If you know how to implement the ``rare`` and ``usual`` macros for other
851 compilers, please let us know.
853 Configure Options
854 =================
856 Especially for a library, compile-time options aren't a good solution for
857 how to integrate a new feature.  An increasingly large number of users install
858 pre-built binary packages rather than building from source, and unless the
859 package is capable of being split into modules, the packager has to choose a
860 set of compile-time options to use.  And they'll tend to choose either the
861 standard ones, or perhaps a broader set to try to keep everyone happy.  For a
862 library, similar issues occur when installing from source as well - the
863 sysadmin must choose the options which will keep all users happy.
865 Another problem with compile-time options is that it's hard to ensure that
866 a change doesn't break compilation under some combination of options without
867 actually building and running the test-suite on all combinations.  The fewer
868 compile-time options, the more likely the code will compile with every
869 combination of them.
871 So please think carefully before adding more compile-time options.  They're
872 probably OK for experimental features (but should go away once a feature is no
873 longer experimental).  Options to instrument a build for special purposes
874 (debug, profiling, etc) are also acceptable.  Disabling whole features probably
875 isn't (e.g. the --disable-backend-XXX options we already have are dubious,
876 though being able to disable the remote backend can be useful when trying to
877 get Xapian going on a platform).
879 Makefile Portability
880 ====================
882 We don't want to force those building Xapian from the source distribution to
883 have to use GNU make.  Requiring GNU make for "make dist" isn't such a problem
884 but it's probably better to use portable constructs everywhere to avoid
885 problems when people move or copy code between targets.  If you do make use
886 of non-portable constructs where it's OK, add a comment noting the special
887 circumstances which justify doing so.
889 Here's an incomplete list of things to avoid:
891 * Don't use "$(RM)" - it's defined by GNU make, but using it actually harms
892   portability as other makes don't define it.  Use plain "rm" instead.
894 * Don't use "%" pattern rules - these are GNU make specific.  Use an
895   implicit rule (e.g. ".c.o:") if you can.  Otherwise, write out each version
896   explicitly.
898 * Don't use "$<" except in implicit rules.  This is an annoying restriction,
899   as using "$<" makes it much easier to make VPATH builds work.  But it's only
900   portable in implicit rules.  Tips for rewriting - if it's a source file,
901   write it as::
903     $(srcdir)/foo.ext
905   If it's a generated object file or similar, just write the name as is.  The
906   tricky case is a generated file which isn't in git but is shipped in the
907   distribution tarball, as such a file could be in either the source or build
908   tree.  Use this trick to make sure it's found whichever directory it's in::
910     `test -f foo.ext || echo '$(srcdir)/'`foo.ext
912 * Don't use "exit 0" to make a rule fail.  Use "false" instead.  BSD make
913   doesn't like "exit 0" in a rule.
915 * Don't use make conditionals.  Automake offers conditionals which may be
916   of use, and these are implemented to work with any make.  See the automake
917   manual for details, and a few caveats.
919 * The list of portable utilities is:
921     cat cmp cp diff echo egrep expr false grep install-info
922     ln ls mkdir mv pwd rm rmdir sed sleep sort tar test touch true
924   Note that versions of these (GNU versions in particular) support switches
925   which aren't portable - notably, "test -r" isn't portable; neither is
926   "cp -a".  And note that "mkdir -p" isn't portable - the semantics vary.
927   The autoconf manual has some useful information about writing portable
928   shell code (most of it not specific to autoconf)::
930     http://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Shell
932 * Don't use "include" - it's not present in BSD make (at least some versions
933   have ".include" instead, but that doesn't really seem to help...)  Automake
934   provides a configure-time include, which may provide a replacement for some
935   uses of "include".
937 * It appears that BSD make only supports VPATH for implicit rules (e.g.
938   ".c.o:") - there's certainly a restriction there which is not present in GNU
939   make.  We used to try to work around this, but now we use AM_MAINTAINER_MODE
940   to disable rules which are only needed by those developing Xapian (these were
941   the rules which caused problems).  And we recommend those developing Xapian
942   use GNU make to avoid problems.
944 * Rules with multiple targets can cause problems for parallel builds.  These
945   rules are really just a shorthand for multiple rules with the same
946   prerequisites and commands, and it is fine to use them in this way.  However,
947   a common temptation is to use them when a single invocation of a command
948   generates multiple output files, by adding each of the output files as a
949   target.  Eg, if a swig language module generates xapian_wrap.cc and
950   xapian_wrap.h, it is tempting to add a single rule something like::
952     # This rule has a problem
953     xapian_wrap.cc xapian_wrap.h: xapian.i
954             SWIG_commands
956   This can result in SWIG_commands being run twice, in parallel.  If
957   SWIG_commands generates any temporary files, the two invocations can
958   interfere causing one of them to fail.
960   Instead of this rule, one solution is to pick one of the output files as a
961   primary target, and add a dependency for the second output file on the first
962   output file::
964     # This rule also has a problem
965     xapian_wrap.h: xapian_wrap.cc
966     xapian_wrap.cc: xapian.i
967             SWIG_commands
969   This ensures that make knows that only one invocation of SWIG_commands is
970   necessary, but could result in problems if the invocation of SWIG_commands
971   failed after creating xapian_wrap.cc, but before creating xapian_wrap.h.
972   Instead, we recommend creating an intermediate target::
973   
974     # This rule works in most cases
975     xapian_wrap.cc xapian_wrap.h: xapian_wrap.stamp
976     xapian_wrap.stamp: xapian.i
977             SWIG_commands
978             touch $@
980   Because the intermediate target is only touched after the commands have
981   executed successfully, subsequent builds will always retry the commands if an
982   error occurs.  Note that the intermediate target cannot be a "phony" target
983   because this would result in the commands being re-run for every build.
985   However, this rule still has a problem - if the xapian_wrap.cc and
986   xapian_wrap.h files are removed, but the xapian_wrap.stamp file is not, the
987   .cc and .h files will not be regenerated.   There is no simple solution to
988   this, but the following is a recipe taken from the automake manual which
989   works.  For details of *why* it works, see the section in the automake manual
990   titled "Multiple Outputs"::
992     # This rule works even if some of the output files were removed
993     xapian_wrap.cc xapian_wrap.h: xapian_wrap.stamp
994     ## Recover from the removal of $@.  A full explanation of these rules is in
995     ## the automake manual under the heading "Multiple Outputs".
996             @if test -f $@; then :; else \
997               trap 'rm -rf xapian_wrap.lock xapian_wrap.stamp' 1 2 13 15; \
998               if mkdir xapian_wrap.lock 2>/dev/null; then \
999                 rm -f xapian_wrap.stamp; \
1000                 $(MAKE) $(AM_MAKEFLAGS) xapian_wrap.stamp; \
1001                 rmdir xapian_wrap.lock; \
1002               else \
1003                 while test -d xapian_wrap.lock; do sleep 1; done; \
1004                 test -f xapian_wrap.stamp; exit $$?; \
1005               fi; \
1006             fi
1007     xapian_wrap.stamp: xapian.i
1008             SWIG_commands
1009             touch $@
1011 * This is actually a robustness point, not portability per se.  Rules which
1012   generate files should be careful not to leave a partial file in place if
1013   there's an error as it will have a timestamp which leads make to believe it's
1014   up-to-date.  So this is bad:
1016   foo.cc: script.pl
1017         $PERL script.pl > foo.cc
1019   This is better:
1021   foo.cc: script.pl
1022         $PERL script.pl > foo.tmp
1023         mv foo.tmp foo.cc
1025   Alternatively, pass the output filename to the script and make sure you
1026   delete the output on error or a signal (although this approach can leave
1027   a partial file in place if the power fails).  All used Makefile.am-s and
1028   scripts have been checked (and fixed if required) as of 2003-07-10 (didn't
1029   check xapian-bindings).
1031 * Another robustness point - if you add a non-file target to a makefile, you
1032   should also list it in ".PHONY".  Otherwise your target won't get remade
1033   reliably if someone creates a file with the same name in their tree.  For
1034   example:
1036   .PHONY: hello goodbye
1038   hello:
1039         echo hello
1041   goodbye:
1042         echo goodbye
1044 And lastly a style point - using "@" to suppress echoing of commands being
1045 executed removes choice from the user - they may want to see what commands
1046 are being executed.  And if they don't want to, many versions of make support
1047 the use "make -s" to suppress the echoing of commands.
1049 Using @echo on a message sent to stdout or stderr is acceptable (since it
1050 avoids showing the message twice).  Otherwise don't use "@" - it makes it
1051 harder to track down problems in the makefiles.
1053 Naming of Scripts
1054 =================
1056 Scripts generally should *not* have an extension indicating the language they
1057 are currently implemented in (e.g. ``runtest`` rather than ``runtest.sh`` or
1058 ``runtest.pl``).  The problem with such an extension is that if we decide
1059 to reimplement the script in a different language, we either have to rename
1060 the script (which is annoying as people will be used to the name, and may
1061 have embedded it in their own scripts), or we have a script with a confusing
1062 name (e.g. a Python script with extension ``.pl``).
1064 The above reasoning doesn't apply to scripts which have to be in a particular
1065 language for some reason, though for consistency they probably shouldn't get
1066 an extension either, unless there's a good reason to have one.
1068 Use of Assert
1069 =============
1071 Use Assert to perform internal consistency checks, and to check for invalid
1072 arguments to functions and methods (e.g. passing a NULL pointer when this isn't
1073 permitted).  It should *NOT* be used to check for error conditions such as
1074 file read errors, memory allocation failing, etc (since we want to perform such
1075 checks in non-debug builds too).
1077 File format errors should also not be tested with Assert - we want to catch
1078 a corrupted database or a malformed input file in a non-debug build too.
1080 There are several variants of Assert:
1082 - Assert(P) -- asserts that expression P is true.
1084 - AssertRel(a,rel,b) -- asserts that (a rel b) is true - rel can be a boolean
1085   relational operator, i.e. one of ``==``, ``!=``, ``>``, ``>=``, ``<``,
1086   ``<=``.  The message given if the assertion fails reports the values of
1087   a and b, so ``AssertRel(a,<,b);`` is more helpful than ``Assert(a < b);``
1089 - AssertEq(a,b) -- shorthand for AssertRel(a,==,b).
1091 - AssertEqDouble(a,b) -- asserts a and b differ by less than DBL_EPSILON
1093 - AssertParanoid(P) -- a particularly expensive assertion.  If you want a build
1094   with Asserts enabled, but without a great performance overhead, then
1095   passing --enable-assertions=partial to configure and AssertParanoids
1096   won't be checked, but Asserts will.  You can also use AssertRelParanoid
1097   and AssertEqParanoid.
1099 - CompileTimeAssert(P) -- this has now been removed, since we require C++11
1100   support from the compuiler, and C++11 added ``static_assert``.
1102 Marking Features as Deprecated
1103 ==============================
1105 In the API headers, a feature (a class, method, function, enum, typedef, etc)
1106 can be marked as deprecated by using the XAPIAN_DEPRECATED() or
1107 XAPIAN_DEPRECATED_CLASS macros.  Note that you can't deprecate a preprocessor
1108 macro.
1110 For compilers with a suitable mechanism (currently GCC 3.1 or later, and
1111 MSVC 7.0 or later) this causes compile-time warning messages to be emitted for
1112 any use of the deprecated feature.  For compilers without support, the macro
1113 just expands to its argument.
1115 Sometimes a deprecated feature will also be removed from the library itself
1116 (particularly something like a typedef), but if the feature is still used
1117 inside the library (for example, so we can define class methods), then use
1118 XAPIAN_DEPRECATED_EX() or XAPIAN_DEPRECATED_CLASS_EX instead, which will only
1119 issue a warning in user code (this relies on user code including xapian.h
1120 and library code including individual headers)
1122 You must add this line to any API header which uses XAPIAN_DEPRECATED() or
1123 XAPIAN_DEPRECATED_CLASS::
1125     #include <xapian/deprecated.h>
1127 When marking a feature as deprecated, document the deprecation in
1128 docs/deprecation.rst.  When actually removing deprecated features, please tidy
1129 up by removing the inclusion of <xapian/deprecated.h> from any file which no
1130 longer marks any features as deprecated.
1132 The XAPIAN_DEPRECATED() macro should wrap the whole declaration except for the
1133 semicolon and any "definition" part, for example::
1135     XAPIAN_DEPRECATED(int old_function(double arg));
1137     class Foo {
1138       public:
1139         XAPIAN_DEPRECATED(int old_method());
1141         XAPIAN_DEPRECATED(int old_const_method() const);
1143         XAPIAN_DEPRECATED(virtual int old_virt_method()) = 0;
1145         XAPIAN_DEPRECATED(static int old_static_method());
1147         XAPIAN_DEPRECATED(static const int OLD_CONSTANT) = 42;
1148     };
1150 Mark a class as deprecated by inserting ``XAPIAN_DEPRECATED_CLASS`` after the
1151 class keyword like so::
1153     class XAPIAN_DEPRECATED_CLASS Foo {
1154       public:
1155         Foo() { }
1157         // ...
1158     };
1160 With recent versions of GCC (4.4.7 allows this, 3.3.5 doesn't), you can
1161 simply mark a method defined inline in a class with ``XAPIAN_DEPRECATED()``
1162 like so:
1163     
1164     class Foo {
1165       public:
1166         // This fails to compile with GCC 3.3.5, so don't do this!
1167         XAPIAN_DEPRECATED(int old_inline_method()) { return 42; }
1168     };
1169     
1170 Xapian 1.3.x and later require at least GCC 4.7, so you can just use the
1171 approach above.  Xapian 1.2.x aims to support GCC 3.1 and later, so in the
1172 unlikely event of needing to adjust deprecation markers in 1.2.x, you need to
1173 rewrite the above like so:
1175     class Foo {
1176       public:
1177         XAPIAN_DEPRECATED(int old_inline_method());
1178     };
1180     inline int Foo::old_inline_method() { return 42; }
1182 Submitting Patches:
1183 ===================
1185 If you have a patch to fix a problem in Xapian, or to add a new feature,
1186 please send it to us for inclusion.  Any major changes should be discussed
1187 on the xapian-devel mailing list first:
1188 <https://xapian.org/lists>
1190 Also, please read the following section on licensing of patches before
1191 submitting a patch.
1193 We find patches in unified diff format easiest to read.  If you're using
1194 git, then "git diff" is good (or "git format-patch" for a patch series).  If
1195 you're working from a tarball, you can unpack a second clean copy of the files
1196 and compare the two versions with "diff -pruN" (-p reports the function name
1197 for each chunk, -r acts recursively, -u does a unified diff, and -N shows
1198 new files in the diff).  Alternatively "ptardiff" (which comes with perl, at
1199 least on Debian and Ubuntu) can diff against the original tarball, unpacking
1200 it on the fly.
1202 Please set the width of a tab character in your editor to 8 spaces, and use
1203 Unix line endings (i.e. LF, not CR+LF).  Failing to do so will make it much
1204 harder for us to merge in your changes.
1206 We don't currently have a formal coding standards document, but please try
1207 to follow the style of the existing code.  In particular:
1209 * Indent C++ code by 4 spaces for a new indentation level, and set your editor
1210   to tab-fill indentation (with a tab being 8 spaces wide).
1212   As an exception, "public", "protected" and "private" declarations in classes
1213   and structs should be indented by 2 spaces, and the following code should be
1214   indented by 2 more spaces::
1216     class Foo {
1217       public:
1218         method();
1219     };
1221   The rationale for this exception is that class definitions in header files
1222   often have fairly long lines, so losing an indent level to the access
1223   specifier tends to make class definitions less readable.
1225   The default access for a class is always "private", so there's no need
1226   to specify that explicitly - in other words, write this::
1227   
1228     class Foo {
1229         int internal_method();
1231       public:
1232         int external_method();
1233     };
1235   Don't write this::
1237     class Foo {
1238       private:
1239         int internal_method();
1241       public:
1242         int external_method();
1243     };
1245   If a class only contains public methods and data, consider declaring it as a
1246   "struct" (the only difference in C++ is that the default access for a
1247   struct is "public").
1249 * Put a space before the "(" after control flow constructs like "for", "if",
1250   "while", etc.  Don't put a space before the "(" in function calls.  So
1251   write "if (strlen(p) > 10)" not "if(strlen (p) > 10)".
1253 * When "if", "else", "for", "while", "do," "switch", "case", "default", "try",
1254   or "catch" is followed by a block enclosed in braces, the opening brace
1255   should be on the same line, like so::
1257     if (x > 12) {
1258         foo(x);
1259         x = 12;
1260     } else {
1261         bar(x);
1262     }
1264   The rationale for this is that it conserves vertical space (allowing more
1265   code to fit on screen) without reducing readability.
1267 * If you have an empty loop body, use `{ }` rather than `;` as the former
1268   stands out more clearly to the reader (but also consider if the code might be
1269   clearer written a different way).
1271 * Prefer "++i;" to "i++;", "i += 1;", or "i = i + 1".  For simple integer
1272   variables these should generate equivalent (if not identical) code, but if i
1273   is an iterator object then the pre-increment form can be more efficient in
1274   some cases with some compilers.  It's simpler and more consistent to always
1275   use the pre-increment form (unless you make use of the old value which the
1276   post-increment form returns).  For the same reasons, prefer "--i;" to "i--;",
1277   "i -= 1;", or "i = i - 1;".
1279 * Prefer "container.empty()" to "container.size() == 0" (and
1280   "!container.empty()" to "container.size() != 0" or "container.size() > 0").
1281   Finding the size of a container may not be a constant time operation for
1282   all containers (e.g. std::list may not be, and indeed isn't for GCC - see
1283   https://gcc.gnu.org/onlinedocs/libstdc++/manual/containers.html#sequences.list.size).
1284   Also the "empty()" form makes the intent of the test more explicit.
1286 * Prefer not to use "else" when the control flow is diverted elsewhere at the
1287   end of the "if" block (e.g. by "return", "continue", "break", "throw").  This
1288   eliminates a level of indentation from the code in the "else" block, and
1289   typically makes the control flow logic clearer.  For example::
1291     if (x == 0) {
1292         foo();
1293         return;
1294     }
1296     while (x--) {
1297         bar();
1298     }
1300   rather than::
1302     if (x == 0) {
1303         foo();
1304         return;
1305     } else {
1306         while (x--) {
1307             bar();
1308         }
1309     }
1311 * For standard ISO C headers, prefer the C++ form for ISO C headers (e.g.
1312   "#include <cstdlib>" rather than "#include <stdlib.h>") unless there's a good
1313   reason (e.g. portability) to do otherwise.  Be sure to document such
1314   exceptions to avoid another developer changing them to the standard form.
1315   Global exceptions: <signal.h> (lots of POSIX stuff which e.g. Sun's compiler
1316   doesn't provide in <csignal>).
1318 * For standard ISO C++ headers, *always* use the ISO C++ form '#include <list>'
1319   (pre-ISO compilers used '#include <list.h>', but GCC has generated a warning
1320   for this form for years, and GCC 4.3 dropped support entirely).
1322 * Some guidelines for efficient use of std::string:
1324   + When passing an empty string to a method expecting ``const std::string &``
1325     prefer ``std::string()`` to ``""`` or ``std::string("")`` as the first form
1326     is more likely to directly use a special "empty string representation" (it
1327     does with GCC at least).
1329   + To make a string object empty, ``s.resize(0)`` (if you want to keep the
1330     current reserved space) or ``s = string()`` (if you don't) seem the best
1331     options.
1333   + Use ``std::string::assign()`` rather than building a temporary string
1334     object and assigning that.  For example, ``foo = std::string(ptr, len);``
1335     is better written as ``foo.assign(ptr, len);``.
1337   + It's generally better to build up strings using ``+=`` rather than
1338     combining series of components with ``+``.  So ``foo = a + " and " + c`` is
1339     better written as ``foo = a; foo += " and "; foo += c;``.  It's possible
1340     for compilers to handle the former without a lot of temporary string
1341     objects by returning a proxy object to allow the concatenation to happen
1342     lazily, but not all compilers do this, and it's likely to still have some
1343     overhead.  Note that GCC 4.1 seems to produce larger code in some cases for
1344     the latter approach, but it's a definite win with GCC 4.4.
1346   * ``std::string(1, '\0')`` seems to be slightly more efficient than
1347     ``std::string("", 1)`` for constructing a std::string containing a single
1348     ASCII nul character.
1350 * Prefer ``new SomeClass`` to ``new SomeClass()``, since the latter tends to
1351   lead one to write ``SomeClass foo();` which is a function prototype, and not
1352   equivalent to the variable definition ``SomeClass foo``.  However, note that
1353   ``new SomePODType()`` is *not* the same as ``new SomePODType`` (if
1354   SomePODType is a POD (Plain Old Data) type) - the former will zero-initialise
1355   scalar members of SomePODType.
1357 * When catching an exception which is an object, do it by const reference, so
1358   like this::
1360       try {
1361           foo();
1362       } catch (const ErrorClass &e) {
1363           bar(e);
1364       }
1366   Catching by value is bad because it "slices" the object if an object of a
1367   derived type is thrown.  Even if derived types aren't a worry, it also causes
1368   the copy constructor to be called needlessly.
1370   See also: http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.7
1372   A const reference is preferable to a non-const reference as it stops the
1373   object being inadvertently modified.  In the rare cases when you want to
1374   modify the caught object, a non-const reference is OK.
1376 We will do our best to give credit where credit is due - if we have used
1377 patches from you, or received helpful reports or advice, we will add your name
1378 to the AUTHORS file (unless you specifically request us not to).  If you see we
1379 have forgotten to do this, please draw it to our attention so that we can
1380 address the omission.
1382 Licensing of patches
1383 ====================
1385 If you want a patch to be considered for inclusion in the Xapian sources, you
1386 must own the copyright on this patch.  Employers often claim copyright on code
1387 written by their employees (even if the code is written in their spare time),
1388 so please check with your employer if this applies.  Be aware that even if you
1389 are a student your university may try and claim some rights on code which you
1390 write.
1392 Patches which are submitted to Xapian will only be included if the copyright
1393 holder(s) dual-license them under each of the following licences:
1395  - GPL version 2 and all later versions (see the file "COPYING" for details).
1396  - MIT/X license::
1398  Copyright (c) <year> <copyright holders>
1400  Permission is hereby granted, free of charge, to any person obtaining a copy
1401  of this software and associated documentation files (the "Software"), to
1402  deal in the Software without restriction, including without limitation the
1403  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1404  sell copies of the Software, and to permit persons to whom the Software is
1405  furnished to do so, subject to the following conditions:
1407  The above copyright notice and this permission notice shall be included in
1408  all copies or substantial portions of the Software.
1410  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1411  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1412  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1413  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1414  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1415  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
1416  IN THE SOFTWARE.
1418 The current distribution of Xapian contains many files which are only licensed
1419 under the GPL, but we are working towards being able to distribute Xapian under
1420 a more permissive license, and are not willing to accept patches which we will
1421 have to rewrite before this can happen.
1423 Tips for Submitting a Good Patch
1424 ================================
1426 1) Make sure that the documentation is updated
1427 ----------------------------------------------
1429  * API classes, methods, functions, and types must be documented by
1430    documentation comments alongside the declaration in ``include/xapian/*.h``.
1431    These are collated by doxygen - see doxygen's documentation for details
1432    of the supported syntax.  We've decided to prefer to use @ rather than \
1433    to introduce doxygen commands (the choice is essentially arbitrary, but
1434    \ introduces C/C++ escape sequences so @ is likely to make for easier to
1435    read mark up for C/C++ coders).
1437  * The documentation comments don't give users a good overview, so we also
1438    need documentation which gives a good overview of how to achieve particular
1439    tasks.  In particularly, major new functionality should have its own "topic"
1440    document, or extend an existing topic document if more appropriate.
1442  * Internal classes, etc should also be documented by documentation comments
1443    where they are declared.
1445 2) Make sure the tests are right
1446 --------------------------------
1448  * If you're adding a feature, also add feature tests for it.  These both
1449    ensure that the feature isn't broken to start with and detect if later
1450    changes stop it working as intended.
1452  * If you've fixed a bug, make sure there's a regression test which
1453    fails on the existing code and succeeds after your changes.
1455  * Make sure all existing tests continue to pass.
1457 If you don't know how to write tests using the Xapian test rig, then
1458 ask.  It's reasonably simple once you've done it once.  There is a brief
1459 introduction to the Xapian test system in ``docs/tests.html``.
1461 3) Make sure the attributions are right
1462 ---------------------------------------
1464  * If necessary, modify the copyright statement at the top of any
1465    files you've altered. If there is no copyright statement, you may
1466    add one (there are a couple of Makefile.am's and similar that don't
1467    have copyright statements; anything that small doesn't really need
1468    one anyway, so it's a judgement call).  If you've added files which
1469    you've written from scratch, they should include the GPL boilerplate
1470    with your name only.
1472  * If you're not in there, add yourself to the AUTHORS file.
1474 4) Commit
1475 ---------
1477  * Commit:
1478   
1479    + If there's a trac ticket or other reference for the bug, mention it in the
1480      commit message - it's a great help to future developers trying to work out
1481      why a change was made.
1483 5) Consider backporting
1484 -----------------------
1486  * If there's an active release branch, check if the bug is present in that
1487    branch, and if the fix is appropriate to backport - if the fix breaks ABI
1488    compatibility or is very invasive, you need to fix it in a different way
1489    for the release branch, or decide not to backport the fix.
1491 6) Update trac
1492 --------------
1494  * If there's a related trac ticket, update it (if the issue is completely
1495    addressed by the changes you've made, then close it).
1497  * Update the release notes for the most recent release with a copy of the
1498    patch.  If the commit from git applies cleanly, you can just link to
1499    it.  If it fails to apply, please attach an adjusted patch which does.
1500    If there are conflicts in test cases which aren't easy to resolve, it is
1501    acceptable to just drop those changes from the patch if we can still be
1502    confident that the issue is actually fixed by the patch.
1504 API Structure Notes
1505 ===================
1507 We use reference counted pointers for most API classes.  These are implemented
1508 using Xapian::Internal::intrusive_ptr, the implementation of which is exposed
1509 for efficiency, and because it's unlikely we'll need to change it frequently,
1510 if at all.
1512 For the reference counted classes, the API class (e.g. Xapian::Enquire) is
1513 really just a wrapper around a reference counted pointer.  This points to an
1514 internal class (e.g. Xapian::Enquire::Internal).  The reference counted
1515 pointer is a member variable of the API class called internal.  Conceptually
1516 this member is private, though it typically isn't declared as private (this
1517 is to avoid littering the external headers with friend declarations for
1518 non-API classes).
1520 There are a few exceptions to the reference counted structure, such as
1521 MSetIterator and ESetIterator which have an exposed implementation.  Tests show
1522 this makes a substantial difference to speed (it's ~20% faster) in typical
1523 cases of iterator use.
1525 The postfix operator++ for iterators should be implemented inline in terms
1526 of the prefix form as described by Joe Buck on the gcc mailing list
1527 - excerpt from http://article.gmane.org/gmane.comp.gcc.devel:50201 ::
1529         class some_iterator {
1530         public:
1531             // ...
1532             some_iterator& operator++();
1534             some_iterator operator++(int) {
1535                 some_iterator tmp = *this;
1536                 operator++();
1537                 return tmp;
1538             }
1539         };
1541     The compiler is allowed to assume that the copy constructor only does
1542     a copy, and to optimize away unneeded copy operations.  The result
1543     in this case should be that, for some_iterator above, using the
1544     postfix operator without using the result should give code equivalent
1545     to using the prefix operator.
1547     Now, for [GCC 3.4], you'll find that the dead uses of tmp are only
1548     completely optimized away if tmp has only one data member that can fit in a
1549     register.  [GCC 4.0 will do] better, and you should find that this style
1550     comes very close to eliminating any penalty from "incorrect" use of the
1551     postfix form.
1553 Xapian's PostingIterator, TermIterator, PositionIterator, and ValueIterator all
1554 have only one data member which fits in a register.
1556 Handy tips for aiding development
1557 =================================
1559 If you are find you are repeatedly changing the API headers (in include/)
1560 during development, then you may become annoyed that the docs/ subdirectory
1561 will rebuild the doxygen documentation every time you run "make" since this
1562 takes a while.  You can disable this temporarily (if you're using GNU make),
1563 by creating a file "docs/GNUmakefile" containing these two lines::
1566         @echo "Skipping 'make $@' in docs"
1568 Note that the whitespace at the start of the second line needs to be a
1569 single "tab" character!
1571 Don't forget to remove (or rename) this and check the documentation builds
1572 before committing or generating a patch though!
1574 If you are using an editor or other tool capable of running syntax checks as you
1575 work there you can use the `make` target 'check-syntax'. For 'emacs' users this
1576 works well with 'flymake'. Usage from a shell::
1578     make check-syntax check_sources=api/omdatabase.cc
1581 How to make a release
1582 =====================
1584 This is a (hopefully complete) list of the jobs which need doing:
1586 * Email Fabrice Colin and Tim Brody so they can check RPM packaging.
1588 * Check if `config/config.guess` and `config/config.sub` need updating to
1589   more recent versions from http://git.savannah.gnu.org/gitweb/?p=config.git
1591 * Check the revision currently specified in the bootstrap for the common
1592   subdirectory.  Unless there's a good reason, we should release
1593   xapian-core and omega with synchronised versions of the shared files.
1595 * Make sure that any new/changed/removed API methods in xapian-core have been
1596   wrapped/updated/removed in xapian-bindings.
1598 * Update the lists of deprecated/removed API methods in docs/deprecation.rst
1600 * Update the NEWS files using information from the ChangeLog files
1602 * Update the version in configure.ac for each module (xapian-core, omega, and
1603   xapian-bindings), and the library version info in xapian-core's configure.ac
1605 * Make sure the submitters of fixed bugs are mentioned in the "thanks" list in
1606   xapian-core/AUTHORS.  Check the list for the appropriate milestone::
1608    https://trac.xapian.org/query?col=id&col=summary&col=reporter&milestone=1.0.14
1610 * On atreus, tag the source trees for the new revision - use the
1611   git-tag-release script, running it with the new version number, for example:
1613   xapian-maintainer-tools/git-tag-release 1.0.14
1615   This script also generates tarballs for the new release and copies them
1616   across to the website.
1618 * Add the new version to the list of versions in trac:
1619   https://trac.xapian.org/admin/ticket/versions
1621 * Add a new milestone for the version after this one:
1622   https://trac.xapian.org/admin/ticket/milestones
1624 * Mark the current milestone as completed.  In order to do so, any unfixed bugs
1625   with this milestone will need to be moved to another milestone (most likely
1626   the milestone you just added).
1628 * Update the wiki:
1630   Create a new page http://wiki.xapian.org/ReleaseNotes/X.Y.Z and link it into
1631   http://wiki.xapian.org/ReleaseNotes in place of the old current release link,
1632   which should be moved to the archived section.
1634   Also update the roadmap at http://wiki.xapian.org/RoadMap by recording the
1635   date of this release and adding an entry for the next release with an
1636   estimated release date.
1638 * Update the website: `generate` in the CVS module www.xapian.org contains the
1639   latest version and the date it was released.
1641 * Run /home/olly/tmp/xapian-website-update/update_website.sh
1643 * Announce the new version on xapian-discuss
1645 * Have a nice cup of tea!
1647 How to make Debian packages for a new release
1648 =============================================
1650 Debian control files are stored in separate git repositories:
1652 * http://anonscm.debian.org/cgit/collab-maint/xapian-bindings.git
1653 * http://anonscm.debian.org/cgit/collab-maint/xapian-core.git
1654 * http://anonscm.debian.org/cgit/collab-maint/xapian-omega.git
1656 To package a new upstream release, these should be updated as follows:
1658 * If there are any patch files in "debian/patches", check if these have been
1659   incorporated into the new release, and if so remove them and update
1660   "debian/patches/series".
1662 * Update the debian/changelog file, being sure to keep it in the
1663   standard Debian format (the easiest way is to use the dch utility
1664   like so: "dch -v 1.2.19-1".  The new version number should be the
1665   version number of the release followed by "-1" (i.e., a debian
1666   patch number of 1).  The changelog message should indicate that
1667   there is a new upstream release, and should mention any significant
1668   changes in the new release.
1670 * Tag using: ``git tag -s -m 1.2.19-1 1.2.19-1``
1672 * FIXME: Document how to make source packages, or update
1673   ``make-source-packages``.
1675 * FIXME: Document how to build binary packages, or update ``build-packages``.
1677 * Test the packages.
1679 * Run ``debsign build/*_amd64.changes`` to GPG sign the packages.
1681 * Run ``dput build/*_amd64.changes`` to upload them to Debian.
1683 * For the Ubuntu backports::
1685    ./backport-source-packages xapian-core 1.2.19-1 ubuntu
1686    ./backport-source-packages xapian-omega 1.2.19-1 ubuntu
1687    ./backport-source-packages xapian-bindings 1.2.19-1 ubuntu
1689   And once libsearch-xapian-perl is uploaded to Debian unstable::
1691    ./backport-source-packages libsearch-xapian-perl 1.2.19.0-1 ubuntu
1693   Then sign::
1695    debsign build/*99*_source.changes
1697   Upload::
1699    dput xapian-backports build/xapian-core*99*_source.changes
1701   Wait for that to have a chance to build, and then::
1703    dput xapian-backports build/xapian-[bo]*99*_source.changes
1704    dput xapian-backports build/libsearch-xapian-perl*_source.changes
1706 .. vim: syntax=rst