<html lang="en"> <head> <title>R Internals</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="R Internals"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="top" href="#Top"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This manual is for R, version 3.0.2 (2013-09-25). Copyright (C) 1999-2013 R Core Team Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team. --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } body {margin-left: 5%; margin-right: 5%;} H1 { background: white; color: rgb(25%, 25%, 25%); font-family: monospace; font-size: xx-large; text-align: center } H2 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; font-size: x-large; text-align: center } H3 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; font-size: large } H4 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace } span.samp{font-family: monospace} span.command{font-family: monospace} span.option{font-family: monospace} span.file{font-family: monospace} span.env{font-family: monospace} ul { margin-top: 0.25ex; margin-bottom: 0.25ex; } li { margin-top: 0.25ex; margin-bottom: 0.25ex; } p { margin-top: 0.6ex; margin-bottom: 1.2ex; } --></style> </head> <body> <h1 class="settitle">R Internals</h1> <div class="contents"> <h2>Table of Contents</h2> <ul> <li><a name="toc_Top" href="#Top">R Internals</a> <li><a name="toc_R-Internal-Structures" href="#R-Internal-Structures">1 R Internal Structures</a> <ul> <li><a href="#SEXPs">1.1 SEXPs</a> <ul> <li><a href="#SEXPTYPEs">1.1.1 SEXPTYPEs</a> <li><a href="#Rest-of-header">1.1.2 Rest of header</a> <li><a href="#The-_0027data_0027">1.1.3 The ‘data’</a> <li><a href="#Allocation-classes">1.1.4 Allocation classes</a> </li></ul> <li><a href="#Environments-and-variable-lookup">1.2 Environments and variable lookup</a> <ul> <li><a href="#Search-paths">1.2.1 Search paths</a> <li><a href="#Namespaces">1.2.2 Namespaces</a> <li><a href="#Hash-table">1.2.3 Hash table</a> </li></ul> <li><a href="#Attributes">1.3 Attributes</a> <li><a href="#Contexts">1.4 Contexts</a> <li><a href="#Argument-evaluation">1.5 Argument evaluation</a> <ul> <li><a href="#Missingness">1.5.1 Missingness</a> <li><a href="#Dot_002ddot_002ddot-arguments">1.5.2 Dot-dot-dot arguments</a> </li></ul> <li><a href="#Autoprinting">1.6 Autoprinting</a> <li><a href="#The-write-barrier">1.7 The write barrier and the garbage collector</a> <li><a href="#Serialization-Formats">1.8 Serialization Formats</a> <li><a href="#Encodings-for-CHARSXPs">1.9 Encodings for CHARSXPs</a> <li><a href="#The-CHARSXP-cache">1.10 The CHARSXP cache</a> <li><a href="#Warnings-and-errors">1.11 Warnings and errors</a> <li><a href="#S4-objects">1.12 S4 objects</a> <ul> <li><a href="#Representation-of-S4-objects">1.12.1 Representation of S4 objects</a> <li><a href="#S4-classes">1.12.2 S4 classes</a> <li><a href="#S4-methods">1.12.3 S4 methods</a> <li><a href="#Mechanics-of-S4-dispatch">1.12.4 Mechanics of S4 dispatch</a> </li></ul> <li><a href="#Memory-allocators">1.13 Memory allocators</a> <ul> <li><a href="#Internals-of-R_005falloc">1.13.1 Internals of R_alloc</a> </li></ul> <li><a href="#Internal-use-of-global-and-base-environments">1.14 Internal use of global and base environments</a> <ul> <li><a href="#Base-environment">1.14.1 Base environment</a> <li><a href="#Global-environment">1.14.2 Global environment</a> </li></ul> <li><a href="#Modules">1.15 Modules</a> <li><a href="#Visibility">1.16 Visibility</a> <ul> <li><a href="#Hiding-C-entry-points">1.16.1 Hiding C entry points</a> <li><a href="#Variables-in-Windows-DLLs">1.16.2 Variables in Windows DLLs</a> </li></ul> <li><a href="#Lazy-loading">1.17 Lazy loading</a> </li></ul> <li><a name="toc__002eInternal-vs-_002ePrimitive" href="#_002eInternal-vs-_002ePrimitive">2 <code>.Internal</code> vs <code>.Primitive</code></a> <ul> <li><a href="#Special-primitives">2.1 Special primitives</a> <li><a href="#Special-internals">2.2 Special internals</a> <li><a href="#Prototypes-for-primitives">2.3 Prototypes for primitives</a> <li><a href="#Adding-a-primitive">2.4 Adding a primitive</a> </li></ul> <li><a name="toc_Internationalization-in-the-R-sources" href="#Internationalization-in-the-R-sources">3 Internationalization in the R sources</a> <ul> <li><a href="#R-code">3.1 R code</a> <li><a href="#Main-C-code">3.2 Main C code</a> <li><a href="#Windows_002dGUI_002dspecific-code">3.3 Windows-GUI-specific code</a> <li><a href="#OS-X-GUI">3.4 OS X GUI</a> <li><a href="#Updating">3.5 Updating</a> </li></ul> <li><a name="toc_Package-Structure" href="#Package-Structure">4 Structure of an Installed Package</a> <ul> <li><a href="#Metadata">4.1 Metadata</a> <li><a href="#Help">4.2 Help</a> </li></ul> <li><a name="toc_Files" href="#Files">5 Files</a> <li><a name="toc_Graphics-Devices" href="#Graphics-Devices">6 Graphics</a> <ul> <li><a href="#Graphics-devices">6.1 Graphics Devices</a> <ul> <li><a href="#Device-structures">6.1.1 Device structures</a> <li><a href="#Device-capabilities">6.1.2 Device capabilities</a> <li><a href="#Handling-text">6.1.3 Handling text</a> <li><a href="#Conventions">6.1.4 Conventions</a> <li><a href="#_0027Mode_0027">6.1.5 ‘Mode’</a> <li><a href="#Graphics-events">6.1.6 Graphics events</a> <li><a href="#Specific-devices">6.1.7 Specific devices</a> <ul> <li><a href="#X11_0028_0029">6.1.7.1 X11()</a> <li><a href="#windows_0028_0029">6.1.7.2 windows()</a> </li></ul> </li></ul> <li><a href="#Colours">6.2 Colours</a> <li><a href="#Base-graphics">6.3 Base graphics</a> <ul> <li><a href="#Arguments-and-parameters">6.3.1 Arguments and parameters</a> </li></ul> <li><a href="#Grid-graphics">6.4 Grid graphics</a> </li></ul> <li><a name="toc_GUI-consoles" href="#GUI-consoles">7 GUI consoles</a> <ul> <li><a href="#R_002eapp">7.1 R.app</a> </li></ul> <li><a name="toc_Tools" href="#Tools">8 Tools</a> <li><a name="toc_R-coding-standards" href="#R-coding-standards">9 R coding standards</a> <li><a name="toc_Testing-R-code" href="#Testing-R-code">10 Testing R code</a> <li><a name="toc_Use-of-TeX-dialects" href="#Use-of-TeX-dialects">11 Use of TeX dialects</a> <li><a name="toc_Current-and-future-directions" href="#Current-and-future-directions">12 Current and future directions</a> <ul> <li><a href="#Long-vectors">12.1 Long vectors</a> <li><a href="#64_002dbit-types">12.2 64-bit types</a> <li><a href="#Large-matrices">12.3 Large matrices</a> </li></ul> <li><a name="toc_Function-and-variable-index" href="#Function-and-variable-index">Function and variable index</a> <li><a name="toc_Concept-index" href="#Concept-index">Concept index</a> </li></ul> </div> <!-- @end ifnothtml --> <div class="node"> <a name="Top"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#R-Internal-Structures">R Internal Structures</a>, Previous: <a rel="previous" accesskey="p" href="#dir">(dir)</a>, Up: <a rel="up" accesskey="u" href="#dir">(dir)</a> </div> <h2 class="unnumbered">R Internals</h2> <p>This is a guide to the internal structures of R and coding standards for the core team working on R itself. <p>This manual is for R, version 3.0.2 (2013-09-25). <p>Copyright © 1999–2013 R Core Team <blockquote> Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. <p>Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. <p>Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team. </blockquote> <ul class="menu"> <li><a accesskey="1" href="#R-Internal-Structures">R Internal Structures</a> <li><a accesskey="2" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a> <li><a accesskey="3" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a> <li><a accesskey="4" href="#Package-Structure">Package Structure</a> <li><a accesskey="5" href="#Files">Files</a> <li><a accesskey="6" href="#Graphics-Devices">Graphics Devices</a> <li><a accesskey="7" href="#GUI-consoles">GUI consoles</a> <li><a accesskey="8" href="#Tools">Tools</a> <li><a accesskey="9" href="#R-coding-standards">R coding standards</a> <li><a href="#Testing-R-code">Testing R code</a> <li><a href="#Use-of-TeX-dialects">Use of TeX dialects</a> <li><a href="#Current-and-future-directions">Current and future directions</a> <li><a href="#Function-and-variable-index">Function and variable index</a> <li><a href="#Concept-index">Concept index</a> </ul> <div class="node"> <a name="R-Internal-Structures"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a>, Previous: <a rel="previous" accesskey="p" href="#Top">Top</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">1 R Internal Structures</h2> <p>This chapter is the beginnings of documentation about R internal structures. It is written for the core team and others studying the code in the <samp><span class="file">src/main</span></samp> directory. <p>It is a work-in-progress and should be checked against the current version of the source code. Versions for R 2.x.y contain historical comments about when features were introduced: this version is for the 3.x.y series. <ul class="menu"> <li><a accesskey="1" href="#SEXPs">SEXPs</a> <li><a accesskey="2" href="#Environments-and-variable-lookup">Environments and variable lookup</a> <li><a accesskey="3" href="#Attributes">Attributes</a> <li><a accesskey="4" href="#Contexts">Contexts</a> <li><a accesskey="5" href="#Argument-evaluation">Argument evaluation</a> <li><a accesskey="6" href="#Autoprinting">Autoprinting</a> <li><a accesskey="7" href="#The-write-barrier">The write barrier</a> <li><a accesskey="8" href="#Serialization-Formats">Serialization Formats</a> <li><a accesskey="9" href="#Encodings-for-CHARSXPs">Encodings for CHARSXPs</a> <li><a href="#The-CHARSXP-cache">The CHARSXP cache</a> <li><a href="#Warnings-and-errors">Warnings and errors</a> <li><a href="#S4-objects">S4 objects</a> <li><a href="#Memory-allocators">Memory allocators</a> <li><a href="#Internal-use-of-global-and-base-environments">Internal use of global and base environments</a> <li><a href="#Modules">Modules</a> <li><a href="#Visibility">Visibility</a> <li><a href="#Lazy-loading">Lazy loading</a> </ul> <div class="node"> <a name="SEXPs"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Environments-and-variable-lookup">Environments and variable lookup</a>, Previous: <a rel="previous" accesskey="p" href="#R-Internal-Structures">R Internal Structures</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.1 SEXPs</h3> <p><a name="index-SEXP-1"></a><a name="index-SEXPRREC-2"></a>What R users think of as <em>variables</em> or <em>objects</em> are symbols which are bound to a value. The value can be thought of as either a <code>SEXP</code> (a pointer), or the structure it points to, a <code>SEXPREC</code> (and there are alternative forms used for vectors, namely <code>VECSXP</code> pointing to <code>VECTOR_SEXPREC</code> structures). So the basic building blocks of R objects are often called <em>nodes</em>, meaning <code>SEXPREC</code>s or <code>VECTOR_SEXPREC</code>s. <p>Note that the internal structure of the <code>SEXPREC</code> is not made available to R Extensions: rather <code>SEXP</code> is an opaque pointer, and the internals can only be accessed by the functions provided. <p><a name="index-node-3"></a>Both types of node structure have as their first three fields a 32-bit <code>sxpinfo</code> header and then three pointers (to the attributes and the previous and next node in a doubly-linked list), and then some further fields. On a 32-bit platform a node<a rel="footnote" href="#fn-1" name="fnd-1"><sup>1</sup></a> occupies 28 bytes: on a 64-bit platform typically 56 bytes (depending on alignment constraints). <p>The first five bits of the <code>sxpinfo</code> header specify one of up to 32 <code>SEXPTYPE</code>s. <ul class="menu"> <li><a accesskey="1" href="#SEXPTYPEs">SEXPTYPEs</a> <li><a accesskey="2" href="#Rest-of-header">Rest of header</a> <li><a accesskey="3" href="#The-_0027data_0027">The 'data'</a> <li><a accesskey="4" href="#Allocation-classes">Allocation classes</a> </ul> <div class="node"> <a name="SEXPTYPEs"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Rest-of-header">Rest of header</a>, Previous: <a rel="previous" accesskey="p" href="#SEXPs">SEXPs</a>, Up: <a rel="up" accesskey="u" href="#SEXPs">SEXPs</a> </div> <h4 class="subsection">1.1.1 SEXPTYPEs</h4> <p><a name="index-SEXPTYPE-4"></a>Currently <code>SEXPTYPE</code>s 0:10 and 13:25 are in use. Values 11 and 12 were used for internal factors and ordered factors and have since been withdrawn. Note that the <code>SEXPTYPE</code> numbers are stored in <code>save</code>d objects and that the ordering of the types is used, so the gap cannot easily be reused. <p><a name="index-SEXPTYPE-table-5"></a><blockquote> <p><table summary=""><tr align="left"><th valign="top">no </th><th valign="top">SEXPTYPE</th><th valign="top">Description <br></th></tr><tr align="left"><td valign="top"><code>0</code> </td><td valign="top"><code>NILSXP</code> </td><td valign="top"><code>NULL</code> <br></td></tr><tr align="left"><td valign="top"><code>1</code> </td><td valign="top"><code>SYMSXP</code> </td><td valign="top">symbols <br></td></tr><tr align="left"><td valign="top"><code>2</code> </td><td valign="top"><code>LISTSXP</code> </td><td valign="top">pairlists <br></td></tr><tr align="left"><td valign="top"><code>3</code> </td><td valign="top"><code>CLOSXP</code> </td><td valign="top">closures <br></td></tr><tr align="left"><td valign="top"><code>4</code> </td><td valign="top"><code>ENVSXP</code> </td><td valign="top">environments <br></td></tr><tr align="left"><td valign="top"><code>5</code> </td><td valign="top"><code>PROMSXP</code> </td><td valign="top">promises <br></td></tr><tr align="left"><td valign="top"><code>6</code> </td><td valign="top"><code>LANGSXP</code> </td><td valign="top">language objects <br></td></tr><tr align="left"><td valign="top"><code>7</code> </td><td valign="top"><code>SPECIALSXP</code> </td><td valign="top">special functions <br></td></tr><tr align="left"><td valign="top"><code>8</code> </td><td valign="top"><code>BUILTINSXP</code> </td><td valign="top">builtin functions <br></td></tr><tr align="left"><td valign="top"><code>9</code> </td><td valign="top"><code>CHARSXP</code> </td><td valign="top">internal character strings <br></td></tr><tr align="left"><td valign="top"><code>10</code> </td><td valign="top"><code>LGLSXP</code> </td><td valign="top">logical vectors <br></td></tr><tr align="left"><td valign="top"><code>13</code> </td><td valign="top"><code>INTSXP</code> </td><td valign="top">integer vectors <br></td></tr><tr align="left"><td valign="top"><code>14</code> </td><td valign="top"><code>REALSXP</code> </td><td valign="top">numeric vectors <br></td></tr><tr align="left"><td valign="top"><code>15</code> </td><td valign="top"><code>CPLXSXP</code> </td><td valign="top">complex vectors <br></td></tr><tr align="left"><td valign="top"><code>16</code> </td><td valign="top"><code>STRSXP</code> </td><td valign="top">character vectors <br></td></tr><tr align="left"><td valign="top"><code>17</code> </td><td valign="top"><code>DOTSXP</code> </td><td valign="top">dot-dot-dot object <br></td></tr><tr align="left"><td valign="top"><code>18</code> </td><td valign="top"><code>ANYSXP</code> </td><td valign="top">make “any” args work <br></td></tr><tr align="left"><td valign="top"><code>19</code> </td><td valign="top"><code>VECSXP</code> </td><td valign="top">list (generic vector) <br></td></tr><tr align="left"><td valign="top"><code>20</code> </td><td valign="top"><code>EXPRSXP</code> </td><td valign="top">expression vector <br></td></tr><tr align="left"><td valign="top"><code>21</code> </td><td valign="top"><code>BCODESXP</code> </td><td valign="top">byte code <br></td></tr><tr align="left"><td valign="top"><code>22</code> </td><td valign="top"><code>EXTPTRSXP</code> </td><td valign="top">external pointer <br></td></tr><tr align="left"><td valign="top"><code>23</code> </td><td valign="top"><code>WEAKREFSXP</code> </td><td valign="top">weak reference <br></td></tr><tr align="left"><td valign="top"><code>24</code> </td><td valign="top"><code>RAWSXP</code> </td><td valign="top">raw vector <br></td></tr><tr align="left"><td valign="top"><code>25</code> </td><td valign="top"><code>S4SXP</code> </td><td valign="top">S4 classes not of simple type <br></td></tr></table> </blockquote> <p><a name="index-atomic-vector-type-6"></a>Many of these will be familiar from R level: the atomic vector types are <code>LGLSXP</code>, <code>INTSXP</code>, <code>REALSXP</code>, <code>CPLXSP</code>, <code>STRSXP</code> and <code>RAWSXP</code>. Lists are <code>VECSXP</code> and names (also known as symbols) are <code>SYMSXP</code>. Pairlists (<code>LISTSXP</code>, the name going back to the origins of R as a Scheme-like language) are rarely seen at R level, but are for example used for argument lists. Character vectors are effectively lists all of whose elements are <code>CHARSXP</code>, a type that is rarely visible at R level. <p><a name="index-language-object-7"></a><a name="index-argument-list-8"></a>Language objects (<code>LANGSXP</code>) are calls (including formulae and so on). Internally they are pairlists with first element a reference<a rel="footnote" href="#fn-2" name="fnd-2"><sup>2</sup></a> to the function to be called with remaining elements the actual arguments for the call (and with the tags if present giving the specified argument names). Although this is not enforced, many places in the code assume that the pairlist is of length one or more, often without checking. <p><a name="index-expression-9"></a>Expressions are of type <code>EXPRSXP</code>: they are a vector of (usually language) objects most often seen as the result of <code>parse()</code>. <p><a name="index-function-10"></a>The functions are of types <code>CLOSXP</code>, <code>SPECIALSXP</code> and <code>BUILTINSXP</code>: where <code>SEXPTYPE</code>s are stored in an integer these are sometimes lumped into a pseudo-type <code>FUNSXP</code> with code 99. Functions defined via <code>function</code> are of type <code>CLOSXP</code> and have formals, body and environment. <p><a name="index-S4-type-11"></a>The <code>SEXPTYPE</code> <code>S4SXP</code> is for S4 objects which do not consist solely of a simple type such as an atomic vector or function. <div class="node"> <a name="Rest-of-header"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#The-_0027data_0027">The 'data'</a>, Previous: <a rel="previous" accesskey="p" href="#SEXPTYPEs">SEXPTYPEs</a>, Up: <a rel="up" accesskey="u" href="#SEXPs">SEXPs</a> </div> <h4 class="subsection">1.1.2 Rest of header</h4> <p>The <code>sxpinfo</code> header is defined as a 32-bit C structure by <pre class="example"> struct sxpinfo_struct { SEXPTYPE type : 5; /* <span class="roman">discussed above</span> */ unsigned int obj : 1; /* <span class="roman">is this an object with a class attribute?</span> */ unsigned int named : 2; /* <span class="roman">used to control copying</span> */ unsigned int gp : 16; /* <span class="roman">general purpose, see below</span> */ unsigned int mark : 1; /* <span class="roman">mark object as ‘in use’ in GC</span> */ unsigned int debug : 1; unsigned int trace : 1; unsigned int spare : 1; /* <span class="roman">unused</span> */ unsigned int gcgen : 1; /* <span class="roman">generation for GC</span> */ unsigned int gccls : 3; /* <span class="roman">class of node for GC</span> */ }; /* Tot: 32 */ </pre> <p><a name="index-debug-bit-12"></a>The <code>debug</code> bit is used for closures and environments. For closures it is set by <code>debug()</code> and unset by <code>undebug()</code>, and indicates that evaluations of the function should be run under the browser. For environments it indicates whether the browsing is in single-step mode. <p><a name="index-trace-bit-13"></a>The <code>trace</code> bit is used for functions for <code>trace()</code> and for other objects when tracing duplications (see <code>tracemem</code>). <p><a name="index-named-bit-14"></a><a name="index-NAMED-15"></a><a name="index-SET_005fNAMED-16"></a><a name="index-copying-semantics-17"></a>The <code>named</code> field is set and accessed by the <code>SET_NAMED</code> and <code>NAMED</code> macros, and take values <code>0</code>, <code>1</code> and <code>2</code>. R has a ‘call by value’ illusion, so an assignment like <pre class="example"> b <- a </pre> <p class="noindent">appears to make a copy of <code>a</code> and refer to it as <code>b</code>. However, if neither <code>a</code> nor <code>b</code> are subsequently altered there is no need to copy. What really happens is that a new symbol <code>b</code> is bound to the same value as <code>a</code> and the <code>named</code> field on the value object is set (in this case to <code>2</code>). When an object is about to be altered, the <code>named</code> field is consulted. A value of <code>2</code> means that the object must be duplicated before being changed. (Note that this does not say that it is necessary to duplicate, only that it should be duplicated whether necessary or not.) A value of <code>0</code> means that it is known that no other <code>SEXP</code> shares data with this object, and so it may safely be altered. A value of <code>1</code> is used for situations like <pre class="example"> dim(a) <- c(7, 2) </pre> <p class="noindent">where in principle two copies of <code>a</code> exist for the duration of the computation as (in principle) <pre class="example"> a <- `dim<-`(a, c(7, 2)) </pre> <p class="noindent">but for no longer, and so some primitive functions can be optimized to avoid a copy in this case. <p>The <code>gp</code> bits are by definition ‘general purpose’. We label these from 0 to 15. Bits 0–5 and bits 14–15 have been used as described below (mainly from detective work on the sources). <p><a name="index-gp-bits-18"></a><a name="index-LEVELS-19"></a><a name="index-SETLEVELS-20"></a>The bits can be accessed and set by the <code>LEVELS</code> and <code>SETLEVELS</code> macros, which names appear to date back to the internal factor and ordered types and are now used in only a few places in the code. The <code>gp</code> field is serialized/unserialized for the <code>SEXPTYPE</code>s other than <code>NILSXP</code>, <code>SYMSXP</code> and <code>ENVSXP</code>. <p>Bits 14 and 15 of <code>gp</code> are used for ‘fancy bindings’. Bit 14 is used to lock a binding or an environment, and bit 15 is used to indicate an active binding. (For the definition of an ‘active binding’ see the header comments in file <samp><span class="file">src/main/envir.c</span></samp>.) Bit 15 is used for an environment to indicate if it participates in the global cache. <p><a name="index-ARGSUSED-21"></a><a name="index-SET_005fARGUSED-22"></a>The macros <code>ARGUSED</code> and <code>SET_ARGUSED</code> are used when matching actual and formal function arguments, and take the values 0, 1 and 2. <p><a name="index-MISSING-23"></a><a name="index-SET_005fMISSING-24"></a>The macros <code>MISSING</code> and <code>SET_MISSING</code> are used for pairlists of arguments. Four bits are reserved, but only two are used (and exactly what for is not explained). It seems that bit 0 is used by <code>matchArgs</code> to mark missingness on the returned argument list, and bit 1 is used to mark the use of a default value for an argument copied to the evaluation frame of a closure. <p><a name="index-DDVAL-25"></a><a name="index-SET_005fDDVAL-26"></a><a name="index-g_t_002e_002e_002e-argument-27"></a>Bit 0 is used by macros <code>DDVAL</code> and <code>SET_DDVAL</code>. This indicates that a <code>SYMSXP</code> is one of the symbols <code>..n</code> which are implicitly created when <code>...</code> is processed, and so indicates that it may need to be looked up in a <code>DOTSXP</code>. <p><a name="index-PRSEEN-28"></a><a name="index-promise-29"></a>Bit 0 is used for <code>PRSEEN</code>, a flag to indicate if a promise has already been seen during the evaluation of the promise (and so to avoid recursive loops). <p>Bit 0 is used for <code>HASHASH</code>, on the <code>PRINTNAME</code> of the <code>TAG</code> of the frame of an environment. (This bit is not serialized for <code>CHARSXP</code> objects.) <p>Bits 0 and 1 are used for weak references (to indicate `ready to finalize', ‘finalize on exit’). <p>Bit 0 is used by the condition handling system (on a <code>VECSXP</code>) to indicate a calling handler. <p>Bit 4 is turned on to mark S4 objects. <p>Bits 1, 2, 3, 5 and 6 are used for a <code>CHARSXP</code> to denote its encoding. Bit 1 indicates that the <code>CHARSXP</code> should be treated as a set of bytes, not necessarily representing a character in any known encoding. Bits 2, 3 and 6 are used to indicate that it is known to be in Latin-1, UTF-8 or <acronym>ASCII</acronym> respectively. <p>Bit 5 for a <code>CHARSXP</code> indicates that it is hashed by its address, that is <code>NA_STRING</code> or is in the <code>CHARSXP</code> cache (this is not serialized). Only exceptionally is a <code>CHARSXP</code> not hashed, and this should never happen in end-user code. <div class="node"> <a name="The-'data'"></a> <a name="The-_0027data_0027"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Allocation-classes">Allocation classes</a>, Previous: <a rel="previous" accesskey="p" href="#Rest-of-header">Rest of header</a>, Up: <a rel="up" accesskey="u" href="#SEXPs">SEXPs</a> </div> <h4 class="subsection">1.1.3 The ‘data’</h4> <p>A <code>SEXPREC</code> is a C structure containing the 32-bit header as described above, three pointers (to the attributes, previous and next node) and the node data, a union <pre class="example"> union { struct primsxp_struct primsxp; struct symsxp_struct symsxp; struct listsxp_struct listsxp; struct envsxp_struct envsxp; struct closxp_struct closxp; struct promsxp_struct promsxp; } u; </pre> <p class="noindent">All of these alternatives apart from the first (an <code>int</code>) are three pointers, so the union occupies three words. <p><a name="index-vector-type-30"></a>The vector types are <code>RAWSXP</code>, <code>CHARSXP</code>, <code>LGLSXP</code>, <code>INTSXP</code>, <code>REALSXP</code>, <code>CPLXSXP</code>, <code>STRSXP</code>, <code>VECSXP</code>, <code>EXPRSXP</code> and <code>WEAKREFSXP</code>. Remember that such types are a <code>VECTOR_SEXPREC</code>, which again consists of the header and the same three pointers, but followed by two integers giving the length and ‘true length’<a rel="footnote" href="#fn-3" name="fnd-3"><sup>3</sup></a> of the vector, and then followed by the data (aligned as required: on most 32-bit systems with a 24-byte <code>VECTOR_SEXPREC</code> node the data can follow immediately after the node). The data are a block of memory of the appropriate length to store ‘true length’ elements (rounded up to a multiple of 8 bytes, with the 8-byte blocks being the ‘Vcells’ referred in the documentation for <code>gc()</code>). <p>The ‘data’ for the various types are given in the table below. A lot of this is interpretation, i.e. the types are not checked. <dl> <dt><code>NILSXP</code><dd>There is only one object of type <code>NILSXP</code>, <code>R_NilValue</code>, with no data. <br><dt><code>SYMSXP</code><dd>Pointers to three nodes, the name, value and internal, accessed by <code>PRINTNAME</code> (a <code>CHARSXP</code>), <code>SYMVALUE</code> and <code>INTERNAL</code>. (If the symbol's value is a <code>.Internal</code> function, the last is a pointer to the appropriate <code>SEXPREC</code>.) Many symbols have <code>SYMVALUE</code> <code>R_UnboundValue</code>. <br><dt><code>LISTSXP</code><dd>Pointers to the CAR, CDR (usually a <code>LISTSXP</code> or <code>NULL</code>) and TAG (a <code>SYMSXP</code> or <code>NULL</code>). <br><dt><code>CLOSXP</code><dd>Pointers to the formals (a pairlist), the body and the environment. <br><dt><code>ENVSXP</code><dd>Pointers to the frame, enclosing environment and hash table (<code>NULL</code> or a <code>VECSXP</code>). A frame is a tagged pairlist with tag the symbol and CAR the bound value. <br><dt><code>PROMSXP</code><dd>Pointers to the value, expression and environment (in which to evaluate the expression). Once an promise has been evaluated, the environment is set to <code>NULL</code>. <br><dt><code>LANGSXP</code><dd>A special type of <code>LISTSXP</code> used for function calls. (The CAR references the function (perhaps via a symbol or language object), and the CDR the argument list with tags for named arguments.) R-level documentation references to ‘expressions’ / ‘language objects’ are mainly <code>LANGSXP</code>s, but can be symbols (<code>SYMSXP</code>s) or expression vectors (<code>EXPRSXP</code>s). <br><dt><code>SPECIALSXP</code><dt><code>BUILTINSXP</code><dd>An integer giving the offset into the table of primitives/<code>.Internal</code>s. <br><dt><code>CHARSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of bytes (allowing for the <code>nul</code> terminator). <br><dt><code>LGLSXP</code><dt><code>INTSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of C <code>int</code>s (which are 32 bits on all R platforms). <br><dt><code>REALSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of C <code>double</code>s <br><dt><code>CPLXSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of C99 <code>double complex</code>s. <br><dt><code>STRSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of pointers (<code>SEXP</code>s pointing to <code>CHARSXP</code>s). <br><dt><code>DOTSXP</code><dd>A special type of <code>LISTSXP</code> for the value bound to a <code>...</code> symbol: a pairlist of promises. <br><dt><code>ANYSXP</code><dd>This is used as a place holder for any type: there are no actual objects of this type. <br><dt><code>VECSXP</code><dt><code>EXPRSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of pointers. These are internally identical (and identical to <code>STRSXP</code>) but differ in the interpretations placed on the elements. <br><dt><code>BCODESXP</code><dd>For the ‘byte-code’ objects generated by the compiler. <br><dt><code>EXTPTRSXP</code><dd>Has three pointers, to the pointer, the protection value (an R object which if alive protects this object) and a tag (a <code>SYMSXP</code>?). <br><dt><code>WEAKREFSXP</code><dd>A <code>WEAKREFSXP</code> is a special <code>VECSXP</code> of length 4, with elements ‘<samp><span class="samp">key</span></samp>’, ‘<samp><span class="samp">value</span></samp>’, ‘<samp><span class="samp">finalizer</span></samp>’ and ‘<samp><span class="samp">next</span></samp>’. The ‘<samp><span class="samp">key</span></samp>’ is <code>NULL</code>, an environment or an external pointer, and the ‘<samp><span class="samp">finalizer</span></samp>’ is a function or <code>NULL</code>. <br><dt><code>RAWSXP</code><dd><code>length</code>, <code>truelength</code> followed by a block of bytes. <br><dt><code>S4SXP</code><dd>two unused pointers and a tag. </dl> <div class="node"> <a name="Allocation-classes"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#The-_0027data_0027">The 'data'</a>, Up: <a rel="up" accesskey="u" href="#SEXPs">SEXPs</a> </div> <h4 class="subsection">1.1.4 Allocation classes</h4> <p><a name="index-allocation-classes-31"></a>As we have seen, the field <code>gccls</code> in the header is three bits to label up to 8 classes of nodes. Non-vector nodes are of class 0, and ‘small’ vector nodes are of classes 1 to 6, with ‘large’ vector nodes being of class 7. The ‘small’ vector nodes are able to store vector data of up to 8, 16, 32, 48, 64 and 128 bytes: larger vectors are <code>malloc</code>-ed individually whereas the ‘small’ nodes are allocated from pages of about 2000 bytes. <div class="node"> <a name="Environments-and-variable-lookup"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Attributes">Attributes</a>, Previous: <a rel="previous" accesskey="p" href="#SEXPs">SEXPs</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.2 Environments and variable lookup</h3> <p><a name="index-environment-32"></a><a name="index-variable-lookup-33"></a>What users think of as ‘variables’ are symbols which are bound to objects in ‘environments’. The word ‘environment’ is used ambiguously in R to mean <em>either</em> the frame of an <code>ENVSXP</code> (a pairlist of symbol-value pairs) <em>or</em> an <code>ENVSXP</code>, a frame plus an enclosure. <p><a name="index-user-databases-34"></a>There are additional places that ‘variables’ can be looked up, called ‘user databases’ in comments in the code. These seem undocumented in the R sources, but apparently refer to the <strong>RObjectTable</strong> package at <a href="http://www.omegahat.org/RObjectTables/">http://www.omegahat.org/RObjectTables/</a>. <p><a name="index-base-environment-35"></a><a name="index-environment_002c-base-36"></a>The base environment is special. There is an <code>ENVSXP</code> environment with enclosure the empty environment <code>R_EmptyEnv</code>, but the frame of that environment is not used. Rather its bindings are part of the global symbol table, being those symbols in the global symbol table whose values are not <code>R_UnboundValue</code>. When R is started the internal functions are installed (by C code) in the symbol table, with primitive functions having values and <code>.Internal</code> functions having what would be their values in the field accessed by the <code>INTERNAL</code> macro. Then <code>.Platform</code> and <code>.Machine</code> are computed and the base package is loaded into the base environment followed by the system profile. <p>The frames of environments (and the symbol table) are normally hashed for faster access (including insertion and deletion). <p>By default R maintains a (hashed) global cache of ‘variables’ (that is symbols and their bindings) which have been found, and this refers only to environments which have been marked to participate, which consists of the global environment (aka the user workspace), the base environment plus environments<a rel="footnote" href="#fn-4" name="fnd-4"><sup>4</sup></a> which have been <code>attach</code>ed. When an environment is either <code>attach</code>ed or <code>detach</code>ed, the names of its symbols are flushed from the cache. The cache is used whenever searching for variables from the global environment (possibly as part of a recursive search). <ul class="menu"> <li><a accesskey="1" href="#Search-paths">Search paths</a> <li><a accesskey="2" href="#Namespaces">Namespaces</a> <li><a accesskey="3" href="#Hash-table">Hash table</a> </ul> <div class="node"> <a name="Search-paths"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Namespaces">Namespaces</a>, Previous: <a rel="previous" accesskey="p" href="#Environments-and-variable-lookup">Environments and variable lookup</a>, Up: <a rel="up" accesskey="u" href="#Environments-and-variable-lookup">Environments and variable lookup</a> </div> <h4 class="subsection">1.2.1 Search paths</h4> <p><a name="index-search-path-37"></a>S has the notion of a ‘search path’: the lookup for a ‘variable’ leads (possibly through a series of frames) to the ‘session frame’ the ‘working directory’ and then along the search path. The search path is a series of databases (as returned by <code>search()</code>) which contain the system functions (but not necessarily at the end of the path, as by default the equivalent of packages are added at the end). <p>R has a variant on the S model. There is a search path (also returned by <code>search()</code>) which consists of the global environment (aka user workspace) followed by environments which have been attached and finally the base environment. Note that unlike S it is not possible to attach environments before the workspace nor after the base environment. <p>However, the notion of variable lookup is more general in R, hence the plural in the title of this subsection. Since environments have enclosures, from any environment there is a search path found by looking in the frame, then the frame of its enclosure and so on. Since loops are not allowed, this process will eventually terminate: it can terminate at either the base environment or the empty environment. (It can be conceptually simpler to think of the search always terminating at the empty environment, but with an optimization to stop at the base environment.) So the ‘search path’ describes the chain of environments which is traversed once the search reaches the global environment. <div class="node"> <a name="Namespaces"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Hash-table">Hash table</a>, Previous: <a rel="previous" accesskey="p" href="#Search-paths">Search paths</a>, Up: <a rel="up" accesskey="u" href="#Environments-and-variable-lookup">Environments and variable lookup</a> </div> <h4 class="subsection">1.2.2 Namespaces</h4> <p><a name="index-namespace-38"></a>Namespaces are environments associated with packages (and once again the base package is special and will be considered separately). A package <var>pkg</var> with a namespace defines two environments <code>namespace:</code><var>pkg</var> and <code>package:</code><var>pkg</var>: it is <code>package:</code><var>pkg</var> that can be <code>attach</code>ed and form part of the search path. <p>The objects defined by the R code in the package are symbols with bindings in the <code>namespace:</code><var>pkg</var> environment. The <code>package:</code><var>pkg</var> environment is populated by selected symbols from the <code>namespace:</code><var>pkg</var> environment (the exports). The enclosure of this environment is an environment populated with the explicit imports from other namespaces, and the enclosure of <em>that</em> environment is the base namespace. (So the illusion of the imports being in the namespace environment is created via the environment tree.) The enclosure of the base namespace is the global environment, so the search from a package namespace goes via the (explicit and implicit) imports to the standard ‘search path’. <p><a name="index-base-namespace-39"></a><a name="index-namespace_002c-base-40"></a><a name="index-R_005fBaseNamespace-41"></a>The base namespace environment <code>R_BaseNamespace</code> is another <code>ENVSXP</code> that is special-cased. It is effectively the same thing as the base environment <code>R_BaseEnv</code> <em>except</em> that its enclosure is the global environment rather than the empty environment: the internal code diverts lookups in its frame to the global symbol table. <div class="node"> <a name="Hash-table"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Namespaces">Namespaces</a>, Up: <a rel="up" accesskey="u" href="#Environments-and-variable-lookup">Environments and variable lookup</a> </div> <h4 class="subsection">1.2.3 Hash table</h4> <p>Environments in R usually have a hash table, and nowadays that is the default in <code>new.env()</code>. It is stored as a <code>VECSXP</code> where <code>length</code> is used for the allocated size of the table and <code>truelength</code> is the number of primary slots in use—the pointer to the <code>VECSXP</code> is part of the header of a <code>SEXP</code> of type <code>ENVSXP</code>, and this points to <code>R_NilValue</code> if the environment is not hashed. <p>For the pros and cons of hashing, see a basic text on Computer Science. <p>The code to implement hashed environments is in <samp><span class="file">src/main/envir.c</span></samp>. Unless set otherwise (e.g. by the <code>size</code> argument of <code>new.env()</code>) the initial table size is <code>29</code>. The table will be resized by a factor of 1.2 once the load factor (the proportion of primary slots in use) reaches 85%. <p>The hash chains are stored as pairlist elements of the <code>VECSXP</code>: items are inserted at the front of the pairlist. Hashing is principally designed for fast searching of environments, which are from time to time added to but rarely deleted from, so items are not actually deleted but have their value set to <code>R_UnboundValue</code>. <div class="node"> <a name="Attributes"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Contexts">Contexts</a>, Previous: <a rel="previous" accesskey="p" href="#Environments-and-variable-lookup">Environments and variable lookup</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.3 Attributes</h3> <p><a name="index-attributes-42"></a><a name="index-ATTRIB-43"></a><a name="index-SET_005fATTRIB-44"></a><a name="index-DUPLICATE_005fATTRIB-45"></a>As we have seen, every <code>SEXPREC</code> has a pointer to the attributes of the node (default <code>R_NilValue</code>). The attributes can be accessed/set by the macros/functions <code>ATTRIB</code> and <code>SET_ATTRIB</code>, but such direct access is normally only used to check if the attributes are <code>NULL</code> or to reset them. Otherwise access goes through the functions <code>getAttrib</code> and <code>setAttrib</code> which impose restrictions on the attributes. One thing to watch is that if you copy attributes from one object to another you may (un)set the <code>"class"</code> attribute and so need to copy the object and S4 bits as well. There is a macro/function <code>DUPLICATE_ATTRIB</code> to automate this. <p>Note that the ‘attributes’ of a <code>CHARSXP</code> are used as part of the management of the <code>CHARSXP</code> cache: of course <code>CHARSXP</code>'s are not user-visible but C-level code might look at their attributes. <p>The code assumes that the attributes of a node are either <code>R_NilValue</code> or a pairlist of non-zero length (and this is checked by <code>SET_ATTRIB</code>). The attributes are named (via tags on the pairlist). The replacement function <code>attributes<-</code> ensures that <code>"dim"</code> precedes <code>"dimnames"</code> in the pairlist. Attribute <code>"dim"</code> is one of several that is treated specially: the values are checked, and any <code>"names"</code> and <code>"dimnames"</code> attributes are removed. Similarly, you cannot set <code>"dimnames"</code> without having set <code>"dim"</code>, and the value assigned must be a list of the correct length and with elements of the correct lengths (and all zero-length elements are replaced by <code>NULL</code>). <p>The other attributes which are given special treatment are <code>"names"</code>, <code>"class"</code>, <code>"tsp"</code>, <code>"comment"</code> and <code>"row.names"</code>. For pairlist-like objects the names are not stored as an attribute but (as symbols) as the tags: however the R interface makes them look like conventional attributes, and for one-dimensional arrays they are stored as the first element of the <code>"dimnames"</code> attribute. The C code ensures that the <code>"tsp"</code> attribute is an <code>REALSXP</code>, the frequency is positive and the implied length agrees with the number of rows of the object being assigned to. Classes and comments are restricted to character vectors, and assigning a zero-length comment or class removes the attribute. Setting or removing a <code>"class"</code> attribute sets the object bit appropriately. Integer row names are converted to and from the internal compact representation. <p><a name="index-copying-semantics-46"></a>Care needs to be taken when adding attributes to objects of the types with non-standard copying semantics. There is only one object of type <code>NILSXP</code>, <code>R_NilValue</code>, and that should never have attributes (and this is enforced in <code>installAttrib</code>). For environments, external pointers and weak references, the attributes should be relevant to all uses of the object: it is for example reasonable to have a name for an environment, and also a <code>"path"</code> attribute for those environments populated from R code in a package. <p><a name="index-attributes_002c-preserving-47"></a><a name="index-preserving-attributes-48"></a>When should attributes be preserved under operations on an object? Becker, Chambers & Wilks (1988, pp. 144–6) give some guidance. Scalar functions (those which operate element-by-element on a vector and whose output is similar to the input) should preserve attributes (except perhaps class, and if they do preserve class they need to preserve the <code>OBJECT</code> and S4 bits). Binary operations normally call <a name="index-copyMostAttributes-49"></a><code>copyMostAttributes</code> to copy most attributes from the longer argument (and if they are of the same length from both, preferring the values on the first). Here ‘most’ means all except the <code>names</code>, <code>dim</code> and <code>dimnames</code> which are set appropriately by the code for the operator. <p>Subsetting (other than by an empty index) generally drops all attributes except <code>names</code>, <code>dim</code> and <code>dimnames</code> which are reset as appropriate. On the other hand, subassignment generally preserves such attributes even if the length is changed. Coercion drops all attributes. For example: <pre class="example"> > x <- structure(1:8, names=letters[1:8], comm="a comment") > x[] a b c d e f g h 1 2 3 4 5 6 7 8 attr(,"comm") [1] "a comment" > x[1:3] a b c 1 2 3 > x[3] <- 3 > x a b c d e f g h 1 2 3 4 5 6 7 8 attr(,"comm") [1] "a comment" > x[9] <- 9 > x a b c d e f g h 1 2 3 4 5 6 7 8 9 attr(,"comm") [1] "a comment" </pre> <div class="node"> <a name="Contexts"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Argument-evaluation">Argument evaluation</a>, Previous: <a rel="previous" accesskey="p" href="#Attributes">Attributes</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.4 Contexts</h3> <p><a name="index-context-50"></a><em>Contexts</em> are the internal mechanism used to keep track of where a computation has got to (and from where), so that control-flow constructs can work and reasonable information can be produced on error conditions (such as <em>via</em> traceback), and otherwise (the <code>sys.</code><var>xxx</var> functions). <p>Execution contexts are a stack of C <code>structs</code>: <pre class="example"> typedef struct RCNTXT { struct RCNTXT *nextcontext; /* <span class="roman">The next context up the chain</span> */ int callflag; /* <span class="roman">The context ‘type’</span> */ JMP_BUF cjmpbuf; /* <span class="roman">C stack and register information</span> */ int cstacktop; /* <span class="roman">Top of the pointer protection stack</span> */ int evaldepth; /* <span class="roman">Evaluation depth at inception</span> */ SEXP promargs; /* <span class="roman">Promises supplied to closure</span> */ SEXP callfun; /* <span class="roman">The closure called</span> */ SEXP sysparent; /* <span class="roman">Environment the closure was called from</span> */ SEXP call; /* <span class="roman">The call that effected this context</span> */ SEXP cloenv; /* <span class="roman">The environment</span> */ SEXP conexit; /* <span class="roman">Interpreted </span><code>on.exit</code><span class="roman"> code</span> */ void (*cend)(void *); /* <span class="roman">C </span><code>on.exit</code><span class="roman"> thunk</span> */ void *cenddata; /* <span class="roman">Data for C </span><code>on.exit</code><span class="roman"> thunk</span> */ char *vmax; /* <span class="roman">Top of the </span><code>R_alloc</code><span class="roman"> stack</span> */ int intsusp; /* <span class="roman">Interrupts are suspended</span> */ SEXP handlerstack; /* <span class="roman">Condition handler stack</span> */ SEXP restartstack; /* <span class="roman">Stack of available restarts</span> */ struct RPRSTACK *prstack; /* <span class="roman">Stack of pending promises</span> */ } RCNTXT, *context; </pre> <p class="noindent">plus additional fields for the byte-code compiler. The ‘types’ are from <pre class="example"> enum { CTXT_TOPLEVEL = 0, /* <span class="roman">toplevel context</span> */ CTXT_NEXT = 1, /* <span class="roman">target for </span><code>next</code> */ CTXT_BREAK = 2, /* <span class="roman">target for </span><code>break</code> */ CTXT_LOOP = 3, /* <code>break</code><span class="roman"> or </span><code>next</code><span class="roman"> target</span> */ CTXT_FUNCTION = 4, /* <span class="roman">function closure</span> */ CTXT_CCODE = 8, /* <span class="roman">other functions that need error cleanup</span> */ CTXT_RETURN = 12, /* <code>return()</code><span class="roman"> from a closure</span> */ CTXT_BROWSER = 16, /* <span class="roman">return target on exit from browser</span> */ CTXT_GENERIC = 20, /* <span class="roman">rather, running an S3 method</span> */ CTXT_RESTART = 32, /* <span class="roman">a call to </span><code>restart</code><span class="roman"> was made from a closure</span> */ CTXT_BUILTIN = 64 /* <span class="roman">builtin internal function</span> */ }; </pre> <p class="noindent">where the <code>CTXT_FUNCTION</code> bit is on wherever function closures are involved. <p>Contexts are created by a call to <code>begincontext</code> and ended by a call to <code>endcontext</code>: code can search up the stack for a particular type of context via <code>findcontext</code> (and jump there) or jump to a specific context via <code>R_JumpToContext</code>. <code>R_ToplevelContext</code> is the ‘idle’ state (normally the command prompt), and <code>R_GlobalContext</code> is the top of the stack. <p>Note that whilst calls to closures and builtins set a context, those to special internal functions never do. <p><a name="index-UseMethod-51"></a><a name="index-method-dispatch-52"></a>Dispatching from a S3 generic (via <code>UseMethod</code> or its internal equivalent) or calling <code>NextMethod</code> sets the context type to <code>CTXT_GENERIC</code>. This is used to set the <code>sysparent</code> of the method call to that of the <code>generic</code>, so the method appears to have been called in place of the generic rather than from the generic. <p>The R <code>sys.frame</code> and <code>sys.call</code> functions work by counting calls to closures (type <code>CTXT_FUNCTION</code>) from either end of the context stack. <p>Note that the <code>sysparent</code> element of the structure is not the same thing as <code>sys.parent()</code>. Element <code>sysparent</code> is primarily used in managing changes of the function being evaluated, i.e. by <code>Recall</code> and method dispatch. <p><code>CTXT_CCODE</code> contexts are currently used in <code>cat()</code>, <code>load()</code>, <code>scan()</code> and <code>write.table()</code> (to close the connection on error), by <code>PROTECT</code>, serialization (to recover from errors, e.g. free buffers) and within the error handling code (to raise the C stack limit and reset some variables). <div class="node"> <a name="Argument-evaluation"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Autoprinting">Autoprinting</a>, Previous: <a rel="previous" accesskey="p" href="#Contexts">Contexts</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.5 Argument evaluation</h3> <p><a name="index-argument-evaluation-53"></a>As we have seen, functions in R come in three types, closures (<code>SEXPTYPE</code> <code>CLOSXP</code>), specials (<code>SPECIALSXP</code>) and builtins (<code>BUILTINSXP</code>). In this section we consider when (and if) the actual arguments of function calls are evaluated. The rules are different for the internal (special/builtin) and R-level functions (closures). <p>For a call to a closure, the actual and formal arguments are matched and a matched call (another <code>LANGSXP</code>) is constructed. This process first replaces the actual argument list by a list of promises to the values supplied. It then constructs a new environment which contains the names of the formal parameters matched to actual or default values: all the matched values are promises, the defaults as promises to be evaluated in the environment just created. That environment is then used for the evaluation of the body of the function, and promises will be forced (and hence actual or default arguments evaluated) when they are encountered. <a name="index-NAMED-54"></a>(Evaluating a promise sets <code>NAMED = 2</code> on its value, so if the argument was a symbol its binding is regarded as having multiple references during the evaluation of the closure call.) <p>If the closure is an S3 generic (that is, contains a call to <code>UseMethod</code>) the evaluation process is the same until the <code>UseMethod</code> call is encountered. At that point the argument on which to do dispatch (normally the first) will be evaluated if it has not been already. If a method has been found which is a closure, a new evaluation environment is created for it containing the matched arguments of the method plus any new variables defined so far during the evaluation of the body of the generic. (Note that this means changes to the values of the formal arguments in the body of the generic are discarded when calling the method, but <em>actual</em> argument promises which have been forced retain the values found when they were forced. On the other hand, missing arguments have values which are promises to use the default supplied by the method and not by the generic.) If the method found is a primitive it is called with the matched argument list of promises (possibly already forced) used for the generic. <p><a name="index-builtin-function-55"></a><a name="index-special-function-56"></a><a name="index-primitive-function-57"></a><a name="index-g_t_002eInternal-function-58"></a>The essential difference<a rel="footnote" href="#fn-5" name="fnd-5"><sup>5</sup></a> between special and builtin functions is that the arguments of specials are not evaluated before the C code is called, and those of builtins are. Note that being a special/builtin is separate from being primitive or <code>.Internal</code>: <code>quote</code> is a special primitive, <code>+</code> is a builtin primitive, <code>cbind</code> is a special <code>.Internal</code> and <code>grep</code> is a builtin <code>.Internal</code>. <p><a name="index-generic_002c-internal-59"></a><a name="index-DispatchOrEval-60"></a>Many of the internal functions are internal generics, which for specials means that they do not evaluate their arguments on call, but the C code starts with a call to <code>DispatchOrEval</code>. The latter evaluates the first argument, and looks for a method based on its class. (If S4 dispatch is on, S4 methods are looked for first, even for S3 classes.) If it finds a method, it dispatches to that method with a call based on promises to evaluate the remaining arguments. If no method is found, the remaining arguments are evaluated before return to the internal generic. <p><a name="index-generic_002c-generic-61"></a><a name="index-DispatchGeneric-62"></a>The other way that internal functions can be generic is to be group generic. Most such functions are builtins (so immediately evaluate all their arguments), and all contain a call to the C function <code>DispatchGeneric</code>. There are some peculiarities over the number of arguments for the <code>"Math"</code> group generic, with some members allowing only one argument, some having two (with a default for the second) and <code>trunc</code> allows one or more but the default method only accepts one. <ul class="menu"> <li><a accesskey="1" href="#Missingness">Missingness</a> <li><a accesskey="2" href="#Dot_002ddot_002ddot-arguments">Dot-dot-dot arguments</a> </ul> <div class="node"> <a name="Missingness"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Dot_002ddot_002ddot-arguments">Dot-dot-dot arguments</a>, Previous: <a rel="previous" accesskey="p" href="#Argument-evaluation">Argument evaluation</a>, Up: <a rel="up" accesskey="u" href="#Argument-evaluation">Argument evaluation</a> </div> <h4 class="subsection">1.5.1 Missingness</h4> <p><a name="index-missingness-63"></a>Actual arguments to (non-internal) R functions can be fewer than are required to match the formal arguments of the function. Having unmatched formal arguments will not matter if the argument is never used (by lazy evaluation), but when the argument is evaluated, either its default value is evaluated (within the evaluation environment of the function) or an error is thrown with a message along the lines of <pre class="example"> argument "foobar" is missing, with no default </pre> <p><a name="index-MISSING-64"></a><a name="index-R_005fMissingArg-65"></a>Internally missingness is handled by two mechanisms. The object <code>R_MissingArg</code> is used to indicate that a formal argument has no (default) value. When matching the actual arguments to the formal arguments, a new argument list is constructed from the formals all of whose values are <code>R_MissingArg</code> with the first <code>MISSING</code> bit set. Then whenever a formal argument is matched to an actual argument, the corresponding member of the new argument list has its value set to that of the matched actual argument, and if that is not <code>R_MissingArg</code> the missing bit is unset. <p>This new argument list is used to form the evaluation frame for the function, and if named arguments are subsequently given a new value (before they are evaluated) the missing bit is cleared. <p>Missingness of arguments can be interrogated via the <code>missing()</code> function. An argument is clearly missing if its missing bit is set or if the value is <code>R_MissingArg</code>. However, missingness can be passed on from function to function, for using a formal argument as an actual argument in a function call does not count as evaluation. So <code>missing()</code> has to examine the value (a promise) of a non-yet-evaluated formal argument to see if it might be missing, which might involve investigating a promise and so on <small class="dots">...</small>. <p>Special primitives also need to handle missing arguments, and in some case (e.g. <code>log</code>) that is why they are special and not builtin. This is usually done by testing if an argument's value is <code>R_MissingArg</code>. <div class="node"> <a name="Dot-dot-dot-arguments"></a> <a name="Dot_002ddot_002ddot-arguments"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Missingness">Missingness</a>, Up: <a rel="up" accesskey="u" href="#Argument-evaluation">Argument evaluation</a> </div> <h4 class="subsection">1.5.2 Dot-dot-dot arguments</h4> <p><a name="index-g_t_002e_002e_002e-argument-66"></a>Dot-dot-dot arguments are convenient when writing functions, but complicate the internal code for argument evaluation. <p>The formals of a function with a <code>...</code> argument represent that as a single argument like any other argument, with tag the symbol <code>R_DotsSymbol</code>. When the actual arguments are matched to the formals, the value of the <code>...</code> argument is of <code>SEXPTYPE</code> <code>DOTSXP</code>, a pairlist of promises (as used for matched arguments) but distinguished by the <code>SEXPTYPE</code>. <p>Recall that the evaluation frame for a function initially contains the <var>name</var><code>=</code><var>value</var> pairs from the matched call, and hence this will be true for <code>...</code> as well. The value of <code>...</code> is a (special) pairlist whose elements are referred to by the special symbols <code>..1</code>, <code>..2</code>, <small class="dots">...</small> which have the <code>DDVAL</code> bit set: when one of these is encountered it is looked up (via <code>ddfindVar</code>) in the value of the <code>...</code> symbol in the evaluation frame. <p>Values of arguments matched to a <code>...</code> argument can be missing. <p>Special primitives may need to handle <code>...</code> arguments: see for example the internal code of <code>switch</code> in file <samp><span class="file">src/main/builtin.c</span></samp>. <div class="node"> <a name="Autoprinting"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#The-write-barrier">The write barrier</a>, Previous: <a rel="previous" accesskey="p" href="#Argument-evaluation">Argument evaluation</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.6 Autoprinting</h3> <p><a name="index-autoprinting-67"></a><a name="index-R_005fVisible-68"></a> Whether the returned value of a top-level R expression is printed is controlled by the global boolean variable <code>R_Visible</code>. This is set (to true or false) on entry to all primitive and internal functions based on the <code>eval</code> column of the table in file <samp><span class="file">src/main/names.c</span></samp>: the appropriate setting can be extracted by the macro <code>PRIMPRINT</code>. <a name="index-PRIMPRINT-69"></a> <a name="index-invisible-70"></a>The R primitive function <code>invisible</code> makes use of this mechanism: it just sets <code>R_Visible = FALSE</code> before entry and returns its argument. <p>For most functions the intention will be that the setting of <code>R_Visible</code> when they are entered is the setting used when they return, but there need to be exceptions. The R functions <code>identify</code>, <code>options</code>, <code>system</code> and <code>writeBin</code> determine whether the result should be visible from the arguments or user action. Other functions themselves dispatch functions which may change the visibility flag: examples<a rel="footnote" href="#fn-6" name="fnd-6"><sup>6</sup></a> are <code>.Internal</code>, <code>do.call</code>, <code>eval</code>, <code>withVisible</code>, <code>if</code>, <code>NextMethod</code>, <code>Recall</code>, <code>recordGraphics</code>, <code>standardGeneric</code>, <code>switch</code> and <code>UseMethod</code>. <p>‘Special’ primitive and internal functions evaluate their arguments internally <em>after</em> <code>R_Visible</code> has been set, and evaluation of the arguments (e.g. an assignment as in PR#9263)) can change the value of the flag. <p>The <code>R_Visible</code> flag can also get altered during the evaluation of a function, with comments in the code about <code>warning</code>, <code>writeChar</code> and graphics functions calling <code>GText</code> (PR#7397). (Since the C-level function <code>eval</code> sets <code>R_Visible</code>, this could apply to any function calling it. Since it is called when evaluating promises, even object lookup can change <code>R_Visible</code>.) Internal and primitive functions force the documented setting of <code>R_Visible</code> on return, unless the C code is allowed to change it (the exceptions above are indicated by <code>PRIMPRINT</code> having value 2). <p>The actual autoprinting is done by <code>PrintValueEnv</code> in file <samp><span class="file">print.c</span></samp>. If the object to be printed has the S4 bit set and S4 methods dispatch is on, <code>show</code> is called to print the object. Otherwise, if the object bit is set (so the object has a <code>"class"</code> attribute), <code>print</code> is called to dispatch methods: for objects without a class the internal code of <code>print.default</code> is called. <div class="node"> <a name="The-write-barrier"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Serialization-Formats">Serialization Formats</a>, Previous: <a rel="previous" accesskey="p" href="#Autoprinting">Autoprinting</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.7 The write barrier and the garbage collector</h3> <p><a name="index-write-barrier-71"></a><a name="index-garbage-collector-72"></a>R has long had a generational garbage collector, and bit <code>gcgen</code> in the <code>sxpinfo</code> header is used in the implementation of this. This is used in conjunction with the <code>mark</code> bit to identify two previous generations. <p>There are three levels of collections. Level 0 collects only the youngest generation, level 1 collects the two youngest generations and level 2 collects all generations. After 20 level-0 collections the next collection is at level 1, and after 5 level-1 collections at level 2. Further, if a level-<var>n</var> collection fails to provide 20% free space (for each of nodes and the vector heap), the next collection will be at level <var>n+1</var>. (The R-level function <code>gc()</code> performs a level-2 collection.) <p>A generational collector needs to efficiently ‘age’ the objects, especially list-like objects (including <code>STRSXP</code>s). This is done by ensuring that the elements of a list are regarded as at least as old as the list <em>when they are assigned</em>. This is handled by the functions <code>SET_VECTOR_ELT</code> and <code>SET_STRING_ELT</code>, which is why they are functions and not macros. Ensuring the integrity of such operations is termed the <dfn>write barrier</dfn> and is done by making the <code>SEXP</code> opaque and only providing access via functions (which cannot be used as lvalues in assignments in C). <p>All code in R extensions is by default behind the write barrier. The only way to obtain direct access to the internals of the <code>SEXPREC</code>s is to define ‘<samp><span class="samp">USE_RINTERNALS</span></samp>’ before including header file <samp><span class="file">Rinternals.h</span></samp>, which is normally defined in <samp><span class="file">Defn.h</span></samp>. To enable a check on the way that the access is used, R can be compiled with flag <samp><span class="option">--enable-strict-barrier</span></samp> which ensures that header <samp><span class="file">Defn.h</span></samp> does not define ‘<samp><span class="samp">USE_RINTERNALS</span></samp>’ and hence that <code>SEXP</code> is opaque in most of R itself. (There are some necessary exceptions: foremost in file <samp><span class="file">memory.c</span></samp> where the accessor functions are defined and also in file <samp><span class="file">size.c</span></samp> which needs access to the sizes of the internal structures.) <p>For background papers see <a href="http://www.stat.uiowa.edu/~luke/R/barrier.html">http://www.stat.uiowa.edu/~luke/R/barrier.html</a> and <a href="http://www.stat.uiowa.edu/~luke/R/gengcnotes.html">http://www.stat.uiowa.edu/~luke/R/gengcnotes.html</a>. <div class="node"> <a name="Serialization-Formats"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Encodings-for-CHARSXPs">Encodings for CHARSXPs</a>, Previous: <a rel="previous" accesskey="p" href="#The-write-barrier">The write barrier</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.8 Serialization Formats</h3> <p><a name="index-serialization-73"></a>Serialized versions of R objects are used by <code>load</code>/<code>save</code> and also at a slightly lower level by <code>saveRDS</code>/<code>readRDS</code> (and their earlier ‘internal’ dot-name versions) and <code>serialize</code>/<code>unserialize</code>. These differ in what they serialize to (a file, a connection, a raw vector) and whether they are intended to serialize a single object or a collection of objects (typically the workspace). <code>save</code> writes a header at the beginning of the file (a single LF-terminated line) which the lower-level versions do not. <p><code>save</code> and <code>saveRDS</code> allow various forms of compression, and <samp><span class="command">gzip</span></samp> compression is the default (except for <acronym>ASCII</acronym> saves). Compression is applied to the whole file stream, including the headers, so serialized files can be uncompressed or re-compressed by external programs. Both <code>load</code> and <code>readRDS</code> can read <samp><span class="command">gzip</span></samp>, <samp><span class="command">bzip2</span></samp> and <samp><span class="command">xz</span></samp> forms of compression when reading from a file, and <samp><span class="command">gzip</span></samp> compression when reading from a connection. <p>R has used the same serialization format since R 1.4.0 in December 2001. Earlier formats are still supported via <code>load</code> and <code>save</code> but such formats are not described here. The current serialization format is called ‘version 2’, and has been expanded in back-compatible ways since its inception, for example to support additional <code>SEXPTYPE</code>s. <p><code>save</code> works by writing a single-line header (typically <code>RDX2\n</code> for a binary save: the only other current value is <code>RDA2\n</code> for <code>save(files=TRUE)</code>), then creating a tagged pairlist of the objects to be saved and serializing that single object. <code>load</code> reads the header line, unserializes a single object (a pairlist or a vector list) and assigns the elements of the object in the specified environment. The header line serves two purposes in R: it identifies the serialization format so <code>load</code> can switch to the appropriate reader code, and the linefeed allows the detection of files which have been subjected to a non-binary transfer which re-mapped line endings. It can also be thought of as a ‘magic number’ in the sense used by the <samp><span class="command">file</span></samp> program (although R save files are not yet by default known to that program). <p>Serialization in R needs to take into account that objects may contain references to environments, which then have enclosing environments and so on. (Environments recognized as package or name space environments are saved by name.) There are ‘reference objects’ which are not duplicated on copy and should remain shared on unserialization. These are weak references, external pointers and environments other than those associated with packages, namespaces and the global environment. These are handled via a hash table, and references after the first are written out as a reference marker indexed by the table entry. <p>Version-2 serialization first writes a header indicating the format (normally ‘<samp><span class="samp">X\n</span></samp>’ for an XDR format binary save, but ‘<samp><span class="samp">A\n</span></samp>’, ASCII, and ‘<samp><span class="samp">B\n</span></samp>’, native word-order binary, can also occur) and then three integers giving the version of the format and two R versions (packed by the <code>R_Version</code> macro from <samp><span class="file">Rversion.h</span></samp>). (Unserialization interprets the two versions as the version of R which wrote the file followed by the minimal version of R needed to read the format.) Serialization then writes out the object recursively using function <code>WriteItem</code> in file <samp><span class="file">src/main/serialize.c</span></samp>. <p>Some objects are written as if they were <code>SEXPTYPE</code>s: such pseudo-<code>SEXPTYPE</code>s cover <code>R_NilValue</code>, <code>R_EmptyEnv</code>, <code>R_BaseEnv</code>, <code>R_GlobalEnv</code>, <code>R_UnboundValue</code>, <code>R_MissingArg</code> and <code>R_BaseNamespace</code>. <p>For all <code>SEXPTYPE</code>s except <code>NILSXP</code>, <code>SYMSXP</code> and <code>ENVSXP</code> serialization starts with an integer with the <code>SEXPTYPE</code> in bits 0:7<a rel="footnote" href="#fn-7" name="fnd-7"><sup>7</sup></a> followed by the object bit, two bits indicating if there are any attributes and if there is a tag (for the pairlist types), an unused bit and then the <code>gp</code> field<a rel="footnote" href="#fn-8" name="fnd-8"><sup>8</sup></a> in bits 12:27. Pairlist-like objects write their attributes (if any), tag (if any), CAR and then CDR (using tail recursion): other objects write their attributes after themselves. Atomic vector objects write their length followed by the data: generic vector-list objects write their length followed by a call to <code>WriteItem</code> for each element. The code for <code>CHARSXP</code>s special-cases <code>NA_STRING</code> and writes it as length <code>-1</code> with no data. Lengths no more than <code>2^31 - 1</code> are written in that way and larger lengths (which only occur on 64-bit systems) as <code>-1</code> followed by the upper and lower 32-bits as integers (regarded as unsigned). <p>Environments are treated in several ways: as we have seen, some are written as specific pseudo-<code>SEXPTYPE</code>s. Package and namespace environments are written with pseudo-<code>SEXPTYPE</code>s followed by the name. ‘Normal’ environments are written out as <code>ENVSXP</code>s with an integer indicating if the environment is locked followed by the enclosure, frame, ‘tag’ (the hash table) and attributes. <p>In the ‘XDR’ format integers and doubles are written in bigendian order: however the format is not fully XDR (as defined in RFC 1832) as byte quantities (such as the contents of <code>CHARSXP</code> and <code>RAWSXP</code> types) are written as-is and not padded to a multiple of four bytes. <p>The ‘ASCII’ format writes 7-bit characters. Integers are formatted with <code>%d</code> (except that <code>NA_integer_</code> is written as <code>NA</code>), doubles formatted with <code>%.16g</code> (plus <code>NA</code>, <code>Inf</code> and <code>-Inf</code>) and bytes with <code>%02x</code>. Strings are written using standard escapes (e.g. <code>\t</code> and <code>\013</code>) for non-printing and non-<acronym>ASCII</acronym> bytes. <div class="node"> <a name="Encodings-for-CHARSXPs"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#The-CHARSXP-cache">The CHARSXP cache</a>, Previous: <a rel="previous" accesskey="p" href="#Serialization-Formats">Serialization Formats</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.9 Encodings for CHARSXPs</h3> <p>Character data in R are stored in the sexptype <code>CHARSXP</code>. <p>There is support for encodings other than that of the current locale, in particular UTF-8 and the multi-byte encodings used on Windows for CJK languages. A limited means to indicate the encoding of a <code>CHARSXP</code> is <em>via</em> two of the ‘general purpose’ bits which are used to declare the encoding to be either Latin-1 or UTF-8. (Note that it is possible for a character vector to contain elements in different encodings.) Both printing and plotting notice the declaration and convert the string to the current locale (possibly using <code><xx></code> to display in hexadecimal bytes that are not valid in the current locale). Many (but not all) of the character manipulation functions will either preserve the declaration or re-encode the character string. <p>Strings that refer to the OS such as file names need to be passed through a wide-character interface on some OSes (e.g. Windows). <p>When are character strings declared to be of known encoding? One way is to do so directly via <code>Encoding</code>. The parser declares the encoding if this is known, either via the <code>encoding</code> argument to <code>parse</code> or from the locale within which parsing is being done at the R command line. (Other ways are recorded on the help page for <code>Encoding</code>.) <p>It is not necessary to declare the encoding of <acronym>ASCII</acronym> strings as they will work in any locale. <acronym>ASCII</acronym> strings should never have a marked encoding, as any encoding will be ignored when entering such strings into the <code>CHARSXP</code> cache. <p>The rationale behind considering only UTF-8 and Latin-1 was that most systems are capable of producing UTF-8 strings and this is the nearest we have to a universal format. For those that do not (for example those lacking a powerful enough <code>iconv</code>), it is likely that they work in Latin-1, the old R assumption. The the parser can return a UTF-8-encoded string if it encounters a ‘<samp><span class="samp">\uxxx</span></samp>’ escape for a Unicode point that cannot be represented in the current charset. (This needs MBCS support, and was only enabled<a rel="footnote" href="#fn-9" name="fnd-9"><sup>9</sup></a> on Windows.) This is enabled for all platforms, and a ‘<samp><span class="samp">\uxxx</span></samp>’ or ‘<samp><span class="samp">\Uxxxxxxxx</span></samp>’ escape ensures that the parsed string will be marked as UTF-8. <p>Most of the character manipulation functions now preserve UTF-8 encodings: there are some notes as to which at the top of file <samp><span class="file">src/main/character.c</span></samp> and in file <samp><span class="file">src/library/base/man/Encoding.Rd</span></samp>. <p>Graphics devices are offered the possibility of handing UTF-8-encoded strings without re-encoding to the native character set, by setting <code>hasTextUTF8</code> to be ‘<samp><span class="samp">TRUE</span></samp>’ and supplying functions <code>textUTF8</code> and <code>strWidthUTF8</code> that expect UTF-8-encoded inputs. Normally the symbol font is encoded in Adobe Symbol encoding, but that can be re-encoded to UTF-8 by setting <code>wantSymbolUTF8</code> to ‘<samp><span class="samp">TRUE</span></samp>’. The Windows' port of cairographics has a rather peculiar assumption: it wants the symbol font to be encoded in UTF-8 as if it were encoded in Latin-1 rather than Adobe Symbol: this is selected by <code>wantSymbolUTF8 = NA_LOGICAL</code>. <p>Windows has no UTF-8 locales, but rather expects to work with UCS-2<a rel="footnote" href="#fn-10" name="fnd-10"><sup>10</sup></a> strings. R (being written in standard C) would not work internally with UCS-2 without extensive changes. The <samp><span class="file">Rgui</span></samp> console<a rel="footnote" href="#fn-11" name="fnd-11"><sup>11</sup></a> uses UCS-2 internally, but communicates with the R engine in the native encoding. To allow UTF-8 strings to be printed in UTF-8 in <samp><span class="file">Rgui.exe</span></samp>, an escape convention is used (see header file <samp><span class="file">rgui_UTF8.h</span></samp>) which is used by <code>cat</code>, <code>print</code> and autoprinting. <p>‘Unicode’ (UCS-2LE) files are common in the Windows world, and <code>readLines</code> and <code>scan</code> will read them into UTF-8 strings on Windows if the encoding is declared explicitly on an unopened connection passed to those functions. <div class="node"> <a name="The-CHARSXP-cache"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Warnings-and-errors">Warnings and errors</a>, Previous: <a rel="previous" accesskey="p" href="#Encodings-for-CHARSXPs">Encodings for CHARSXPs</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.10 The CHARSXP cache</h3> <p><a name="index-mkChar-74"></a>There is a global cache for <code>CHARSXP</code>s created by <code>mkChar</code> — the cache ensures that most <code>CHARSXP</code>s with the same contents share storage (‘contents’ including any declared encoding). Not all <code>CHARSXP</code>s are part of the cache – notably ‘<samp><span class="samp">NA_STRING</span></samp>’ is not. <code>CHARSXP</code>s reloaded from the <code>save</code> formats of R prior to 0.99.0 are not cached (since the code used is frozen and very few examples still exist). <p><a name="index-mkCharLenCE-75"></a>The cache records the encoding of the string as well as the bytes: all requests to create a <code>CHARSXP</code> should be <em>via</em> a call to <code>mkCharLenCE</code>. Any encoding given in <code>mkCharLenCE</code> call will be ignored if the string's bytes are all <acronym>ASCII</acronym> characters. <div class="node"> <a name="Warnings-and-errors"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#S4-objects">S4 objects</a>, Previous: <a rel="previous" accesskey="p" href="#The-CHARSXP-cache">The CHARSXP cache</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.11 Warnings and errors</h3> <p><a name="index-warning-76"></a><a name="index-warningcall-77"></a><a name="index-error-78"></a><a name="index-errorcall-79"></a> Each of <code>warning</code> and <code>stop</code> have two C-level equivalents, <code>warning</code>, <code>warningcall</code>, <code>error</code> and <code>errorcall</code>. The relationship between the pairs is similar: <code>warning</code> tries to fathom out a suitable call, and then calls <code>warningcall</code> with that call as the first argument if it succeeds, and with <code>call = R_NilValue</code> it is does not. When <code>warningcall</code> is called, it includes the deparsed call in its printout unless <code>call = R_NilValue</code>. <p><code>warning</code> and <code>error</code> look at the context stack. If the topmost context is not of type <code>CTXT_BUILTIN</code>, it is used to provide the call, otherwise the next context provides the call. This means that when these functions are called from a primitive or <code>.Internal</code>, the imputed call will not be to primitive/<code>.Internal</code> but to the function calling the primitive/<code>.Internal</code> . This is exactly what one wants for a <code>.Internal</code>, as this will give the call to the closure wrapper. (Further, for a <code>.Internal</code>, the call is the argument to <code>.Internal</code>, and so may not correspond to any R function.) However, it is unlikely to be what is needed for a primitive. <p>The upshot is that that <code>warningcall</code> and <code>errorcall</code> should normally be used for code called from a primitive, and <code>warning</code> and <code>error</code> should be used for code called from a <code>.Internal</code> (and necessarily from <code>.Call</code>, <code>.C</code> and so on, where the call is not passed down). However, there are two complications. One is that code might be called from either a primitive or a <code>.Internal</code>, in which case probably <code>warningcall</code> is more appropriate. The other involves replacement functions, where the call was once of the form <pre class="example"> > length(x) <- y ~ x Error in "length<-"(`*tmp*`, value = y ~ x) : invalid value </pre> <p class="noindent">which is unpalatable to the end user. For replacement functions there will be a suitable context at the top of the stack, so <code>warning</code> should be used. (The results for <code>.Internal</code> replacement functions such as <code>substr<-</code> are not ideal.) <div class="node"> <a name="S4-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Memory-allocators">Memory allocators</a>, Previous: <a rel="previous" accesskey="p" href="#Warnings-and-errors">Warnings and errors</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.12 S4 objects</h3> <p>[This section is currently a preliminary draft and should not be taken as definitive. The description assumes that <samp><span class="env">R_NO_METHODS_TABLES</span></samp> has not been set.] <ul class="menu"> <li><a accesskey="1" href="#Representation-of-S4-objects">Representation of S4 objects</a> <li><a accesskey="2" href="#S4-classes">S4 classes</a> <li><a accesskey="3" href="#S4-methods">S4 methods</a> <li><a accesskey="4" href="#Mechanics-of-S4-dispatch">Mechanics of S4 dispatch</a> </ul> <div class="node"> <a name="Representation-of-S4-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#S4-classes">S4 classes</a>, Previous: <a rel="previous" accesskey="p" href="#S4-objects">S4 objects</a>, Up: <a rel="up" accesskey="u" href="#S4-objects">S4 objects</a> </div> <h4 class="subsection">1.12.1 Representation of S4 objects</h4> <p>S4 objects can be of any <code>SEXPTYPE</code>. They are either an object of a simple type (such as an atomic vector or function) with S4 class information or of type <code>S4SXP</code>. In all cases, the ‘S4 bit’ (bit 4 of the ‘general purpose’ field) is set, and can be tested by the macro/function <code>IS_S4_OBJECT</code>. <p>S4 objects are created via <code>new()</code><a rel="footnote" href="#fn-12" name="fnd-12"><sup>12</sup></a> and thence via the C function <code>R_do_new_object</code>. This duplicates the prototype of the class, adds a class attribute and sets the S4 bit. All S4 class attributes should be character vectors of length one with an attribute giving (as a character string) the name of the package (or <code>.GlobalEnv</code>) containing the class definition. Since S4 objects have a class attribute, the <code>OBJECT</code> bit is set. <p>It is currently unclear what should happen if the class attribute is removed from an S4 object, or if this should be allowed. <div class="node"> <a name="S4-classes"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#S4-methods">S4 methods</a>, Previous: <a rel="previous" accesskey="p" href="#Representation-of-S4-objects">Representation of S4 objects</a>, Up: <a rel="up" accesskey="u" href="#S4-objects">S4 objects</a> </div> <h4 class="subsection">1.12.2 S4 classes</h4> <p>S4 classes are stored as R objects in the environment in which they are created, with names <code>.__C__</code><var>classname</var>: as such they are not listed by default by <code>ls</code>. <p>The objects are S4 objects of class <code>"classRepresentation"</code> which is defined in the <strong>methods</strong> package. <p>Since these are just objects, they are subject to the normal scoping rules and can be imported and exported from namespaces like other objects. The directives <code>importClassesFrom</code> and <code>exportClasses</code> are merely convenient ways to refer to class objects without needing to know their internal ‘metaname’ (although <code>exportClasses</code> does a little sanity checking via <code>isClass</code>). <div class="node"> <a name="S4-methods"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Mechanics-of-S4-dispatch">Mechanics of S4 dispatch</a>, Previous: <a rel="previous" accesskey="p" href="#S4-classes">S4 classes</a>, Up: <a rel="up" accesskey="u" href="#S4-objects">S4 objects</a> </div> <h4 class="subsection">1.12.3 S4 methods</h4> <p>Details of methods are stored in S4 objects of class <code>"MethodsList"</code>. They have a non-syntactic name of the form <code>.__M__</code><var>generic</var><code>:</code><var>package</var> for all methods defined in the current environment for the named generic derived from a specific package (which might be <code>.GlobalEnv</code>). <p>There is also environment <code>.__T__</code><var>generic</var><code>:</code><var>package</var> which has names the signatures of the methods defined, and values the corresponding method functions. This is often referred to as a `methods table'. <p>When a package without a namespace is attached these objects become visible on the search path. <code>library</code> calls <code>methods:::cacheMetaData</code> to update the internal tables. <p>During an R session there is an environment associated with each non-primitive generic containing objects <code>.AllMTable</code>, <code>.Generic</code>, <code>.Methods</code>, <code>.MTable</code>, <code>.SigArgs</code> and <code>.SigLength</code>. <code>.MTable</code> and <code>AllMTable</code> are merged methods tables containing all the methods defined directly and via inheritance respectively. <code>.Methods</code> is a merged methods list. <p>Exporting methods from a namespace is more complicated than exporting a class. Note first that you do not export a method, but rather the directive <code>exportMethods</code> will export all the methods defined in the namespace for a specified generic: the code also adds to the list of generics any that are exported directly. For generics which are listed via <code>exportMethods</code> or exported themselves, the corresponding <code>"MethodsList"</code> and environment are exported and so will appear (as hidden objects) in the package environment. <p>Methods for primitives which are internally S4 generic (see below) are always exported, whether mentioned in the <samp><span class="file">NAMESPACE</span></samp> file or not. <p>Methods can be imported either via the directive <code>importMethodsFrom</code> or via importing a namespace by <code>import</code>. Also, if a generic is imported via <code>importFrom</code>, its methods are also imported. In all cases the generic will be imported if it is in the namespace, so <code>importMethodsFrom</code> is most appropriate for methods defined on generics in other packages. Since methods for a generic could be imported from several different packages, the methods tables are merged. <p>When a package with a namespace is attached <code>methods:::cacheMetaData</code> is called to update the internal tables: only the visible methods will be cached. <div class="node"> <a name="Mechanics-of-S4-dispatch"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#S4-methods">S4 methods</a>, Up: <a rel="up" accesskey="u" href="#S4-objects">S4 objects</a> </div> <h4 class="subsection">1.12.4 Mechanics of S4 dispatch</h4> <p>This subsection does not discuss how S4 methods are chosen: see <a href="http://developer.r-project.org/howMethodsWork.pdf">http://developer.r-project.org/howMethodsWork.pdf</a>. <p>For all but primitive functions, setting a method on an existing function that is not itself S4 generic creates a new object in the current environment which is a call to <code>standardGeneric</code> with the old definition as the default method. Such S4 generics can also be created <em>via</em> a call to <code>setGeneric</code><a rel="footnote" href="#fn-13" name="fnd-13"><sup>13</sup></a> and are standard closures in the R language, with environment the environment within which they are created. With the advent of namespaces this is somewhat problematic: if <code>myfn</code> was previously in a package with a name space there will be two functions called <code>myfn</code> on the search paths, and which will be called depends on which search path is in use. This is starkest for functions in the base namespace, where the original will be found ahead of the newly created function from any other package with a namespace. <p>Primitive functions are treated quite differently, for efficiency reasons: this results in different semantics. <code>setGeneric</code> is disallowed for primitive functions. The <strong>methods</strong> namespace contains a list <code>.BasicFunsList</code> named by primitive functions: the entries are either <code>FALSE</code> or a standard S4 generic showing the effective definition. When <code>setMethod</code> (or <code>setReplaceMethod</code>) is called, it either fails (if the list entry is <code>FALSE</code>) or a method is set on the effective generic given in the list. <p>Actual dispatch of S4 methods for almost all primitives piggy-backs on the S3 dispatch mechanism, so S4 methods can only be dispatched for primitives which are internally S3 generic. When a primitive that is internally S3 generic is called with a first argument which is an S4 object and S4 dispatch is on (that is, the <strong>methods</strong> namespace is loaded), <code>DispatchOrEval</code> calls <code>R_possible_dispatch</code> (defined in file <samp><span class="file">src/main/objects.c</span></samp>). (Members of the S3 group generics, which includes all the generic operators, are treated slightly differently: the first two arguments are checked and <code>DispatchGroup</code> is called.) <code>R_possible_dispatch</code> first checks an internal table to see if any S4 methods are set for that generic (and S4 dispatch is currently enabled for that generic), and if so proceeds to S4 dispatch using methods stored in another internal table. All primitives are in the base namespace, and this mechanism means that S4 methods can be set for (some) primitives and will always be used, in contrast to setting methods on non-primitives. <p>The exception is <code>%*%</code>, which is S4 generic but not S3 generic as its C code contains a direct call to <code>R_possible_dispatch</code>. <p>The primitive <code>as.double</code> is special, as <code>as.numeric</code> and <code>as.real</code> are copies of it. The <strong>methods</strong> package code partly refers to generics by name and partly by function, and maps <code>as.double</code> and <code>as.real</code> to <code>as.numeric</code> (since that is the name used by packages exporting methods for it). <p>Some elements of the language are implemented as primitives, for example <code>}</code>. This includes the subset and subassignment ‘functions’ and they are S4 generic, again piggybacking on S3 dispatch. <p><code>.BasicFunsList</code> is generated when <strong>methods</strong> is installed, by computing all primitives, initially disallowing methods on all and then setting generics for members of <code>.GenericArgsEnv</code>, the S4 group generics and a short exceptions list in file <samp><span class="file">BasicFunsList.R</span></samp>: this currently contains the subsetting and subassignment operators and an override for <code>c</code>. <div class="node"> <a name="Memory-allocators"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Internal-use-of-global-and-base-environments">Internal use of global and base environments</a>, Previous: <a rel="previous" accesskey="p" href="#S4-objects">S4 objects</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.13 Memory allocators</h3> <p>R's memory allocation is almost all done via routines in file <samp><span class="file">src/main/memory.c</span></samp>. It is important to keep track of where memory is allocated, as the Windows port (by default) makes use of a memory allocator that differs from <code>malloc</code> etc as provided by MinGW. Specifically, there are entry points <code>Rm_malloc</code>, <code>Rm_free</code>, <code>Rm_calloc</code> and <code>Rm_free</code> provided by file <samp><span class="file">src/gnuwin32/malloc.c</span></samp>. This was done for two reasons. The primary motivation was performance: the allocator provided by MSVCRT <em>via</em> MinGW was far too slow at handling the many small allocations that the allocation system for <code>SEXPREC</code>s uses. As a side benefit, we can set a limit on the amount of allocated memory: this is useful as whereas Windows does provide virtual memory it is relatively far slower than many other R platforms and so limiting R's use of swapping is highly advantageous. The high-performance allocator is only called from <samp><span class="file">src/main/memory.c</span></samp>, <samp><span class="file">src/main/regex.c</span></samp>, <samp><span class="file">src/extra/pcre</span></samp> and <samp><span class="file">src/extra/xdr</span></samp>: note that this means that it is not used in packages. <p>The rest of R should where possible make use of the allocators made available by file <samp><span class="file">src/main/memory.c</span></samp>, which are also the methods recommended in <a href="R-exts.html#Memory-allocation">Memory allocation</a> <a name="index-R_005falloc-80"></a><a name="index-Calloc-81"></a><a name="index-Realloc-82"></a><a name="index-Free-83"></a>for use in R packages, namely the use of <code>R_alloc</code>, <code>Calloc</code>, <code>Realloc</code> and <code>Free</code>. Memory allocated by <code>R_alloc</code> is freed by the garbage collector once the ‘watermark’ has been reset by calling <a name="index-vmaxset-84"></a><code>vmaxset</code>. This is done automatically by the wrapper code calling primitives and <code>.Internal</code> functions (and also by the wrapper code to <code>.Call</code> and <code>.External</code>), but <a name="index-vmaxget-85"></a><code>vmaxget</code> and <code>vmaxset</code> can be used to reset the watermark from within internal code if the memory is only required for a short time. <p><a name="index-alloca-86"></a>All of the methods of memory allocation mentioned so far are relatively expensive. All R platforms support <code>alloca</code>, and in almost all cases<a rel="footnote" href="#fn-14" name="fnd-14"><sup>14</sup></a> this is managed by the compiler, allocates memory on the C stack and is very efficient. <p>There are two disadvantages in using <code>alloca</code>. First, it is fragile and care is needed to avoid writing (or even reading) outside the bounds of the allocation block returned. Second, it increases the danger of overflowing the C stack. It is suggested that it is only used for smallish allocations (up to tens of thousands of bytes), and that <p><a name="index-R_005fCheckStack-87"></a> <pre class="example"> R_CheckStack(); </pre> <p class="noindent">is called immediately after the allocation (as R's stack checking mechanism will warn far enough from the stack limit to allow for modest use of alloca). (<code>do_makeunique</code> in file <samp><span class="file">src/main/unique.c</span></samp> provides an example of both points.) <p>There is an alternative check, <a name="index-R_005fCheckStack2-88"></a> <pre class="example"> R_CheckStack2(size_t extra); </pre> <p class="noindent">to be called immediately <em>before</em> trying an allocation of <code>extra</code> bytes. <p>An alternative strategy has been used for various functions which require intermediate blocks of storage of varying but usually small size, and this has been consolidated into the routines in the header file <samp><span class="file">src/main/RBufferUtils.h</span></samp>. This uses a structure which contains a buffer, the current size and the default size. A call to <a name="index-R_005fAllocStringBuffer-89"></a> <pre class="example"> R_AllocStringBuffer(size_t blen, R_StringBuffer *buf); </pre> <p class="noindent">sets <code>buf->data</code> to a memory area of at least <code>blen+1</code> bytes. At least the default size is used, which means that for small allocations the same buffer can be reused. A call to <a name="index-R_005fFreeStringBufferL-90"></a><a name="index-R_005fFreeStringBuffer-91"></a><code>R_FreeStringBufferL</code> releases memory if more than the default has been allocated whereas a call to <code>R_FreeStringBuffer</code> frees any memory allocated. <p>The <code>R_StringBuffer</code> structure needs to be initialized, for example by <pre class="example"> static R_StringBuffer ex_buff = {NULL, 0, MAXELTSIZE}; </pre> <p class="noindent">which uses a default size of <code>MAXELTSIZE = 8192</code> bytes. Most current uses have a static <code>R_StringBuffer</code> structure, which allows the (default-sized) buffer to be shared between calls to e.g. <code>grep</code> and even between functions: this will need to be changed if R ever allows concurrent evaluation threads. So the idiom is <pre class="example"> static R_StringBuffer ex_buff = {NULL, 0, MAXELTSIZE}; ... char *buf; for(i = 0; i < n; i++) { compute len buf = R_AllocStringBuffer(len, &ex_buff); use buf } /* free allocation if larger than the default, but leave default allocated for future use */ R_FreeStringBufferL(&ex_buff); </pre> <ul class="menu"> <li><a accesskey="1" href="#Internals-of-R_005falloc">Internals of R_alloc</a> </ul> <div class="node"> <a name="Internals-of-R_alloc"></a> <a name="Internals-of-R_005falloc"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Memory-allocators">Memory allocators</a>, Up: <a rel="up" accesskey="u" href="#Memory-allocators">Memory allocators</a> </div> <h4 class="subsection">1.13.1 Internals of R_alloc</h4> <p>The memory used by <code>R_alloc</code> is allocated as R vectors, of type <code>RAWSXP</code>. Thus the allocation is in units of 8 bytes, and is rounded up. A request for zero bytes currently returns <code>NULL</code> (but this should not be relied on). For historical reasons, in all other cases 1 byte is added before rounding up so the allocation is always 1–8 bytes more than was asked for: again this should not be relied on. <p>The vectors allocated are protected via the setting of <code>R_VStack</code>, as the garbage collector marks everything that can be reached from that location. When a vector is <code>R_alloc</code>ated, its <code>ATTRIB</code> pointer is set to the current <code>R_VStack</code>, and <code>R_VStack</code> is set to the latest allocation. Thus <code>R_VStack</code> is a single-linked chain of the vectors currently allocated via <code>R_alloc</code>. Function <code>vmaxset</code> resets the location <code>R_VStack</code>, and should be to a value that has previously be obtained <em>via</em> <code>vmaxget</code>: allocations after the value was obtained will no longer be protected and hence available for garbage collection. <div class="node"> <a name="Internal-use-of-global-and-base-environments"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Modules">Modules</a>, Previous: <a rel="previous" accesskey="p" href="#Memory-allocators">Memory allocators</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.14 Internal use of global and base environments</h3> <p>This section notes known use by the system of these environments: the intention is to minimize or eliminate such uses. <ul class="menu"> <li><a accesskey="1" href="#Base-environment">Base environment</a> <li><a accesskey="2" href="#Global-environment">Global environment</a> </ul> <div class="node"> <a name="Base-environment"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Global-environment">Global environment</a>, Previous: <a rel="previous" accesskey="p" href="#Internal-use-of-global-and-base-environments">Internal use of global and base environments</a>, Up: <a rel="up" accesskey="u" href="#Internal-use-of-global-and-base-environments">Internal use of global and base environments</a> </div> <h4 class="subsection">1.14.1 Base environment</h4> <p><a name="index-base-environment-92"></a><a name="index-environment_002c-base-93"></a><a name="index-g_t_002eDevice-94"></a><a name="index-g_t_002eDevices-95"></a>The graphics devices system maintains two variables <code>.Device</code> and <code>.Devices</code> in the base environment: both are always set. The variable <code>.Devices</code> gives a list of character vectors of the names of open devices, and <code>.Device</code> is the element corresponding to the currently active device. The null device will always be open. <p><a name="index-g_t_002eOptions-96"></a>There appears to be a variable <code>.Options</code>, a pairlist giving the current options settings. But in fact this is just a symbol with a value assigned, and so shows up as a base variable. <p><a name="index-g_t_002eLast_002evalue-97"></a>Similarly, the evaluator creates a symbol <code>.Last.value</code> which appears as a variable in the base environment. <p><a name="index-g_t_002eTraceback-98"></a><a name="index-last_002ewarning-99"></a>Errors can give rise to objects <code>.Traceback</code> and <code>last.warning</code> in the base environment. <div class="node"> <a name="Global-environment"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Base-environment">Base environment</a>, Up: <a rel="up" accesskey="u" href="#Internal-use-of-global-and-base-environments">Internal use of global and base environments</a> </div> <h4 class="subsection">1.14.2 Global environment</h4> <p><a name="index-global-environment-100"></a><a name="index-environment_002c-global-101"></a><a name="index-g_t_002eRandom_002eseed-102"></a>The seed for the random number generator is stored in object <code>.Random.seed</code> in the global environment. <p><a name="index-dump_002eframes-103"></a>Some error handlers may give rise to objects in the global environment: for example <code>dump.frames</code> by default produces <code>last.dump</code>. <p><a name="index-g_t_002eSavedPlots-104"></a>The <code>windows()</code> device makes use of a variable <code>.SavedPlots</code> to store display lists of saved plots for later display. This is regarded as a variable created by the user. <div class="node"> <a name="Modules"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Visibility">Visibility</a>, Previous: <a rel="previous" accesskey="p" href="#Internal-use-of-global-and-base-environments">Internal use of global and base environments</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.15 Modules</h3> <p><a name="index-modules-105"></a>R makes use of a number of shared objects/DLLs stored in the <samp><span class="file">modules</span></samp> directory. These are parts of the code which have been chosen to be loaded ‘on demand’ rather than linked as dynamic libraries or incorporated into the main executable/dynamic library. <p>For a few of these (e.g. <code>vfonts</code>) the issue is size: the database for the Hershey fonts is included in the C code of the module and was at one time an appreciable part of the codebase for a rarely used feature. However, for most of the modules the motivation has been the amount of (often optional) code they will bring in via libraries to which they are linked. <dl> <dt><code>internet</code><dd>The internal HTTP and FTP clients and socket support, which link to system-specific support libraries. <br><dt><code>lapack</code><dd>The code which makes use of the LAPACK library, and is linked to <samp><span class="file">libRlapack</span></samp> or an external LAPACK library. <br><dt><code>vfonts</code><dd>The Hershey font databases and the code to draw with them. <br><dt><code>X11</code><dd>(Unix-alikes only.) The <code>X11()</code>, <code>jpeg()</code>, <code>png()</code> and <code>tiff()</code> devices. These are optional, and links to some or all of the <code>X11</code>, <code>pango</code>, <code>cairo</code>, <code>jpeg</code>, <code>libpng</code> and <code>libtiff</code> libraries. <br><dt><samp><span class="file">internet2.dll</span></samp><dd>(Windows only.) An alternative version of the internet access routines, compiled against Internet Explorer internals (and so loads <samp><span class="file">wininet.dll</span></samp> and <samp><span class="file">wsock32.dll</span></samp>). </dl> <div class="node"> <a name="Visibility"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Lazy-loading">Lazy loading</a>, Previous: <a rel="previous" accesskey="p" href="#Modules">Modules</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.16 Visibility</h3> <p><a name="index-visibility-106"></a> <ul class="menu"> <li><a accesskey="1" href="#Hiding-C-entry-points">Hiding C entry points</a> <li><a accesskey="2" href="#Variables-in-Windows-DLLs">Variables in Windows DLLs</a> </ul> <div class="node"> <a name="Hiding-C-entry-points"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Variables-in-Windows-DLLs">Variables in Windows DLLs</a>, Previous: <a rel="previous" accesskey="p" href="#Visibility">Visibility</a>, Up: <a rel="up" accesskey="u" href="#Visibility">Visibility</a> </div> <h4 class="subsection">1.16.1 Hiding C entry points</h4> <p>We make use of the visibility mechanisms discussed in <a href="R-exts.html#Controlling-visibility">Controlling visibility</a>, C entry points not needed outside the main R executable/dynamic library (and in particular in no package nor module) should be prefixed by <code>attribute_hidden</code>. <a name="index-attribute_005fhidden-107"></a>Minimizing the visibility of symbols in the R dynamic library will speed up linking to it (which packages will do) and reduce the possibility of linking to the wrong entry points of the same name. In addition, on some platforms reducing the number of entry points allows more efficient versions of PIC to be used: somewhat over half the entry points are hidden. A convenient way to hide variables (as distinct from functions) is to declare them <code>extern0</code> in header file <samp><span class="file">Defn.h</span></samp>. <p>The visibility mechanism used is only available with some compilers and platforms, and in particular not on Windows, where an alternative mechanism is used. Entry points will not be made available in <samp><span class="file">R.dll</span></samp> if they are listed in the file <samp><span class="file">src/gnuwin32/Rdll.hide</span></samp>. <a name="index-Rdll_002ehide-108"></a>Entries in that file start with a space and must be strictly in alphabetic order in the C locale (use <samp><span class="command">sort</span></samp> on the file to ensure this if you change it). It is possible to hide Fortran as well as C entry points via this file: the former are lower-cased and have an underline as suffix, and the suffixed name should be included in the file. Some entry points exist only on Windows or need to be visible only on Windows, and some notes on these are provided in file <samp><span class="file">src/gnuwin32/Maintainters.notes</span></samp>. <p>Because of the advantages of reducing the number of visible entry points, they should be declared <code>attribute_hidden</code> where possible. Note that this only has an effect on a shared-R-library build, and so care is needed not to hide entry points that are legitimately used by packages. So it is best if the decision on visibility is made when a new entry point is created, including the decision if it should be included in header file <samp><span class="file">Rinternals.h</span></samp>. A list of the visible entry points on shared-R-library build on a reasonably standard Unix-alike can be made by something like <pre class="example"> nm -g libR.so | grep ‘ [BCDT] ’ | cut -b20- </pre> <div class="node"> <a name="Variables-in-Windows-DLLs"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Hiding-C-entry-points">Hiding C entry points</a>, Up: <a rel="up" accesskey="u" href="#Visibility">Visibility</a> </div> <h4 class="subsection">1.16.2 Variables in Windows DLLs</h4> <p>Windows is unique in that it conventionally treats importing variables differently from functions: variables that are imported from a DLL need to be specified by a prefix (often ‘<samp><span class="samp">_imp_</span></samp>’) when being linked to (‘imported’) but not when being linked from (‘exported’). The details depend on the compiler system, and have changed for MinGW during the lifetime of that port. They are in the main hidden behind some macros defined in header file <samp><span class="file">R_ext/libextern.h</span></samp>. <p>A (non-function) variable in the main R sources that needs to be referred to outside <samp><span class="file">R.dll</span></samp> (in a package, module or another DLL such as <samp><span class="file">Rgraphapp.dll</span></samp>) should be declared with prefix <code>LibExtern</code>. The main use is in <samp><span class="file">Rinternals.h</span></samp>, but it needs to be considered for any public header and also <samp><span class="file">Defn.h</span></samp>. <p>It would nowadays be possible to make use of the ‘auto-import’ feature of the MinGW port of <samp><span class="command">ld</span></samp> to fix up imports from DLLs (and if R is built for the Cygwin platform this is what happens). However, this was not possible when the MinGW build of R was first constructed in ca 1998, allows less control of visibility and would not work for other Windows compiler suites. <p>It is only possible to check if this has been handled correctly by compiling the R sources on Windows. <div class="node"> <a name="Lazy-loading"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Visibility">Visibility</a>, Up: <a rel="up" accesskey="u" href="#R-Internal-Structures">R Internal Structures</a> </div> <h3 class="section">1.17 Lazy loading</h3> <p>Lazy loading is always used for code in packages but is optional (selected by the package maintainer) for datasets in packages. When a package/namespace which uses it is loaded, the package/namespace environment is populated with promises for all the named objects: when these promises are evaluated they load the actual code from a database. <p>There are separate databases for code and data, stored in the <samp><span class="file">R</span></samp> and <samp><span class="file">data</span></samp> subdirectories. The database consists of two files, <samp><var>name</var><span class="file">.rdb</span></samp> and <samp><var>name</var><span class="file">.rdx</span></samp>. The <samp><span class="file">.rdb</span></samp> file is a concatenation of serialized objects, and the <samp><span class="file">.rdx</span></samp> file contains an index. The objects are stored in (usually) a <samp><span class="command">gzip</span></samp>-compressed format with a 4-byte header giving the uncompressed serialized length (in XDR, that is big-endian, byte order) and read by a call to the primitive <code>lazyLoadDBfetch</code>. (Note that this makes lazy-loading unsuitable for really large objects: the unserialized length of an R object can exceed 4GB.) <p>The index or ‘map’ file <samp><var>name</var><span class="file">.rdx</span></samp> is a compressed serialized R object to be read by <code>readRDS</code>. It is a list with three elements <code>variables</code>, <code>references</code> and <code>compressed</code>. The first two are named lists of integer vectors of length 2 giving the offset and length of the serialized object in the <samp><var>name</var><span class="file">.rdb</span></samp> file. Element <code>variables</code> has an entry for each named object: <code>references</code> serializes a temporary environment used when named environments are added to the database. <code>compressed</code> is a logical indicating if the serialized objects were compressed: compression is always used nowadays. We later added the values <code>compressed = 2</code> and <code>3</code> for <samp><span class="command">bzip2</span></samp> and <samp><span class="command">xz</span></samp> compression (with the possibility of future expansion to other methods): these formats add a fifth byte to the header for the type of compression, and stores serialized objects uncompressed if compression expands them. <p>The loader for a lazy-load database of code or data is function <code>lazyLoad</code> in the <strong>base</strong> package, but note that there is a separate copy to load <strong>base</strong> itself in file <samp><span class="file">R_HOME/base/R/base</span></samp>. <p>Lazy-load databases are created by the code in <samp><span class="file">src/library/tools/R/makeLazyLoad.R</span></samp>: the main tool is the unexported function <code>makeLazyLoadDB</code> and the insertion of database entries is done by calls to <code>.Call("R_lazyLoadDBinsertValue", ...)</code>. <p>Lazy-load databases of less than 10MB are cached in memory at first use: this was found necessary when using file systems with high latency (removable devices and network-mounted file systems on Windows). <p>The same database mechanism is used to store parsed <samp><span class="file">Rd</span></samp> files. One or all of the parsed objects is fetched by a call to <code>tools:::fetchRdDB</code>. <div class="node"> <a name=".Internal-vs-.Primitive"></a> <a name="g_t_002eInternal-vs-_002ePrimitive"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a>, Previous: <a rel="previous" accesskey="p" href="#R-Internal-Structures">R Internal Structures</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">2 <code>.Internal</code> vs <code>.Primitive</code></h2> <p><a name="index-g_t_002eInternal-109"></a><a name="index-g_t_002ePrimitive-110"></a>C code compiled into R at build time can be called directly in what are termed <em>primitives</em> or via the <code>.Internal</code> interface, which is very similar to the <code>.External</code> interface except in syntax. More precisely, R maintains a table of R function names and corresponding C functions to call, which by convention all start with ‘<samp><span class="samp">do_</span></samp>’ and return a <code>SEXP</code>. This table (<code>R_FunTab</code> in file <samp><span class="file">src/main/names.c</span></samp>) also specifies how many arguments to a function are required or allowed, whether or not the arguments are to be evaluated before calling, and whether the function is ‘internal’ in the sense that it must be accessed via the <code>.Internal</code> interface, or directly accessible in which case it is printed in R as <code>.Primitive</code>. <p>Functions using <code>.Internal()</code> wrapped in a closure are in general preferred as this ensures standard handling of named and default arguments. For example, <code>grep</code> is defined as <pre class="example"> grep <- function (pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE) { if (!is.character(x)) x <- structure(as.character(x), names = names(x)) .Internal(grep(as.character(pattern), x, ignore.case, value, perl, fixed, useBytes, invert)) } </pre> <p>and the use of <code>as.character</code> allows methods to be dispatched (for example, for factors). <p>However, for reasons of convenience and also efficiency (as there is some overhead in using the <code>.Internal</code> interface wrapped in a function closure), the primitive functions are exceptions that can be accessed directly. And of course, primitive functions are needed for basic operations—for example <code>.Internal</code> is itself a primitive. Note that primitive functions make no use of R code, and hence are very different from the usual interpreted functions. In particular, <code>formals</code> and <code>body</code> return <code>NULL</code> for such objects, and argument matching can be handled differently. For some primitives (including <code>call</code>, <code>switch</code>, <code>.C</code> and <code>.subset</code>) positional matching is important to avoid partial matching of the first argument. <p>The list of primitive functions is subject to change; currently, it includes the following. <ol type=1 start=1> <li>“Special functions” which really are <em>language</em> elements, but implemented as primitive functions: <pre class="example"> { ( if for while repeat break next return function quote switch </pre> <li>Language elements and basic <em>operator</em>s (i.e., functions usually <em>not</em> called as <code>foo(a, b, ...)</code>) for subsetting, assignment, arithmetic and logic: <pre class="example"> [ [[ $ @ <- <<- = [<- [[<- $<- @<- + - * / ^ %% %*% %/% < <= == != >= > | || & && ! </pre> <li>“Low level” 0– and 1–argument functions which belong to one of the following groups of functions: <ol type=a start=1> <li>Basic mathematical functions with a single argument, i.e., <pre class="example"> abs sign sqrt floor ceiling exp expm1 log2 log10 log1p cos sin tan acos asin atan cosh sinh tanh acosh asinh atanh gamma lgamma digamma trigamma cumsum cumprod cummax cummin Im Re Arg Conj Mod </pre> <p><code>log</code> is a primitive function of one or two arguments with named argument matching. <p><code>trunc</code> is a difficult case: it is a primitive that can have one or more arguments: the default method handled in the primitive has only one. <li>Functions rarely used outside of “programming” (i.e., mostly used inside other functions), such as <pre class="example"> nargs missing on.exit interactive as.call as.character as.complex as.double as.environment as.integer as.logical as.raw is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.real is.recursive is.single is.symbol baseenv emptyenv globalenv pos.to.env unclass invisible seq_along seq_len </pre> <li>The programming and session management utilities <pre class="example"> browser proc.time gc.time tracemem retracemem untracemem </pre> </ol> <li>The following basic replacement and extractor functions <pre class="example"> length length<- class class<- oldClass oldCLass<- attr attr<- attributes attributes<- names names<- dim dim<- dimnames dimnames<- environment<- levels<- storage.mode<- </pre> <p><a name="index-NAMED-111"></a>Note that optimizing <code>NAMED = 1</code> is only effective within a primitive (as the closure wrapper of a <code>.Internal</code> will set <code>NAMED = 2</code> when the promise to the argument is evaluated) and hence replacement functions should where possible be primitive to avoid copying (at least in their default methods). <li>The following functions are primitive for efficiency reasons: <pre class="example"> : ~ c list call expression substitute UseMethod standardGeneric .C .Fortran .Call .External round signif rep seq.int </pre> <p class="noindent">as well as the following internal-use-only functions <pre class="example"> .Primitive .Internal .Call.graphics .External.graphics .subset .subset2 .primTrace .primUntrace lazyLoadDBfetch </pre> </ol> <p>The multi-argument primitives <pre class="example"> call switch .C .Fortran .Call .External </pre> <p class="noindent">intentionally use positional matching, and need to do so to avoid partial matching to their first argument. They do check that the first argument is unnamed or for the first two, partially matches the formal argument name. On the other hand, <pre class="example"> attr attr<- browser rememtrace substitute UseMethod log round signif rep seq.int </pre> <p class="noindent">manage their own argument matching and do work in the standard way. <p>All the one-argument primitives check that if they are called with a named argument that this (partially) matches the name given in the documentation: this is also done for replacement functions with one argument plus <code>value</code>. <p>The net effect is that argument matching for primitives intended for end-user use is done in the same way as for interpreted functions except for the six exceptions where positional matching is required. <ul class="menu"> <li><a accesskey="1" href="#Special-primitives">Special primitives</a> <li><a accesskey="2" href="#Special-internals">Special internals</a> <li><a accesskey="3" href="#Prototypes-for-primitives">Prototypes for primitives</a> <li><a accesskey="4" href="#Adding-a-primitive">Adding a primitive</a> </ul> <div class="node"> <a name="Special-primitives"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Special-internals">Special internals</a>, Previous: <a rel="previous" accesskey="p" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a>, Up: <a rel="up" accesskey="u" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a> </div> <h3 class="section">2.1 Special primitives</h3> <p>A small number of primitives are <em>specials</em> rather than <em>builtins</em>, that is they are entered with unevaluated arguments. This is clearly necessary for the language constructs and the assignment operators, as well as for <code>&&</code> and <code>||</code> which conditionally evaluate their second argument, and <code>~</code>, <code>.Internal</code>, <code>call</code>, <code>expression</code>, <code>missing</code>, <code>on.exit</code>, <code>quote</code> and <code>substitute</code> which do not evaluate some of their arguments. <p><code>rep</code> and <code>seq.int</code> are special as they evaluate some of their arguments conditional on which are non-missing. <p><code>log</code>, <code>round</code> and <code>signif</code> are special to allow default values to be given to missing arguments. <p>The subsetting, subassignment and <code>@</code> operators are all special. (For both extraction and replacement forms, <code>$</code> and <code>@</code> take a symbol argument, and <code>[</code> and <code>[[</code> allow missing arguments.) <p><code>UseMethod</code> is special to avoid the additional contexts added to calls to builtins. <div class="node"> <a name="Special-internals"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Prototypes-for-primitives">Prototypes for primitives</a>, Previous: <a rel="previous" accesskey="p" href="#Special-primitives">Special primitives</a>, Up: <a rel="up" accesskey="u" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a> </div> <h3 class="section">2.2 Special internals</h3> <p>There are also special <code>.Internal</code> functions: <code>NextMethod</code>, <code>Recall</code>, <code>withVisible</code>, <code>cbind</code>, <code>rbind</code> (to allow for the <code>deparse.level</code> argument), <code>eapply</code>, <code>lapply</code> and <code>vapply</code>. <div class="node"> <a name="Prototypes-for-primitives"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Adding-a-primitive">Adding a primitive</a>, Previous: <a rel="previous" accesskey="p" href="#Special-internals">Special internals</a>, Up: <a rel="up" accesskey="u" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a> </div> <h3 class="section">2.3 Prototypes for primitives</h3> <p>Prototypes are available for the primitive functions and operators, and these are used for printing, <code>args</code> and package checking (e.g. by <code>tools::checkS3methods</code> and by package <a href="http://CRAN.R-project.org/package=codetools"><strong>codetools</strong></a>). There are two environments in the <strong>base</strong> package (and namespace), ‘<samp><span class="samp">.GenericArgsEnv</span></samp>’ for those primitives which are internal S3 generics, and ‘<samp><span class="samp">.ArgsEnv</span></samp>’ for the rest. Those environments contain closures with the same names as the primitives, formal arguments derived (manually) from the help pages, a body which is a suitable call to <code>UseMethod</code> or <code>NULL</code> and environment the base namespace. <p>The C code for <code>print.default</code> and <code>args</code> uses the closures in these environments in preference to the definitions in base (as primitives). <p>The QC function <code>undoc</code> checks that all the functions prototyped in these environments are currently primitive, and that the primitives not included are better thought of as language elements (at the time of writing <pre class="example"> $ $<- && ( : @ @<- [ [[ [[<- [<- { || ~ <- <<- = break for function if next repeat return while </pre> <p class="noindent">). One could argue about <code>~</code>, but it is known to the parser and has semantics quite unlike a normal function. And <code>:</code> is documented with different argument names in its two meanings.) <p>The QC functions <code>codoc</code> and <code>checkS3methods</code> also make use of these environments (effectively placing them in front of base in the search path), and hence the formals of the functions they contain are checked against the help pages by <code>codoc</code>. However, there are two problems with the generic primitives. The first is that many of the operators are part of the S3 group generic <code>Ops</code> and that defines their arguments to be <code>e1</code> and <code>e2</code>: although it would be very unusual, an operator could be called as e.g. <code>"+"(e1=a, e2=b)</code> and if method dispatch occurred to a closure, there would be an argument name mismatch. So the definitions in environment <code>.GenericArgsEnv</code> have to use argument names <code>e1</code> and <code>e2</code> even though the traditional documentation is in terms of <code>x</code> and <code>y</code>: <code>codoc</code> makes the appropriate adjustment via <code>tools:::.make_S3_primitive_generic_env</code>. The second discrepancy is with the <code>Math</code> group generics, where the group generic is defined with argument list <code>(x, ...)</code>, but most of the members only allow one argument when used as the default method (and <code>round</code> and <code>signif</code> allow two as default methods): again fix-ups are used. <p>Those primitives which are in <code>.GenericArgsEnv</code> are checked (via <samp><span class="file">tests/primitives.R</span></samp>) to be generic <em>via</em> defining methods for them, and a check is made that the remaining primitives are probably not generic, by setting a method and checking it is not dispatched to (but this can fail for other reasons). However, there is no certain way to know that if other <code>.Internal</code> or primitive functions are not internally generic except by reading the source code. <div class="node"> <a name="Adding-a-primitive"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Prototypes-for-primitives">Prototypes for primitives</a>, Up: <a rel="up" accesskey="u" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a> </div> <h3 class="section">2.4 Adding a primitive</h3> <p>[For R-core use: reverse this procedure to remove a primitive. Most commonly this is done by changing a <code>.Internal</code> to a primitive or <em>vice versa</em>.] <p>Primitives are listed in the table <code>R_FunTab</code> in <samp><span class="file">src/main/names.c</span></samp>: primitives have ‘<samp><span class="samp">Y = 0</span></samp>’ in the ‘<samp><span class="samp">eval</span></samp>’ field. <p>There needs to an a ‘<samp><span class="samp">\alias</span></samp>’ entry in a help file in the <strong>base</strong> package, and the primitive needs to be added to one of the lists at the start of this section. <p>Some primitives are regarded as language elements (the current ones are listed above). These need to be in added to two lists of exceptions, <code>langElts</code> in <code>undoc()</code> (in file <samp><span class="file">src/library/tools/R/QC.R</span></samp>) and <code>lang_elements</code> in <samp><span class="file">tests/primitives.R</span></samp>. <p>All other primitives are regarded as functions and should be listed in one of the environments defined in <samp><span class="file">src/library/base/R/zzz.R</span></samp>, either <code>.ArgsEnv</code> or <code>.GenericArgsEnv</code>: internal generics also need to be listed in the character vector <code>.S3PrimitiveGenerics</code>. Note too the discussion about argument matching above: if you add a primitive function with more than one argument by converting a <code>.Internal</code> you need to add argument matching to the C code, and for those with a single argument, add argument-name checking. <p>Do ensure that <samp><span class="command">make check-devel</span></samp> has been run: that tests most of these requirements. <div class="node"> <a name="Internationalization-in-the-R-sources"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Package-Structure">Package Structure</a>, Previous: <a rel="previous" accesskey="p" href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">3 Internationalization in the R sources</h2> <p>The process of marking messages (errors, warnings etc) for translation in an R package is described in <a href="R-exts.html#Internationalization">Internationalization</a>, and the standard packages included with R have (with an exception in <strong>grDevices</strong> for the menus of the <code>windows()</code> device) been internationalized in the same way as other packages. <ul class="menu"> <li><a accesskey="1" href="#R-code">R code</a> <li><a accesskey="2" href="#Main-C-code">Main C code</a> <li><a accesskey="3" href="#Windows_002dGUI_002dspecific-code">Windows-GUI-specific code</a> <li><a accesskey="4" href="#OS-X-GUI">OS X GUI</a> <li><a accesskey="5" href="#Updating">Updating</a> </ul> <div class="node"> <a name="R-code"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Main-C-code">Main C code</a>, Previous: <a rel="previous" accesskey="p" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a>, Up: <a rel="up" accesskey="u" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a> </div> <h3 class="section">3.1 R code</h3> <p>Internationalization for R code is done in exactly the same way as for extension packages. As all standard packages which have R code also have a namespace, it is never necessary to specify <code>domain</code>, but for efficiency calls to <code>message</code>, <code>warning</code> and <code>stop</code> should include <code>domain = NA</code> when the message is constructed <em>via</em> <code>gettextf</code>, <code>gettext</code> or <code>ngettext</code>. <p>For each package, the extracted messages and translation sources are stored under package directory <samp><span class="file">po</span></samp> in the source package, and compiled translations under <samp><span class="file">inst/po</span></samp> for installation to package directory <samp><span class="file">po</span></samp> in the installed package. This also applies to C code in packages. <div class="node"> <a name="Main-C-code"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Windows_002dGUI_002dspecific-code">Windows-GUI-specific code</a>, Previous: <a rel="previous" accesskey="p" href="#R-code">R code</a>, Up: <a rel="up" accesskey="u" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a> </div> <h3 class="section">3.2 Main C code</h3> <p>The main C code (e.g. that in files <samp><span class="file">src/*/*.c</span></samp> and in the modules) is where R is closest to the sort of application for which ‘<samp><span class="samp">gettext</span></samp>’ was written. Messages in the main C code are in domain <code>R</code> and stored in the top-level directory <samp><span class="file">po</span></samp> with compiled translations under <samp><span class="file">share/locale</span></samp>. <p>The list of files covered by the R domain is specified in file <samp><span class="file">po/POTFILES.in</span></samp>. <p>The normal way to mark messages for translation is via <code>_("msg")</code> just as for packages. However, sometimes one needs to mark passages for translation without wanting them translated at the time, for example when declaring string constants. This is the purpose of the <code>N_</code> macro, for example <pre class="example"> { ERROR_ARGTYPE, N_("invalid argument type")}, </pre> <p class="noindent">from file <samp><span class="file">src/main/errors.c</span></samp>. <p>The <code>P_</code> macro <pre class="example"> #ifdef ENABLE_NLS #define P_(StringS, StringP, N) ngettext (StringS, StringP, N) #else #define P_(StringS, StringP, N) (N > 1 ? StringP: StringS) #endif </pre> <p class="noindent">may be used as a wrapper for <code>ngettext</code>: however in some cases the preferred approach has been to conditionalize (on <code>ENABLE_NLS</code>) code using <code>ngettext</code>. <p>The macro <code>_("msg")</code> can safely be used in directory <samp><span class="file">src/appl</span></samp>; the header for standalone ‘<samp><span class="samp">nmath</span></samp>’ skips possible translation. (This does not apply to <code>N_</code> or <code>P_</code>). <div class="node"> <a name="Windows-GUI-specific-code"></a> <a name="Windows_002dGUI_002dspecific-code"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#OS-X-GUI">OS X GUI</a>, Previous: <a rel="previous" accesskey="p" href="#Main-C-code">Main C code</a>, Up: <a rel="up" accesskey="u" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a> </div> <h3 class="section">3.3 Windows-GUI-specific code</h3> <p>Messages for the Windows GUI are in a separate domain ‘<samp><span class="samp">RGui</span></samp>’. This was done for two reasons: <ul> <li>The translators for the Windows version of R might be separate from those for the rest of R (familiarity with the GUI helps), and <li>Messages for Windows are most naturally handled in the native charset for the language, and in the case of CJK languages the charset is Windows-specific. (It transpires that as the <code>iconv</code> we ported works well under Windows, this is less important than anticipated.) </ul> <p>Messages for the ‘<samp><span class="samp">RGui</span></samp>’ domain are marked by <code>G_("msg")</code>, a macro that is defined in header file <samp><span class="file">src/gnuwin32/win-nls.h</span></samp>. The list of files that are considered is hardcoded in the <code>RGui.pot-update</code> target of file <samp><span class="file">po/Makefile.in.in</span></samp>: note that this includes <samp><span class="file">devWindows.c</span></samp> as the menus on the <code>windows</code> device are considered to be part of the GUI. (There is also <code>GN_("msg")</code>, the analogue of <code>N_("msg")</code>.) <p>The template and message catalogs for the ‘<samp><span class="samp">RGui</span></samp>’ domain are in the top-level <samp><span class="file">po</span></samp> directory. <div class="node"> <a name="OS-X-GUI"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Updating">Updating</a>, Previous: <a rel="previous" accesskey="p" href="#Windows_002dGUI_002dspecific-code">Windows-GUI-specific code</a>, Up: <a rel="up" accesskey="u" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a> </div> <h3 class="section">3.4 OS X GUI</h3> <p>This is handled separately: see <a href="http://developer.r-project.org/Translations.html">http://developer.r-project.org/Translations.html</a>. <div class="node"> <a name="Updating"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#OS-X-GUI">OS X GUI</a>, Up: <a rel="up" accesskey="u" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a> </div> <h3 class="section">3.5 Updating</h3> <p>See file <samp><span class="file">po/README</span></samp> for how to update the message templates and catalogs. <div class="node"> <a name="Package-Structure"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Files">Files</a>, Previous: <a rel="previous" accesskey="p" href="#Internationalization-in-the-R-sources">Internationalization in the R sources</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">4 Structure of an Installed Package</h2> <ul class="menu"> <li><a accesskey="1" href="#Metadata">Metadata</a> <li><a accesskey="2" href="#Help">Help</a> </ul> <p>The structure of a <em>source</em> packages is described in <a href="R-exts.html#Creating-R-packages">Creating R packages</a>: this chapter is concerned with the structure of <em>installed</em> packages. <p>An installed package has a top-level file <samp><span class="file">DESCRIPTION</span></samp>, a copy of the file of that name in the package sources with a ‘<samp><span class="samp">Built</span></samp>’ field appended, and file <samp><span class="file">INDEX</span></samp>, usually describing the objects on which help is available, a file <samp><span class="file">NAMESPACE</span></samp> if the package has a name space, optional files such as <samp><span class="file">CITATION</span></samp>, <samp><span class="file">LICENCE</span></samp> and <samp><span class="file">NEWS</span></samp>, and any other files copied in from <samp><span class="file">inst</span></samp>. It will have directories <samp><span class="file">Meta</span></samp>, <samp><span class="file">help</span></samp> and <samp><span class="file">html</span></samp> (even if the package has no help pages), almost always has a directory <samp><span class="file">R</span></samp> and often has a directory <samp><span class="file">libs</span></samp> to contain compiled code. Other directories with known meaning to R are <samp><span class="file">data</span></samp>, <samp><span class="file">demo</span></samp>, <samp><span class="file">doc</span></samp> and <samp><span class="file">po</span></samp>. <p>Function <code>library</code> looks for a namespace and if one is found passes control to <code>loadNamespace</code>. Then <code>library</code> or <code>loadNamespace</code> looks for file <samp><span class="file">R/</span><var>pkgname</var></samp>, warns if it is not found and otherwise sources the code (using <code>sys.source</code>) into the package's environment, then lazy-loads a database <samp><span class="file">R/sysdata</span></samp> if present. So how R code gets loaded depends on the contents of <samp><span class="file">R/</span><var>pkgname</var></samp>: a standard template to load lazy-load databases are provided in <samp><span class="file">share/R/nspackloader.R</span></samp>. <p>Compiled code is usually loaded when the package's namespace is loaded by a <code>useDynlib</code> directive in a <samp><span class="file">NAMESPACE</span></samp> file or by the package's <code>.onLoad</code> function. Conventionally compiled code is loaded by a call to <code>library.dynam</code> and this looks in directory <samp><span class="file">libs</span></samp> (and in an appropriate sub-directory if sub-architectures are in use) for a shared object (Unix-alike) or DLL (Windows). <p>Subdirectory <samp><span class="file">data</span></samp> serves two purposes. In a package using lazy-loading of data, it contains a lazy-load database <samp><span class="file">Rdata</span></samp>, plus a file <samp><span class="file">Rdata.rds</span></samp> which contain a named character vector used by <code>data()</code> in the (unusual) event that it is used for such a package. Otherwise it is a copy of the <samp><span class="file">data</span></samp> directory in the sources, with saved images re-compressed if <samp><span class="command">R CMD INSTALL --resave-data</span></samp> was used. <p>Subdirectory <samp><span class="file">demo</span></samp> supports the <code>demo</code> function, and is copied from the sources. <p>Subdirectory <samp><span class="file">po</span></samp> contains (in subdirectories) compiled message catalogs. <div class="node"> <a name="Metadata"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Help">Help</a>, Previous: <a rel="previous" accesskey="p" href="#Package-Structure">Package Structure</a>, Up: <a rel="up" accesskey="u" href="#Package-Structure">Package Structure</a> </div> <h3 class="section">4.1 Metadata</h3> <p>Directory <samp><span class="file">Meta</span></samp> contains several files in <code>.rds</code> format, that is serialized R objects written by <code>saveRDS</code>. All packages have files <samp><span class="file">Rd.rds</span></samp>, <samp><span class="file">hsearch.rds</span></samp>, <samp><span class="file">links.rds</span></samp> and <samp><span class="file">package.rds</span></samp>. Packages with namespaces have a file <samp><span class="file">nsInfo.rds</span></samp>, and those with data, demos or vignettes have <samp><span class="file">data.rds</span></samp>, <samp><span class="file">demo.rds</span></samp> or <samp><span class="file">vignette.rds</span></samp> files. <p>The structure of these files (and their existence and names) is private to R, so the description here is for those trying to follow the R sources: there should be no reference to these files in non-base packages. <p>File <samp><span class="file">package.rds</span></samp> is a dump of information extracted from the <samp><span class="file">DESCRIPTION</span></samp> file. It is a list of several components. The first, ‘<samp><span class="samp">DESCRIPTION</span></samp>’, is a character vector, the <samp><span class="file">DESCRIPTION</span></samp> file as read by <code>read.dcf</code>. Further elements ‘<samp><span class="samp">Depends</span></samp>’, ‘<samp><span class="samp">Suggests</span></samp>’, ‘<samp><span class="samp">Imports</span></samp>’, ‘<samp><span class="samp">Rdepends</span></samp>’ and ‘<samp><span class="samp">Rdepends2</span></samp>’ record the ‘<samp><span class="samp">Depends</span></samp>’, ‘<samp><span class="samp">Suggests</span></samp>’ and ‘<samp><span class="samp">Imports</span></samp>’ fields. These are all lists, and can be empty. The first three have an entry for each package named, each entry being a list of length 1 or 3, which element ‘<samp><span class="samp">name</span></samp>’ (the package name) and optional elements ‘<samp><span class="samp">op</span></samp>’ (a character string) and ‘<samp><span class="samp">version</span></samp>’ (an object of class ‘<samp><span class="samp">"package_version"</span></samp>’). Element ‘<samp><span class="samp">Rdepends</span></samp>’ is used for the first version dependency on R, and ‘<samp><span class="samp">Rdepends2</span></samp>’ is a list of zero or more R version dependencies—each is a three-element list of the form described for packages. Element ‘<samp><span class="samp">Rdepends</span></samp>’ is no longer used, but it is still potentially needed so R < 2.7.0 can detect that the package was not installed for it. <p>File <samp><span class="file">nsInfo.rds</span></samp> records a list, a parsed version of the <samp><span class="file">NAMESPACE</span></samp> file. <p>File <samp><span class="file">Rd.rds</span></samp> records a data frame with one row for each help file. The columns are ‘<samp><span class="samp">File</span></samp>’ (the file name with extension), ‘<samp><span class="samp">Name</span></samp>’ (the ‘<samp><span class="samp">\name</span></samp>’ section), ‘<samp><span class="samp">Type</span></samp>’ (from the optional ‘<samp><span class="samp">\docType</span></samp>’ section), ‘<samp><span class="samp">Title</span></samp>’, ‘<samp><span class="samp">Encoding</span></samp>’, ‘<samp><span class="samp">Aliases</span></samp>’, ‘<samp><span class="samp">Concepts</span></samp>’ and ‘<samp><span class="samp">Keywords</span></samp>’. All columns are character vectors apart from ‘<samp><span class="samp">Aliases</span></samp>’, which is a list of character vectors. <p>File <samp><span class="file">hsearch.rds</span></samp> records the information to be used by ‘<samp><span class="samp">help.search</span></samp>’. This is a list of four unnamed elements which are character matrices for help files, aliases, keywords and concepts. All the matrices have columns ‘<samp><span class="samp">ID</span></samp>’ and ‘<samp><span class="samp">Package</span></samp>’ which are used to tie the aliases, keywords and concepts (the remaining column of the last three elements) to a particular help file. The first element has further columns ‘<samp><span class="samp">LibPath</span></samp>’ (stored as <code>""</code> and filled in what the file is loaded), ‘<samp><span class="samp">name</span></samp>’, ‘<samp><span class="samp">title</span></samp>’, ‘<samp><span class="samp">topic</span></samp>’ (the first alias, used when presenting the results as ‘<samp><var>pkgname</var><span class="samp">::</span><var>topic</var></samp>’) and ‘<samp><span class="samp">Encoding</span></samp>’. <p>File <samp><span class="file">links.rds</span></samp> records a named character vector, the names being aliases and the values character strings of the form <pre class="example"> "../../<var>pkgname</var>/html/<var>filename</var>.html" </pre> <p>File <samp><span class="file">data.rds</span></samp> records a two-column character matrix with columns of dataset names and titles from the corresponding help file. File <samp><span class="file">demo.rds</span></samp> has the same structure for package demos. <p>File <samp><span class="file">vignette.rds</span></samp> records a dataframe with one row for each ‘vignette’ (<samp><span class="file">.[RS]nw</span></samp> file in <samp><span class="file">inst/doc</span></samp>) and with columns ‘<samp><span class="samp">File</span></samp>’ (the full file path in the sources), ‘<samp><span class="samp">Title</span></samp>’, ‘<samp><span class="samp">PDF</span></samp>’ (the pathless file name of the installed PDF version, if present), ‘<samp><span class="samp">Depends</span></samp>’, ‘<samp><span class="samp">Keywords</span></samp>’ and ‘<samp><span class="samp">R</span></samp>’ (the pathless file name of the installed R code, if present). <div class="node"> <a name="Help"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Metadata">Metadata</a>, Up: <a rel="up" accesskey="u" href="#Package-Structure">Package Structure</a> </div> <h3 class="section">4.2 Help</h3> <p>All installed packages, whether they had any <samp><span class="file">.Rd</span></samp> files or not, have <samp><span class="file">help</span></samp> and <samp><span class="file">html</span></samp> directories. The latter normally only contains the single file <samp><span class="file">00Index.html</span></samp>, the package index which has hyperlinks to the help topics (if any). <p>Directory <samp><span class="file">help</span></samp> contains files <samp><span class="file">AnIndex</span></samp>, <samp><span class="file">paths.rds</span></samp> and <samp><var>pkgname</var><span class="file">.rd[bx]</span></samp>. The latter two files are a lazy-load database of parsed <samp><span class="file">.Rd</span></samp> files, accessed by <code>tools:::fetchRdDB</code>. File <samp><span class="file">paths.rds</span></samp> is a saved character vector of the original path names of the <samp><span class="file">.Rd</span></samp> files, used when updating the database. <p>File <samp><span class="file">AnIndex</span></samp> is a two-column tab-delimited file: the first column contains the aliases defined in the help files and the second the basename (without the <samp><span class="file">.Rd</span></samp> or <samp><span class="file">.rd</span></samp> extension) of the file containing that alias. It is read by <code>utils:::index.search</code> to search for files matching a topic (alias), and read by <code>scan</code> in <code>utils:::matchAvailableTopics</code>, part of the completion system. <p>File <samp><span class="file">aliases.rds</span></samp> is the same information as <samp><span class="file">AnIndex</span></samp> as a named character vector (names the topics, values the file basename), for faster access. <div class="node"> <a name="Files"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Graphics-Devices">Graphics Devices</a>, Previous: <a rel="previous" accesskey="p" href="#Package-Structure">Package Structure</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">5 Files</h2> <p>R provides many functions to work with files and directories: many of these have been added relatively recently to facilitate scripting in R and in particular the replacement of Perl scripts by R scripts in the management of R itself. <p>These functions are implemented by standard C/POSIX library calls, except on Windows. That means that filenames must be encoded in the current locale as the OS provides no other means to access the file system: increasingly filenames are stored in UTF-8 and the OS will translate filenames to UTF-8 in other locales. So using a UTF-8 locale gives transparent access to the whole file system. <p>Windows is another story. There the internal view of filenames is in UTF-16LE (so-called ‘Unicode’), and standard C library calls can only access files whose names can be expressed in the current codepage. To circumvent that restriction, there is a parallel set of Windows-specific calls which take wide-character arguments for filepaths. Much of the file-handling in R has been moved over to using these functions, so filenames can be manipulated in R as UTF-8 encoded character strings, converted to wide characters (which on Windows are UTF-16LE) and passed to the OS. The utilities <code>RC_fopen</code> and <code>filenameToWchar</code> help this process. Currently <code>file.copy</code> to a directory, <code>list.files</code>, <code>list.dirs</code> and <code>path.expand</code> work only with filepaths encoded in the current codepage. <p>All these functions do tilde expansion, in the same way as <code>path.expand</code>, with the deliberate exception of <code>Sys.glob</code>. <p>File names may be case sensitive or not: the latter is the norm on Windows and OS X, the former on other Unix-alikes. Note that this is a property of both the OS and the file system: it is often possible to map names to upper or lower case when mounting the file system. This can affect the matching of patterns in <code>list.files</code> and <code>Sys.glob</code>. <p>File names commonly contain spaces on Windows and OS X but not elsewhere. As file names are handled as character strings by R, spaces are not usually a concern unless file names are passed to other process, e.g. by a <code>system</code> call. <p>Windows has another couple of peculiarities. Whereas a POSIX file system has a single root directory (and other physical file systems are mounted onto logical directories under that root), Windows has separate roots for each physical or logical file system (‘volume’), organized under <em>drives</em> (with file paths starting <code>D:</code> for an <acronym>ASCII</acronym> letter, case-insensitively) and <em>network shares</em> (with paths like <code>\netname\topdir\myfiles\a file</code>. There is a current drive, and path names without a drive part are relative to the current drive. Further, each drive has a current directory, and relative paths are relative to that current directory, on a particular drive if one is specified. So <samp><span class="file">D:dir\file</span></samp> and <samp><span class="file">D:</span></samp> are valid path specifications (the last being the current directory on drive <samp><span class="file">D:</span></samp>). <!-- basename Wchar na --> <!-- dir.create Wchar ~ --> <!-- dirname Wchar ~ --> <!-- getwd --> <!-- file.access Wchar ~ --> <!-- file.append RC_fopen --> <!-- file.copy no ~ (+ file.append) --> <!-- file.create RC_fopen --> <!-- file.edit UTF-8 in R code --> <!-- file.exists Wchar ~ --> <!-- file.info Wchar ~ --> <!-- file.link 8-bit ~ --> <!-- file.remove Wchar ~ --> <!-- file.rename Wchar ~ --> <!-- file.show UTF-8 in R code --> <!-- file.symlink not ~ --> <!-- file_test --> <!-- list.dirs no ~ --> <!-- list.files no ~ --> <!-- normalizePath Wchar ~ --> <!-- path.expand no --> <!-- setwd Wchar ~ --> <!-- Sys.chmod Wchar ~ --> <!-- Sys.glob Wchar not --> <!-- Sys.readlink not ~ --> <!-- Sys.umask --> <!-- unlink Wchar ~ --> <div class="node"> <a name="Graphics-Devices"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#GUI-consoles">GUI consoles</a>, Previous: <a rel="previous" accesskey="p" href="#Files">Files</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">6 Graphics</h2> <p>R's graphics internals were re-designed to enable multiple graphics systems to be installed on top on the graphics ‘engine’ – currently there are two such systems, one supporting ‘base’ graphics (based on that in S and whose R code<a rel="footnote" href="#fn-15" name="fnd-15"><sup>15</sup></a> is in package <strong>graphics</strong>) and one implemented in package <strong>grid</strong>. <p>Some notes on the historical changes can be found at <a href="http://www.stat.auckland.ac.nz/~paul/R/basegraph.html">http://www.stat.auckland.ac.nz/~paul/R/basegraph.html</a> and <a href="http://www.stat.auckland.ac.nz/~paul/R/graphicsChanges.html">http://www.stat.auckland.ac.nz/~paul/R/graphicsChanges.html</a>. <p>At the lowest level is a graphics device, which manages a plotting surface (a screen window or a representation to be written to a file). This implements a set of graphics primitives, to ‘draw’ <ul> <li>a circle, optionally filled <li>a rectangle, optionally filled <li>a line <li>a set of connected lines <li>a polygon, optionally filled <li>a paths, optionally filled using a winding rule <li>text <li>a raster image (optional) <li>and to set a clipping rectangle </ul> <p class="noindent">as well as requests for information such as <ul> <li>the width of a string if plotted <li>the metrics (width, ascent, descent) of a single character <li>the current size of the plotting surface </ul> <p class="noindent">and requests/opportunities to take action such as <ul> <li>start a new ‘page’, possibly after responding to a request to ask the user for confirmation. <li>return the position of the device pointer (if any). <li>when a device become the current device or stops being the current device (this is usually used to change the window title on a screen device). <li>when drawing starts or finishes (e.g. used to flush graphics to the screen when drawing stops). <li>wait for an event, for example a mouse click or keypress. <li>an ‘onexit’ action, to clean up if plotting is interrupted (by an error or by the user). <li>capture the current contents of the device as a raster image. <li>close the device. </ul> <p>The device also sets a number of variables, mainly Boolean flags indicating its capabilities. Devices work entirely in ‘device units’ which are up to its developer: they can be in pixels, big points (1/72 inch), twips, <small class="dots">...</small>, and can differ<a rel="footnote" href="#fn-16" name="fnd-16"><sup>16</sup></a> in the ‘<samp><span class="samp">x</span></samp>’ and ‘<samp><span class="samp">y</span></samp>’ directions. <!-- think of the engine as colors.c, devices.c, engine.c, plotmath.c, vfonts.c --> <p>The next layer up is the graphics ‘engine’ that is the main interface to the device (although the graphics subsystems do talk directly to devices). This is responsible for clipping lines, rectangles and polygons, converting the <code>pch</code> values <code>0...26</code> to sets of lines/circles, centring (and otherwise adjusting) text, rendering mathematical expressions (‘plotmath’) and mapping colour descriptions such as names to the internal representation. <!-- graphics.c looks at device dimensions, locator, metricinfo --> <!-- par.c looks at various device pars --> <!-- plot3d.c looks at useRotatedTextInContour --> <!-- grid looks at size, clipping, locator, ipr --> <p>Another function of the engine is to manage display lists and snapshots. Some but not all instances of graphics devices maintain display lists, a ‘list’ of operations that have been performed on the device to produce the current plot (since the device was opened or the plot was last cleared, e.g. by <code>plot.new</code>). Screen devices generally maintain a display list to handle repaint and resize events whereas file-based formats do not—display lists are also used to implement <code>dev.copy()</code> and friends. The display list is a pairlist of <code>.Internal</code> (base graphics) or <code>.Call.graphics</code> (grid graphics) calls, which means that the C code implementing a graphics operation will be re-called when the display list is replayed: apart from the part which records the operation if successful. <p>Snapshots of the current graphics state are taken by <code>GEcreateSnapshot</code> and replayed later in the session by <code>GEplaySnapshot</code>. These are used by <code>recordPlot()</code>, <code>replayPlot()</code> and the GUI menus of the <code>windows()</code> device. The ‘state’ includes the display list. <p>The top layer comprises the graphics subsystems. Although there is provision for 24 subsystems, after 6 years only two exist, ‘base’ and ‘grid’. The base subsystem is registered with the engine when R is initialized, and unregistered (via <code>KillAllDevices</code>) when an R session is shut down. The grid subsystem is registered in its <code>.onLoad</code> function and unregistered in the <code>.onUnload</code> function. The graphics subsystem may also have ‘state’ information saved in a snapshot (currently base does and grid does not). <p>Package <strong>grDevices</strong> was originally created to contain the basic graphics devices (although <code>X11</code> is in a separate load-on-demand module because of the volume of external libraries it brings in). Since then it has been used for other functionality that was thought desirable for use with <strong>grid</strong>, and hence has been transferred from package <strong>graphics</strong> to <strong>grDevices</strong>. This is principally concerned with the handling of colours and recording and replaying plots. <ul class="menu"> <li><a accesskey="1" href="#Graphics-devices">Graphics devices</a> <li><a accesskey="2" href="#Colours">Colours</a> <li><a accesskey="3" href="#Base-graphics">Base graphics</a> <li><a accesskey="4" href="#Grid-graphics">Grid graphics</a> </ul> <div class="node"> <a name="Graphics-devices"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Colours">Colours</a>, Previous: <a rel="previous" accesskey="p" href="#Graphics-Devices">Graphics Devices</a>, Up: <a rel="up" accesskey="u" href="#Graphics-Devices">Graphics Devices</a> </div> <h3 class="section">6.1 Graphics Devices</h3> <p>R ships with several graphics devices, and there is support for third-party packages to provide additional devices—several packages now do. This section describes the device internals from the viewpoint of a would-be writer of a graphics device. <ul class="menu"> <li><a accesskey="1" href="#Device-structures">Device structures</a> <li><a accesskey="2" href="#Device-capabilities">Device capabilities</a> <li><a accesskey="3" href="#Handling-text">Handling text</a> <li><a accesskey="4" href="#Conventions">Conventions</a> <li><a accesskey="5" href="#g_t_0027Mode_0027">'Mode'</a> <li><a accesskey="6" href="#Graphics-events">Graphics events</a> <li><a accesskey="7" href="#Specific-devices">Specific devices</a> </ul> <div class="node"> <a name="Device-structures"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Device-capabilities">Device capabilities</a>, Previous: <a rel="previous" accesskey="p" href="#Graphics-devices">Graphics devices</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.1 Device structures</h4> <p>There are two types used internally which are pointers to structures related to graphics devices. <p>The <code>DevDesc</code> type is a structure defined in the header file <samp><span class="file">R_ext/GraphicsDevice.h</span></samp> (which is included by <samp><span class="file">R_ext/GraphicsEngine.h</span></samp>). This describes the physical characteristics of a device, the capabilities of the device driver and contains a set of callback functions that will be used by the graphics engine to obtain information about the device and initiate actions (e.g. a new page, plotting a line or some text). Type <code>pDevDesc</code> is a pointer to this type. <p>The following callbacks can be omitted (or set to the null pointer, their default value) when appropriate default behaviour will be taken by the graphics engine: <code>activate</code>, <code>cap</code>, <code>deactivate</code>, <code>locator</code>, <code>holdflush</code> (API version 9), <code>mode</code>, <code>newFrameConfirm</code>, <code>path</code>, <code>raster</code> and <code>size</code>. <p>The relationship of device units to physical dimensions is set by the element <code>ipr</code> of the <code>DevDesc</code> structure: a ‘<samp><span class="samp">double</span></samp>’ array of length 2. <p>The <code>GEDevDesc</code> type is a structure defined in <samp><span class="file">R_ext/GraphicsEngine.h</span></samp> (with comments in the file) as <pre class="example"> typedef struct _GEDevDesc GEDevDesc; struct _GEDevDesc { pDevDesc dev; Rboolean displayListOn; SEXP displayList; SEXP DLlastElt; SEXP savedSnapshot; Rboolean dirty; Rboolean recordGraphics; GESystemDesc *gesd[MAX_GRAPHICS_SYSTEMS]; Rboolean ask; } </pre> <p class="noindent">So this is essentially a device structure plus information about the device maintained by the graphics engine and normally<a rel="footnote" href="#fn-17" name="fnd-17"><sup>17</sup></a> visible to the engine and not to the device. Type <code>pGEDevDesc</code> is a pointer to this type. <p>The graphics engine maintains an array of devices, as pointers to <code>GEDevDesc</code> structures. The array is of size 64 but the first element is always occupied by the <code>"null device"</code> and the final element is kept as NULL as a sentinel.<a rel="footnote" href="#fn-18" name="fnd-18"><sup>18</sup></a> This array is reflected in the R variable ‘<samp><span class="samp">.Devices</span></samp>’. Once a device is killed its element becomes available for reallocation (and its name will appear as <code>""</code> in ‘<samp><span class="samp">.Devices</span></samp>’). Exactly one of the devices is ‘active’: this is the the null device if no other device has been opened and not killed. <p>Each instance of a graphics device needs to set up a <code>GEDevDesc</code> structure by code very similar to <pre class="example"> pGEDevDesc gdd; R_GE_checkVersionOrDie(R_GE_version); R_CheckDeviceAvailable(); BEGIN_SUSPEND_INTERRUPTS { pDevDesc dev; /* Allocate and initialize the device driver data */ if (!(dev = (pDevDesc) calloc(1, sizeof(DevDesc)))) return 0; /* or error() */ /* set up device driver or free ‘dev’ and error() */ gdd = GEcreateDevDesc(dev); GEaddDevice2(gdd, "dev_name"); } END_SUSPEND_INTERRUPTS; </pre> <p>The <code>DevDesc</code> structure contains a <code>void *</code> pointer ‘<samp><span class="samp">deviceSpecific</span></samp>’ which is used to store data specific to the device. Setting up the device driver includes initializing all the non-zero elements of the <code>DevDesc</code> structure. <p>Note that the device structure is zeroed when allocated: this provides some protection against future expansion of the structure since the graphics engine can add elements that need to be non-NULL/non-zero to be ‘on’ (and the structure ends with 64 reserved bytes which will be zeroed and allow for future expansion). <p>Rather more protection is provided by the version number of the engine/device API, <code>R_GE_version</code> defined in <samp><span class="file">R_ext/GraphicsEngine.h</span></samp> together with access functions <pre class="example"> int R_GE_getVersion(void); void R_GE_checkVersionOrDie(int version); </pre> <p class="noindent">If a graphics device calls <code>R_GE_checkVersionOrDie(R_GE_version)</code> it can ensure it will only be used in versions of R which provide the API it was designed for and compiled against. <div class="node"> <a name="Device-capabilities"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Handling-text">Handling text</a>, Previous: <a rel="previous" accesskey="p" href="#Device-structures">Device structures</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.2 Device capabilities</h4> <p>The following ‘capabilities’ can be defined for the device's <code>DevDesc</code> structure. <ul> <li><code>canChangeGamma</code> – <code>Rboolean</code>: can the display gamma be adjusted? This is now ignored, as gamma support has been removed. <li><code>canHadj</code> – <code>integer</code>: can the device do horizontal adjustment of text <em>via</em> the <code>text</code> callback, and if so, how precisely? 0 = no adjustment, 1 = {0, 0.5, 1} (left, centre, right justification) or 2 = continuously variable (in [0,1]) between left and right justification. <li><code>canGenMouseDown</code> – <code>Rboolean</code>: can the device handle mouse down events? This flag and the next three are not currently used by R, but are maintained for back compatibility. <li><code>canGenMouseMove</code> – <code>Rboolean</code>: ditto for mouse move events. <li><code>canGenMouseUp</code> – <code>Rboolean</code>: ditto for mouse up events. <li><code>canGenKeybd</code> – <code>Rboolean</code>: ditto for keyboard events. <li><code>hasTextUTF8</code> – <code>Rboolean</code>: should non-symbol text be sent (in UTF-8) to the <code>textUTF8</code> and <code>strWidthUTF8</code> callbacks, and sent as Unicode points (negative values) to the <code>metricInfo</code> callback? <li><code>wantSymbolUTF8</code> – <code>Rboolean</code>: should symbol text be handled in UTF-8 in the same way as other text? Requires <code>textUTF8 = TRUE</code>. <li><code>haveTransparency</code>: does the device support semi-transparent colours? <li><code>haveTransparentBg</code>: can the background be fully or semi-transparent? <li><code>haveRaster</code>: is there support for rendering raster images? <li><code>haveCapture</code>: is there support for <code>grid::grid.cap</code>? <li><code>haveLocator</code>: is there an interactive locator? </ul> <p>The last three can often be deduced to be false from the presence of <code>NULL</code> entries instead of the corresponding functions. <div class="node"> <a name="Handling-text"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Conventions">Conventions</a>, Previous: <a rel="previous" accesskey="p" href="#Device-capabilities">Device capabilities</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.3 Handling text</h4> <p>Handling text is probably the hardest task for a graphics device, and the design allows for the device to optionally indicate that it has additional capabilities. (If the device does not, these will if possible be handled in the graphics engine.) <p>The three callbacks for handling text that must be in all graphics devices are <code>text</code>, <code>strWidth</code> and <code>metricInfo</code> with declarations <pre class="example"> void text(double x, double y, const char *str, double rot, double hadj, pGgcontext gc, pDevDesc dd); double strWidth(const char *str, pGEcontext gc, pDevDesc dd); void metricInfo(int c, pGEcontext gc, double* ascent, double* descent, double* width, pDevDesc dd); </pre> <p class="noindent">The ‘<samp><span class="samp">gc</span></samp>’ parameter provides the graphics context, most importantly the current font and fontsize, and ‘<samp><span class="samp">dd</span></samp>’ is a pointer to the active device's structure. <p>The <code>text</code> callback should plot ‘<samp><span class="samp">str</span></samp>’ at ‘<samp><span class="samp">(x, y)</span></samp>’<a rel="footnote" href="#fn-19" name="fnd-19"><sup>19</sup></a> with an anti-clockwise rotation of ‘<samp><span class="samp">rot</span></samp>’ degrees. (For ‘<samp><span class="samp">hadj</span></samp>’ see below.) The interpretation for horizontal text is that the baseline is at <code>y</code> and the start is a <code>x</code>, so any left bearing for the first character will start at <code>x</code>. <p>The <code>strWidth</code> callback computes the width of the string which it would occupy if plotted horizontally in the current font. (Width here is expected to include both (preferably) or neither of left and right bearings.) <p>The <code>metricInfo</code> callback computes the size of a single character: <code>ascent</code> is the distance it extends above the baseline and <code>descent</code> how far it extends below the baseline. <code>width</code> is the amount by which the cursor should be advanced when the character is placed. For <code>ascent</code> and <code>descent</code> this is intended to be the bounding box of the ‘ink’ put down by the glyph and not the box which might be used when assembling a line of conventional text (it needs to be for e.g. <code>hat(beta)</code> to work correctly). However, the <code>width</code> is used in plotmath to advance to the next character, and so needs to include left and right bearings. <p>The <em>interpretation</em> of ‘<samp><span class="samp">c</span></samp>’ depends on the locale. In a single-byte locale values <code>32...255</code> indicate the corresponding character in the locale (if present). For the symbol font (as used by ‘<samp><span class="samp">graphics::par(font=5)</span></samp>’, ‘<samp><span class="samp">grid::gpar(fontface=5</span></samp>’) and by ‘plotmath’), values <code>32...126, 161...239, 241...254</code> indicate glyphs in the Adobe Symbol encoding. In a multibyte locale, <code>c</code> represents a Unicode point (except in the symbol font). So the function needs to include code like <pre class="example"> Rboolean Unicode = mbcslocale && (gc->fontface != 5); if (c < 0) { Unicode = TRUE; c = -c; } if(Unicode) UniCharMetric(c, ...); else CharMetric(c, ...); </pre> <p class="noindent">In addition, if device capability <code>hasTextUTF8</code> (see below) is true, Unicode points will be passed as negative values: the code snippet above shows how to handle this. (This applies to the symbol font only if device capability <code>wantSymbolUTF8</code> is true.) <p>If possible, the graphics device should handle clipping of text. It indicates this by the structure element <code>canClip</code> which if true will result in calls to the callback <code>clip</code> to set the clipping region. If this is not done, the engine will clip very crudely (by omitting any text that does not appear to be wholly inside the clipping region). <p>The device structure has an integer element <code>canHadj</code>, which indicates if the device can do horizontal alignment of text. If this is one, argument ‘<samp><span class="samp">hadj</span></samp>’ to <code>text</code> will be called as <code>0 ,0.5, 1</code> to indicate left-, centre- and right-alignment at the indicated position. If it is two, continuous values in the range <code>[0, 1]</code> are assumed to be supported. <p>Capability <code>hasTextUTF8</code> if true, it has two consequences. First, there are callbacks <code>textUTF8</code> and <code>strWidthUTF8</code> that should behave identically to <code>text</code> and <code>strWidth</code> except that ‘<samp><span class="samp">str</span></samp>’ is assumed to be in UTF-8 rather than the current locale's encoding. The graphics engine will call these for all text except in the symbol font. Second, Unicode points will be passed to the <code>metricInfo</code> callback as negative integers. If your device would prefer to have UTF-8-encoded symbols, define <code>wantSymbolUTF8</code> as well as <code>hasTextUTF8</code>. In that case text in the symbol font is sent to <code>textUTF8</code> and <code>strWidthUTF8</code>. <p>Some devices can produce high-quality rotated text, but those based on bitmaps often cannot. Those which can should set <code>useRotatedTextInContour</code> to be true from graphics API version 4. <p>Several other elements relate to the precise placement of text by the graphics engine: <pre class="example"> double xCharOffset; double yCharOffset; double yLineBias; double cra[2]; </pre> <p class="noindent">These are more than a little mysterious. Element <code>cra</code> provides an indication of the character size, <code>par("cra")</code> in base graphics, in device units. The mystery is what is meant by ‘character size’: which character, which font at which size? Some help can be obtained by looking at what this is used for. The first element, ‘width’, is not used by R except to set the graphical parameters. The second, ‘height’, is use to set the line spacing, that is the relationship between <code>par("mai")</code> and <code>par("mai")</code> and so on. It is suggested that a good choice is <pre class="example"> dd->cra[0] = 0.9 * fnsize; dd->cra[1] = 1.2 * fnsize; </pre> <p class="noindent">where ‘<samp><span class="samp">fnsize</span></samp>’ is the ‘size’ of the standard font (<code>cex=1</code>) on the device, in device units. So for a 12-point font (the usual default for graphics devices), ‘<samp><span class="samp">fnsize</span></samp>’ should be 12 points in device units. <p>The remaining elements are yet more mysterious. The <code>postscript()</code> device says <pre class="example"> /* Character Addressing Offsets */ /* These offsets should center a single */ /* plotting character over the plotting point. */ /* Pure guesswork and eyeballing ... */ dd->xCharOffset = 0.4900; dd->yCharOffset = 0.3333; dd->yLineBias = 0.2; </pre> <p class="noindent">It seems that <code>xCharOffset</code> is not currently used, and <code>yCharOffset</code> is used by the base graphics system to set vertical alignment in <code>text()</code> when <code>pos</code> is specified, and in <code>identify()</code>. It is occasionally used by the graphic engine when attempting exact centring of text, such as character string values of <code>pch</code> in <code>points()</code> or <code>grid.points()</code>—however, it is only used when precise character metric information is not available or for multi-line strings. <p><code>yLineBias</code> is used in the base graphics system in <code>axis()</code> and <code>mtext()</code> to provide a default for their ‘<samp><span class="samp">padj</span></samp>’ argument. <div class="node"> <a name="Conventions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#g_t_0027Mode_0027">'Mode'</a>, Previous: <a rel="previous" accesskey="p" href="#Handling-text">Handling text</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.4 Conventions</h4> <p>The aim is to make the (default) output from graphics devices as similar as possible. Generally people follow the model of the <code>postscript</code> and <code>pdf</code> devices (which share most of their internal code). <p>The following conventions have become established: <ul> <li>The default size of a device should be 7 inches square. <li>There should be a ‘<samp><span class="samp">pointsize</span></samp>’ argument which defaults to 12, and it should give the pointsize in big points (1/72 inch). How exactly this is interpreted is font-specific, but it should use a font which works with lines packed 1/6 inch apart, and looks good with lines 1/5 inch apart (that is with 2pt leading). <li>The default font family should be a sans serif font, e.g Helvetica or similar (e.g. Arial on Windows). <li><code>lwd = 1</code> should correspond to a line width of 1/96 inch. This will be a problem with pixel-based devices, and generally there is a minimum line width of 1 pixel (although this may not be appropriate where anti-aliasing of lines is used, and <code>cairo</code> prefers a minimum of 2 pixels). <li>Even very small circles should be visible, e.g. by using a minimum radius of 1 pixel or replacing very small circles by a single filled pixel. <li>How RGB colour values will be interpreted should be documented, and preferably be sRGB. <li>The help page should describe its policy on these conventions. </ul> <p>These conventions are less clear-cut for bitmap devices, especially where the bitmap format does not have a design resolution. <p>The interpretation of the line texture (<code>par("lty"</code>) is described in the header <samp><span class="file">GraphicsEngine.h</span></samp> and in the help for <code>par</code>: note that the ‘scale’ of the pattern should be proportional to the line width (at least for widths above the default). <div class="node"> <a name="'Mode'"></a> <a name="g_t_0027Mode_0027"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Graphics-events">Graphics events</a>, Previous: <a rel="previous" accesskey="p" href="#Conventions">Conventions</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.5 ‘Mode’</h4> <p>One of the device callbacks is a function <code>mode</code>, documented in the header as <pre class="example"> * device_Mode is called whenever the graphics engine * starts drawing (mode=1) or stops drawing (mode=0) * GMode (in graphics.c) also says that * mode = 2 (graphical input on) exists. * The device is not required to do anything </pre> <p class="noindent">Since <code>mode = 2</code> has only recently been documented at device level. It could be used to change the graphics cursor, but devices currently do that in the <code>locator</code> callback. (In base graphics the mode is set for the duration of a <code>locator</code> call, but if <code>type != "n"</code> is switched back for each point whilst annotation is being done.) <p>Many devices do indeed do nothing on this call, but some screen devices ensure that drawing is flushed to the screen when called with <code>mode = 0</code>. It is tempting to use it for some sort of buffering, but note that ‘drawing’ is interpreted at quite a low level and a typical single figure will stop and start drawing many times. The buffering introduced in the <code>X11()</code> device makes use of <code>mode = 0</code> to indicate activity: it updates the screen after <em>ca</em> 100ms of inactivity. <p>This callback need not be supplied if it does nothing. <div class="node"> <a name="Graphics-events"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Specific-devices">Specific devices</a>, Previous: <a rel="previous" accesskey="p" href="#g_t_0027Mode_0027">'Mode'</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.6 Graphics events</h4> <p>Graphics devices may be designed to handle user interaction: not all are. <p>Users may use <code>grDevices::setGraphicsEventEnv</code> to set the <code>eventEnv</code> environment in the device driver to hold event handlers. When the user calls <code>grDevices::getGraphicsEvent</code>, R will take three steps. First, it sets the device driver member <code>gettingEvent</code> to <code>true</code> for each device with a non-<code>NULL</code> <code>eventEnv</code> entry, and calls <code>initEvent(dd, true)</code> if the callback is defined. It then enters an event loop. Each time through the loop R will process events once, then check whether any device has set the <code>result</code> member of <code>eventEnv</code> to a non-<code>NULL</code> value, and will save the first such value found to be returned. C functions <code>doMouseEvent</code> and <code>doKeybd</code> are provided to call the R event handlers <code>onMouseDown</code>, <code>onMouseMove</code>, <code>onMouseUp</code>, and <code>onKeybd</code> and set <code>eventEnv$result</code> during this step. Finally, <code>initEvent</code> is called again with <code>init=false</code> to inform the the devices that the loop is done, and the result is returned to the user. <div class="node"> <a name="Specific-devices"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Graphics-events">Graphics events</a>, Up: <a rel="up" accesskey="u" href="#Graphics-devices">Graphics devices</a> </div> <h4 class="subsection">6.1.7 Specific devices</h4> <p>Specific devices are mostly documented by comments in their sources, although for devices of many years' standing those comments can be in need of updating. This subsection is a repository of notes on design decisions. <ul class="menu"> <li><a accesskey="1" href="#X11_0028_0029">X11()</a> <li><a accesskey="2" href="#windows_0028_0029">windows()</a> </ul> <div class="node"> <a name="X11()"></a> <a name="X11_0028_0029"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#windows_0028_0029">windows()</a>, Previous: <a rel="previous" accesskey="p" href="#Specific-devices">Specific devices</a>, Up: <a rel="up" accesskey="u" href="#Specific-devices">Specific devices</a> </div> <h5 class="subsubsection">6.1.7.1 X11()</h5> <p>The <code>X11(type="Xlib")</code> device dates back to the mid 1990's and was written then in <code>Xlib</code>, the most basic X11 toolkit. It has since optionally made use of a few features from other toolkits: <code>libXt</code> is used to read X11 resources, and <code>libXmu</code> is used in the handling of clipboard selections. <p>Using basic <code>Xlib</code> code makes drawing fast, but is limiting. There is no support of translucent colours (that came in the <code>Xrender</code> toolkit of 2000) nor for rotated text (which R implements by rendering text to a bitmap and rotating the latter). <p>The hinting for the X11 window asks for backing store to be used, and some windows managers may use it to handle repaints, but it seems that most repainting is done by replaying the display list (and here the fast drawing is very helpful). <p>There are perennial problems with finding fonts. Many users fail to realize that fonts are a function of the X server and not of the machine that R is running on. After many difficulties, R tries first to find the nearest size match in the sizes provided for Adobe fonts in the standard 75dpi and 100dpi X11 font packages—even that will fail to work when users of near-100dpi screens have only the 75dpi set installed. The 75dpi set allows sizes down to 6 points on a 100dpi screen, but some users do try to use smaller sizes and even 6 and 8 point bitmapped fonts do not look good. <p>Introduction of UTF-8 locales has caused another wave of difficulties. X11 has very few genuine UTF-8 fonts, and produces composite fontsets for the <code>iso10646-1</code> encoding. Unfortunately these seem to have low coverage apart from a few monospaced fonts in a few sizes (which are not suitable for graph annotation), and where glyphs are missing what is plotted is often quite unsatisfactory. <p>The current approach is to make use of more modern toolkits, namely <code>cairo</code> for rendering and <code>Pango</code> for font management—because these are associated with <code>Gtk+2</code> they are widely available. Cairo supports translucent colours and alpha-blending (<em>via</em> <code>Xrender</code>), and anti-aliasing for the display of lines and text. Pango's font management is based on <code>fontconfig</code> and somewhat mysterious, but it seems mainly to use Type 1 and TrueType fonts on the machine running R and send grayscale bitmaps to cairo. <div class="node"> <a name="windows()"></a> <a name="windows_0028_0029"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#X11_0028_0029">X11()</a>, Up: <a rel="up" accesskey="u" href="#Specific-devices">Specific devices</a> </div> <h5 class="subsubsection">6.1.7.2 windows()</h5> <p>The <code>windows()</code> device is a family of devices: it supports plotting to Windows (enhanced) metafiles, <code>BMP</code>, <code>JPEG</code>, <code>PNG</code> and <code>TIFF</code> files as well as to Windows printers. <p>In most of these cases the primary plotting is to a bitmap: this is used for the (default) buffering of the screen device, which also enables the current plot to be saved to BMP, JPEG, PNG or TIFF (it is the internal bitmap which is copied to the file in the appropriate format). <p>The device units are pixels (logical ones on a metafile device). <p>The code was originally written by Guido Masarotto with extensive use of macros, which can make it hard to disentangle. <p>For a screen device, <code>xd->gawin</code> is the canvas of the screen, and <code>xd->bm</code> is the off-screen bitmap. So macro <code>DRAW</code> arranges to plot to <code>xd->bm</code>, and if buffering is off, also to <code>xd->gawin</code>. For all other device, <code>xd->gawin</code> is the canvas, a bitmap for the <code>jpeg()</code> and <code>png()</code> device, and an internal representation of a Windows metafile for the <code>win.metafile()</code> and <code>win.print</code> device. Since ‘plotting’ is done by Windows GDI calls to the appropriate canvas, its precise nature is hidden by the GDI system. <p>Buffering on the screen device is achieved by running a timer, which when it fires copies the internal bitmap to the screen. This is set to fire every 500ms (by default) and is reset to 100ms after plotting activity. <p>Repaint events are handled by copying the internal bitmap to the screen canvas (and then reinitializing the timer), unless there has been a resize. Resizes are handled by replaying the display list: this might not be necessary if a fixed canvas with scrollbars is being used, but that is the least popular of the three forms of resizing. <p>Text on the device has moved to ‘Unicode’ (UCS-2) in recent years. UTF-8 is requested (<code>hasTextUTF8 = TRUE</code>) for standard text, and converted to UCS-2 in the plotting functions in file <samp><span class="file">src/extra/graphapp/gdraw.c</span></samp>. However, GDI has no support for Unicode symbol fonts, and symbols are handled in Adobe Symbol encoding. <p>There is support for translucent colours (with alpha channel between 0 and 255) was introduced on the screen device and bitmap devices.<a rel="footnote" href="#fn-20" name="fnd-20"><sup>20</sup></a> This is done by drawing on a further internal bitmap, <code>xd->bm2</code>, in the opaque version of the colour then alpha-blending that bitmap to <code>xd->bm</code>. The alpha-blending routine is in a separate DLL, <samp><span class="file">msimg32.dll</span></samp>, which is loaded on first use. As small a rectangular region as reasonably possible is alpha-blended (this is rectangle <code>r</code> in the code), but things like mitre joins make estimation of a tight bounding box too much work for lines and polygonal boundaries. Translucent-coloured lines are not common, and the performance seems acceptable. <p>The support for a transparent background in <code>png()</code> predates full alpha-channel support in <code>libpng</code> (let alone in PNG viewers), so makes use of the limited transparency support in earlier versions of PNG. Where 24-bit colour is used, this is done by marking a single colour to be rendered as transparent. R chose ‘<samp><span class="samp">#fdfefd</span></samp>’, and uses this as the background colour (in <code>GA_NewPage</code> if the specified background colour is transparent (and all non-opaque background colours are treated as transparent). So this works by marking that colour in the PNG file, and viewers without transparency support see a slightly-off-white background, as if there were a near-white canvas. Where a palette is used in the PNG file (if less than 256 colours were used) then this colour is recorded with full transparency and the remaining colours as opaque. If 32-bit colour were available then we could add a full alpha channel, but this is dependent on the graphics hardware and undocumented properties of GDI. <div class="node"> <a name="Colours"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Base-graphics">Base graphics</a>, Previous: <a rel="previous" accesskey="p" href="#Graphics-devices">Graphics devices</a>, Up: <a rel="up" accesskey="u" href="#Graphics-Devices">Graphics Devices</a> </div> <h3 class="section">6.2 Colours</h3> <p>Devices receive colours as a <code>typedef</code> <code>rcolor</code> (an <code>unsigned int</code>) defined in the header <samp><span class="file">R_ext/GraphicsEngine.h</span></samp>). The 4 bytes are <em>R</em> ,<em>G</em>, <em>B</em> and <em>alpha</em> from least to most significant. So each of RGB has 256 levels of luminosity from 0 to 255. The alpha byte represents opacity, so value 255 is fully opaque and 0 fully transparent: many but not all devices handle semi-transparent colours. <p>Colors can be created in C via the macro <code>R_RGBA</code>, and a set of macros are defined in <samp><span class="file">R_ext/GraphicsDevice.h</span></samp> to extract the various components. <p>Colours in the base graphics system were originally adopted from S (and before that the GRZ library from Bell Labs), with the concept of a (variable-sized) palette of colours referenced by numbers ‘<samp><span class="samp">1...</span><var>N</var></samp>’ plus ‘<samp><span class="samp">0</span></samp>’ (the background colour of the current device). R introduced the idea of referring to colours by character strings, either in the forms ‘<samp><span class="samp">#RRGGBB</span></samp>’ or ‘<samp><span class="samp">#RRGGBBAA</span></samp>’ (representing the bytes in hex) as given by function <code>rgb()</code> or via names: the 657 known names are given in the character vector <code>colors</code> and in a table in file <samp><span class="file">colors.c</span></samp> in package <strong>grDevices</strong>. Note that semi-transparent colours are not ‘premultiplied’, so 50% transparent white is ‘<samp><span class="samp">#ffffff80</span></samp>’. <p>Integer or character <code>NA</code> colours are mapped internally to transparent white, as is the character string <code>"NA"</code>. <p>The handling of negative colour numbers was undefined (and inconsistent) prior to R 3.0.0, which made them an error. Colours greater than ‘<samp><var>N</var></samp>’ are wrapped around, so that for example with the default palette of size 8, colour ‘<samp><span class="samp">10</span></samp>’ is colour ‘<samp><span class="samp">2</span></samp>’ in the palette. <p>Integer colours have been used more widely than the base graphics sub-system, as they are supported by package <strong>grid</strong> and hence by <a href="http://CRAN.R-project.org/package=lattice"><strong>lattice</strong></a> and <a href="http://CRAN.R-project.org/package=ggplot2"><strong>ggplot2</strong></a>. (They are also used by package <a href="http://CRAN.R-project.org/package=rgl"><strong>rgl</strong></a>.) <strong>grid</strong> did re-define colour ‘<samp><span class="samp">0</span></samp>’ to be transparent white, but <a href="http://CRAN.R-project.org/package=rgl"><strong>rgl</strong></a> used <code>col2rgb</code> and hence the background colour of base graphics. <p>Note that positive integer colours refer to the current palette and colour ‘<samp><span class="samp">0</span></samp>’ to the current device (and a device is opened if needs be). These are mapped to type <code>rcolor</code> at the time of use: this matters when re-playing the display list, e.g. when a device is resized or <code>dev.copy</code> is used. The palette should be thought of as per-session: it is stored in package <strong>grDevices</strong>. <p>The convention is that devices use the colorspace ‘sRGB’. This is an industry standard: it is used by Web browsers and JPEGs from all but high-end digital cameras. The interpretation is a matter for graphics devices and for code that manipulates colours, but not for the graphics engine or subsystems. <p>R uses a painting model similar to PostScript and PDF. This means that where shapes (circles, rectangles and polygons) can both be filled and have a stroked border, the fill should be painted first and then the border (or otherwise only half the border will be visible). Where both the fill and the border are semi-transparent there is some room for interpretation of the intention. Most devices first paint the fill and then the border, alpha-blending at each step. However, PDF does some automatic grouping of objects, and <em>when the fill and the border have the same alpha</em>, they are painted onto the same layer and then alpha-blended in one step. (See p. 569 of the PDF Reference Sixth Edition, version 1.7. Unfortunately, although this is what the PDF standard says should happen, it is not correctly implemented by some viewers.) <p>The mapping from colour numbers to type <code>rcolor</code> is primarily done by function <code>RGBpar3</code>: this is exported from the R binary but linked to code in package <strong>grDevices</strong>. The first argument is a <code>SEXP</code> pointing to a character, integer or double vector, and the second is the <code>rcolor</code> value for colour <code>0</code> (or <code>"0"</code>). C entry point <code>RGBpar</code> is a wrapper that takes <code>0</code> to be transparent white: it is often used to set colour defaults for devices. The R-level wrapper is <code>col2rgb</code>. <p>There is also <code>R_GE_str2col</code> which takes a C string and converts to type <code>rcolor</code>: <code>"0'</code> is converted to transparent white. <p>There is a R-level conversion of colours to ‘<samp><span class="samp">##RRGGBBAA</span></samp>’ by <code>image.default(useRaster = TRUE)</code>. <p>The other color-conversion entry point in the API is <code>name2col</code> which takes a colour name (a C string) and returns a value of type <code>rcolor</code>. This handles <code>"NA"</code>, <code>"transparent"</code> and the 657 colours known to the R function <code>colors()</code>. <div class="node"> <a name="Base-graphics"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Grid-graphics">Grid graphics</a>, Previous: <a rel="previous" accesskey="p" href="#Colours">Colours</a>, Up: <a rel="up" accesskey="u" href="#Graphics-Devices">Graphics Devices</a> </div> <h3 class="section">6.3 Base graphics</h3> <p>The base graphics system was migrated to package <strong>graphics</strong> in R 3.0.0: it was previously implemented in files in <samp><span class="file">src/main</span></samp>. <p>For historical reasons it is largely implemented in two layers. Files <samp><span class="file">plot.c</span></samp>, <code>plot3d.c</code> and <code>par.c</code> contain the code for the around 30 <code>.External</code> calls that implement the basic graphics operations. This code then calls functions with names starting with <code>G</code> and declared in header <samp><span class="file">Rgraphics.h</span></samp> in file <samp><span class="file">graphics.c</span></samp>, which in turn call the graphics engine (whose functions almost all have names starting with <code>GE</code>). <p>A large part of the infrastructure of the base graphics subsystem are the graphics parameters (as set/read by <code>par()</code>). These are stored in a <code>GPar</code> structure declared in the private header <samp><span class="file">Graphics.h</span></samp>. This structure has two variables (<code>state</code> and <code>valid</code>) tracking the state of the base subsystem on the device, and many variables recording the graphics parameters and functions of them. <p>The base system state is contained in <code>baseSystemState</code> structure defined in <samp><span class="file">R_ext/GraphicsBase.h</span></samp>. This contains three <code>GPar</code> structures and a Boolean variable used to record if <code>plot.new()</code> (or <code>persp</code>) has been used successfully on the device. <p>The three copies of the <code>GPar</code> structure are used to store the current parameters (accessed via <code>gpptr</code>), the ‘device copy’ (accessed via <code>dpptr</code>) and space for a saved copy of the `device copy' parameters. The current parameters are, clearly, those currently in use and are copied from the ‘device copy’ whenever <code>plot.new()</code> is called (whether or not that advances to the next ‘page’). The saved copy keeps the state when the device was last completely cleared (e.g. when <code>plot.new()</code> was called with <code>par(new=TRUE)</code>), and is used to replay the display list. <p>The separation is not completely clean: the ‘device copy’ is altered if a plot with log scale(s) is set up via <code>plot.window()</code>. <p>There is yet another copy of most of the graphics parameters in <code>static</code> variables in <samp><span class="file">graphics.c</span></samp> which are used to preserve the current parameters across the processing of inline parameters in high-level graphics calls (handled by <code>ProcessInlinePars</code>). <p>Snapshots of the base subsystem record the ‘saved device copy’ of the <code>GPar</code> structure. <ul class="menu"> <li><a accesskey="1" href="#Arguments-and-parameters">Arguments and parameters</a> </ul> <div class="node"> <a name="Arguments-and-parameters"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Base-graphics">Base graphics</a>, Up: <a rel="up" accesskey="u" href="#Base-graphics">Base graphics</a> </div> <h4 class="subsection">6.3.1 Arguments and parameters</h4> <p>There is an unfortunate confusion between some of the graphical parameters (as set by <code>par</code>) and arguments to base graphic functions of the same name. This description may help set the record straight. <p>Most of the high-level plotting functions accept graphical parameters as additional arguments, which are then often passed to lower-level functions if not already named arguments (which is the main source of confusion). <p>Graphical parameter <code>bg</code> is the background colour of the plot. Argument <code>bg</code> refers to the fill colour for the filled symbols <code>21</code> to <code>25</code>. It is an argument to the function <code>plot.xy</code>, but normally passed by the default method of <code>points</code>, often from a <code>plot</code> method. <p>Graphics parameters <code>cex</code>, <code>col</code>, <code>lty</code>, <code>lwd</code> and <code>pch</code> also appear as arguments of <code>plot.xy</code> and so are often passed as arguments from higher-level plot functions such as <code>lines</code>, <code>points</code> and <code>plot</code> methods. They appear as arguments of <code>legend</code>, <code>col</code>, <code>lty</code> and <code>lwd</code> are arguments of <code>arrows</code> and <code>segments</code>. When used as arguments they can be vectors, recycled to control the various lines, points and segments. When set a graphical parameters they set the default rendering: in addition <code>par(cex=)</code> sets the overall character expansion which subsequent calls (as arguments or on-line graphical parameters) multiply. <p>The handling of missing values differs in the two classes of uses. Generally these are errors when used in <code>par</code> but cause the corresponding element of the plot to be omitted when used as an element of a vector argument. Originally the interpretation of arguments was mainly left to the device, but as from R 3.0.0 some of this is pre-empted in the graphics engine (but for example the handling of <code>lwd = 0</code> remains device-specific, with some interpreting it as a ‘thinnest possible’ line). <div class="node"> <a name="Grid-graphics"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Base-graphics">Base graphics</a>, Up: <a rel="up" accesskey="u" href="#Graphics-Devices">Graphics Devices</a> </div> <h3 class="section">6.4 Grid graphics</h3> <p>[At least pointers to documentation.] <div class="node"> <a name="GUI-consoles"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Tools">Tools</a>, Previous: <a rel="previous" accesskey="p" href="#Graphics-Devices">Graphics Devices</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">7 GUI consoles</h2> <p>The standard R front-ends are programs which run in a terminal, but there are several ways to provide a GUI console. <p>This can be done by a package which is loaded from terminal-based R and launches a console as part of its startup code or by the user running a specific function: package <a href="http://CRAN.R-project.org/package=Rcmdr"><strong>Rcmdr</strong></a> is a well-known example with a Tk-based GUI. <p>There used to be a Gtk-based console invoked by <samp><span class="command">R --gui=GNOME</span></samp>: this relied on special-casing in the front-end shell script to launch a different executable. There still is <samp><span class="command">R --gui=Tk</span></samp>, which starts terminal-based R and runs <code>tcltk::tkStartGui()</code> as part of the modified startup sequence. <p>However, the main way to run a GUI console is to launch a separate program which runs embedded R: this is done by <samp><span class="command">Rgui.exe</span></samp> on Windows and <samp><span class="command">R.app</span></samp> on OS X. The first is an integral part of R and the code for the console is currently in <samp><span class="file">R.dll</span></samp>. <ul class="menu"> <li><a accesskey="1" href="#R_002eapp">R.app</a> </ul> <div class="node"> <a name="R.app"></a> <a name="R_002eapp"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#GUI-consoles">GUI consoles</a>, Up: <a rel="up" accesskey="u" href="#GUI-consoles">GUI consoles</a> </div> <h3 class="section">7.1 R.app</h3> <p><samp><span class="command">R.app</span></samp> is a OS X application which provides a console. Its sources are a separate project<a rel="footnote" href="#fn-21" name="fnd-21"><sup>21</sup></a>, and its binaries link to an R installation which it runs as a dynamic library <samp><span class="file">libR.dylib</span></samp>. The standard <acronym>CRAN</acronym> distribution of R for OS X bundles the GUI and R itself, but installing the GUI is optional and either component can be updated separately. <p><samp><span class="command">R.app</span></samp> relies on <samp><span class="file">libR.dylib</span></samp> being in a specific place, and hence on R having been built and installed as a Mac OS X ‘framework’. Specifically, it uses <samp><span class="file">/Library/Frameworks/R.framework/R</span></samp>. This is a symbolic link, as frameworks can contain multiple versions of R. It eventually resolves to <samp><span class="file">/Library/Frameworks/R.framework/Versions/Current/Resources/lib/libR.dylib</span></samp>, which is (in the <acronym>CRAN</acronym> distribution) a ‘fat’ binary containing multiple sub-architectures. <p>OS X applications are directory trees: each <samp><span class="command">R.app</span></samp> contains a front-end written in Objective-C for one sub-architecture: in the standard distribution there are separate applications for 32- and 64-bit Intel architectures. <p>Originally the R sources contained quite a lot of code used only by the OS X GUI, but by R 3.0.0 this was been migrated to the <samp><span class="command">R.app</span></samp> sources. <p><samp><span class="command">R.app</span></samp> starts R as an embedded application with a command-line which includes <samp><span class="option">--gui=aqua</span></samp> (see below). It uses most of the interface pointers defined in the header <samp><span class="file">Rinterface.h</span></samp>, plus a private interface pointer in file <samp><span class="file">src/main/sysutils.c</span></samp>. It adds an environment it names <code>tools:RGUI</code> to the second position in the search path. This contains a number of utility functions used to support the menu items, for example <code>package.manager()</code>, plus functions <code>q()</code> and <code>quit()</code> which mask those in package <strong>base</strong>—the custom versions save the history in a way specific to <code>R.app</code>. <p>There is a <samp><span class="command">configure</span></samp> option <samp><span class="option">--with-aqua</span></samp> for R which customizes the way R is built: this is distinct from the <samp><span class="option">--enable-R-framework</span></samp> option which causes <samp><span class="command">make install</span></samp> to install R as the framework needed for use with <code>R.app</code>. (The option <samp><span class="option">--with-aqua</span></samp> is the default on OS X.) It sets the macro <code>HAVE_AQUA</code> in <samp><span class="file">config.h</span></samp> and the make variable <code>BUILD_AQUA_TRUE</code>. These have several consequences: <ul> <li>The <code>quartz()</code> device is built (other than as a stub) in package <strong>grDevices</strong>: this needs an Objective-C compiler. Then <code>quartz()</code> can be used with terminal R provided the latter has access to the OS X screen. <li>File <code>src/unix/aqua.c</code> is compiled. This now only contains an interface pointer for the <code>quartz()</code> device(s). <li><code>capabilities("aqua")</code> is set to <code>TRUE</code>. <li>The default path for a personal library directory is set as <samp><span class="file">~/Library/R/x.y/library</span></samp>. <!-- This is done in @file{etc/Renviron}. --> <li>There is support for setting a ‘busy’ indicator whilst waiting for <code>system()</code> to return. <li><code>R_ProcessEvents</code> is inhibited in a forked child from package <strong>parallel</strong>. The associated callback in <code>R.app</code> does things which should not be done in a child, and forking forks the whole process including the console. <li>There is support for starting the embedded R with the option <samp><span class="option">--gui=aqua</span></samp>: when this is done the global C variable <code>useaqua</code> is set to a true value. This has consequences: <ul> <li>The R session is asserted to be interactive <em>via</em> <code>R_Interactive</code>. <li><code>.Platform$GUI</code> is set to <code>"AQUA"</code>. That has consequences: <ul> <li>The environment variable <samp><span class="env">DISPLAY</span></samp> is set to ‘<samp><span class="samp">:0</span></samp>’ if not already set. <li><samp><span class="file">/usr/local/bin</span></samp> is appended to <samp><span class="env">PATH</span></samp> since that is where <samp><span class="command">gfortran</span></samp> is installed. <li>The default <acronym>HTML</acronym> browser is switched to the one in <samp><span class="command">R.app</span></samp>. <li>Various widgets are switched to the versions provided in <samp><span class="command">R.app</span></samp>: these include graphical menus, the data editor (but not the data viewer used by <code>View()</code>) and the workspace browser invoked by <code>browseEnv()</code>. <li>The <strong>grDevices</strong> package when loaded knows that it is being run under <samp><span class="command">R.app</span></samp> and so informs any <code>quartz</code> devices that a Quartz event loop is already running. </ul> <li>The use of the OS's <code>system</code> function (including by <code>system()</code> and <code>system2()</code>, and to launch editors and pagers) is replaced by a version in <code>R.app</code> (which by default just calls the OS's <code>system</code> with various signal handlers reset). </ul> <li>If either R was started by <samp><span class="option">--gui=aqua</span></samp> or R is running in a terminal which is not of type ‘<samp><span class="samp">dumb</span></samp>’, the standard output to files <samp><span class="file">stdout</span></samp> and <samp><span class="file">stderr</span></samp> is directed through the C function <code>Rstd_WriteConsoleEx</code>. This uses ANSI terminal escapes to render lines sent to <code>stderr</code> as bold on <code>stdout</code>. <li>For historical reasons the startup option <code>-psn</code> is allowed but ignored. (It seems that in 2003, ‘<samp><span class="samp">r27492</span></samp>’, this was added by Finder.) </ul> <div class="node"> <a name="Tools"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#R-coding-standards">R coding standards</a>, Previous: <a rel="previous" accesskey="p" href="#GUI-consoles">GUI consoles</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">8 Tools</h2> <p>The behavior of <samp><span class="command">R CMD check</span></samp> can be controlled through a variety of command line arguments and environment variables. <p>There is an internal <samp><span class="option">--install=</span><var>value</var></samp> command line argument not shown by <samp><span class="command">R CMD check --help</span></samp>, with possible values <dl> <dt><code>check:</code><var>file</var><dd>Assume that installation was already performed with stdout/stderr to <var>file</var>, the contents of which need to be checked (without repeating the installation). This is useful for checks applied by repository maintainers: it reduces the check time by the installation time given that the package has already been installed. In this case, one also needs to specify <em>where</em> the package was installed to using command line option <samp><span class="option">--library</span></samp>. <br><dt><code>fake</code><dd>Fake installation, and turn off the run-time tests. <br><dt><code>skip</code><dd>Skip installation, e.g., when testing recommended packages bundled with R. <br><dt><code>no</code><dd>The same as <samp><span class="option">--no-install</span></samp> : turns off installation and the tests which require the package to be installed. </dl> <p>The following environment variables can be used to customize the operation of <samp><span class="command">check</span></samp>: a convenient place to set these is the check environment file (default, <samp><span class="file">~/.R/check.Renviron</span></samp>). <dl> <dt><code>_R_CHECK_ALL_NON_ISO_C_</code><a name="index-g_t_005fR_005fCHECK_005fALL_005fNON_005fISO_005fC_005f-112"></a><dd>If true, do not ignore compiler (typically GCC) warnings about non ISO C code in <em>system</em> headers. Note that this may also show additional ISO C++ warnings. Default: false. <br><dt><code>_R_CHECK_FORCE_SUGGESTS_</code><a name="index-g_t_005fR_005fCHECK_005fFORCE_005fSUGGESTS_005f-113"></a><dd>If true, give an error if suggested packages are not available. Default: true (but false for CRAN submission checks). <br><dt><code>_R_CHECK_RD_CONTENTS_</code><a name="index-g_t_005fR_005fCHECK_005fRD_005fCONTENTS_005f-114"></a><dd>If true, check <samp><span class="file">Rd</span></samp> files for auto-generated content which needs editing, and missing argument documentation. Default: true. <br><dt><code>_R_CHECK_RD_LINE_WIDTHS_</code><a name="index-g_t_005fR_005fCHECK_005fRD_005fLINE_005fWIDTHS_005f-115"></a><dd>If true, check <samp><span class="file">Rd</span></samp> line widths in usage and examples sections. Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_RD_STYLE_</code><a name="index-g_t_005fR_005fCHECK_005fRD_005fSTYLE_005f-116"></a><dd>If true, check whether <samp><span class="file">Rd</span></samp> usage entries for S3 methods use the full function name rather than the appropriate <code>\method</code> markup. Default: true. <br><dt><code>_R_CHECK_RD_XREFS_</code><a name="index-g_t_005fR_005fCHECK_005fRD_005fXREFS_005f-117"></a><dd>If true, check the cross-references in <samp><span class="file">.Rd</span></samp> files. Default: true. <br><dt><code>_R_CHECK_SUBDIRS_NOCASE_</code><a name="index-g_t_005fR_005fCHECK_005fSUBDIRS_005fNOCASE_005f-118"></a><dd>If true, check the case of directories such as <samp><span class="file">R</span></samp> and <samp><span class="file">man</span></samp>. Default: true. <br><dt><code>_R_CHECK_SUBDIRS_STRICT_</code><a name="index-g_t_005fR_005fCHECK_005fSUBDIRS_005fSTRICT_005f-119"></a><dd>Initial setting for <samp><span class="option">--check-subdirs</span></samp>. Default: ‘<samp><span class="samp">default</span></samp>’ (which checks only tarballs, and checks in the <samp><span class="file">src</span></samp> only if there is no <samp><span class="file">configure</span></samp> file). <br><dt><code>_R_CHECK_USE_CODETOOLS_</code><a name="index-g_t_005fR_005fCHECK_005fUSE_005fCODETOOLS_005f-120"></a><dd>If true, make use of the <a href="http://CRAN.R-project.org/package=codetools"><strong>codetools</strong></a> package, which provides a detailed analysis of visibility of objects (but may give false positives). Default: true. <br><dt><code>_R_CHECK_USE_INSTALL_LOG_</code><a name="index-g_t_005fR_005fCHECK_005fUSE_005fINSTALL_005fLOG_005f-121"></a><dd>If true, record the output from installing a package as part of its check to a log file (<samp><span class="file">00install.out</span></samp> by default), even when running interactively. Default: true. <br><dt><code>_R_CHECK_VIGNETTES_NLINES_</code><a name="index-g_t_005fR_005fCHECK_005fVIGNETTES_005fNLINES_005f-122"></a><dd>Maximum number of lines to show of the bottom of the output when reporting errors in running vignettes. Default: 10. <br><dt><code>_R_CHECK_CODOC_S4_METHODS_</code><a name="index-g_t_005fR_005fCHECK_005fCODOC_005fS4_005fMETHODS_005f-123"></a><dd>Control whether <code>codoc()</code> testing is also performed on S4 methods. Default: true. <br><dt><code>_R_CHECK_DOT_INTERNAL_</code><a name="index-g_t_005fR_005fCHECK_005fDOT_005fINTERNAL_005f-124"></a><dd>Control whether the package code is scanned for <code>.Internal</code> calls, which should only be used by base (and occasionally by recommended) packages. Default: true. <br><dt><code>_R_CHECK_EXECUTABLES_</code><a name="index-g_t_005fR_005fCHECK_005fEXECUTABLES_005f-125"></a><dd>Control checking for executable (binary) files. Default: true. <br><dt><code>_R_CHECK_EXECUTABLES_EXCLUSIONS_</code><a name="index-g_t_005fR_005fCHECK_005fEXECUTABLES_005fEXCLUSIONS_005f-126"></a><dd>Control whether checking for executable (binary) files ignores files listed in the package's <samp><span class="file">BinaryFiles</span></samp> file. Default: true (but false for CRAN submission checks). However, most likely this package-level override mechanism will be removed eventually. <br><dt><code>_R_CHECK_PERMISSIONS_</code><a name="index-g_t_005fR_005fCHECK_005fPERMISSIONS_005f-127"></a><dd>Control whether permissions of files should be checked. Default: true iff <code>.Platform$OS.type == "unix"</code>. <br><dt><code>_R_CHECK_FF_CALLS_</code><a name="index-g_t_005fR_005fCHECK_005fFF_005fCALLS_005f-128"></a><dd>Allows turning off <code>checkFF()</code> testing. Legacy mostly. Default: true. <br><dt><code>_R_CHECK_LICENSE_</code><a name="index-g_t_005fR_005fCHECK_005fLICENSE_005f-129"></a><dd>Control whether/how license checks are performed. A possible value is ‘<samp><span class="samp">maybe</span></samp>’ (warn in case of problems, but not about standardizable non-standard license specs). Default: true. <br><dt><code>_R_CHECK_RD_EXAMPLES_T_AND_F_</code><a name="index-g_t_005fR_005fCHECK_005fRD_005fEXAMPLES_005fT_005fAND_005fF_005f-130"></a><dd>Control whether <code>check_T_and_F()</code> also looks for “bad” (global) ‘<samp><span class="samp">T</span></samp>’/‘<samp><span class="samp">F</span></samp>’ uses in examples. Off by default because this can result in false positives. <br><dt><code>_R_CHECK_RD_CHECKRD_MINLEVEL_</code><a name="index-g_t_005fR_005fCHECK_005fRD_005fCHECKRD_005fMINLEVEL_005f-131"></a><dd>Controls the minimum level for reporting warnings from <code>checkRd</code>. Default: -1. <br><dt><code>_R_CHECK_XREFS_REPOSITORIES_</code><a name="index-g_t_005fR_005fCHECK_005fXREFS_005fREPOSITORIES_005f-132"></a><dd>If set to a non-empty value, a space-separated list of repositories to use to determine known packages. Default: empty, when the CRAN, Omegahat and Bioconductor repositories known to R is used. <br><dt><code>_R_CHECK_SRC_MINUS_W_IMPLICIT_</code><a name="index-g_t_005fR_005fCHECK_005fSRC_005fMINUS_005fW_005fIMPLICIT_005f-133"></a><dd>Control whether installation output is checked for compilation warnings about implicit function declarations (as spotted by GCC with command line option <samp><span class="option">-Wimplicit-function-declaration</span></samp>, which is implied by <samp><span class="option">-Wall</span></samp>). Default: false. <br><dt><code>_R_CHECK_SRC_MINUS_W_UNUSED_</code><a name="index-g_t_005fR_005fCHECK_005fSRC_005fMINUS_005fW_005fUNUSED_005f-134"></a><dd>Control whether installation output is checked for compilation warnings about unused code constituents (as spotted by GCC with command line option <samp><span class="option">-Wunused</span></samp>, which is implied by <samp><span class="option">-Wall</span></samp>). Default: true. <br><dt><code>_R_CHECK_WALL_FORTRAN_</code><a name="index-g_t_005fR_005fCHECK_005fWALL_005fFORTRAN_005f-135"></a><dd>Control whether gfortran 4.0 or later <samp><span class="option">-Wall</span></samp> warnings are used in the analysis of installation output. Default: false, even though the warnings are justifiable. <br><dt><code>_R_CHECK_ASCII_CODE_</code><a name="index-g_t_005fR_005fCHECK_005fASCII_005fCODE_005f-136"></a><dd>If true, check R code for non-ascii characters. Default: true. <br><dt><code>_R_CHECK_ASCII_DATA_</code><a name="index-g_t_005fR_005fCHECK_005fASCII_005fDATA_005f-137"></a><dd>If true, check data for non-ascii characters. Default: true. <br><dt><code>_R_CHECK_COMPACT_DATA_</code><a name="index-g_t_005fR_005fCHECK_005fCOMPACT_005fDATA_005f-138"></a><dd>If true, check data for ascii and uncompressed saves, and also check if using <samp><span class="command">bzip2</span></samp> or <code>xz</code> compression would be significantly better. Default: true. <br><dt><code>_R_CHECK_SKIP_ARCH_</code><a name="index-g_t_005fR_005fCHECK_005fSKIP_005fARCH_005f-139"></a><dd>Comma-separated list of architectures that will be omitted from checking in a multi-arch setup. Default: none. <br><dt><code>_R_CHECK_SKIP_TESTS_ARCH_</code><a name="index-g_t_005fR_005fCHECK_005fSKIP_005fTESTS_005fARCH_005f-140"></a><dd>Comma-separated list of architectures that will be omitted from running tests in a multi-arch setup. Default: none. <br><dt><code>_R_CHECK_SKIP_EXAMPLES_ARCH_</code><a name="index-g_t_005fR_005fCHECK_005fSKIP_005fEXAMPLES_005fARCH_005f-141"></a><dd>Comma-separated list of architectures that will be omitted from running examples in a multi-arch setup. Default: none. <br><dt><code>_R_CHECK_VC_DIRS_</code><a name="index-g_t_005fR_005fCHECK_005fVC_005fDIRS_005f-142"></a><dd>Should the unpacked package directory be checked for version-control directories (<samp><span class="file">CVS</span></samp>, <samp><span class="file">.svn</span></samp> <small class="dots">...</small>)? Default: true for tarballs. <br><dt><code>_R_CHECK_PKG_SIZES_</code><a name="index-g_t_005fR_005fCHECK_005fPKG_005fSIZES_005f-143"></a><dd>Should <samp><span class="command">du</span></samp> be used to find the installed sizes of packages? <samp><span class="command">R CMD check</span></samp> does check for the availability of <samp><span class="command">du</span></samp>. but this option allows the check to be overruled if an unsuitable command is found (including one that does not respect the <samp><span class="option">-k</span></samp> flag to report in units of 1Kb, or reports in a different format – the GNU, OS X and Solaris <samp><span class="command">du</span></samp> commands have been tested). Default: true if <samp><span class="command">du</span></samp> is found. <br><dt><code>_R_CHECK_DOC_SIZES_</code><a name="index-g_t_005fR_005fCHECK_005fDOC_005fSIZES_005f-144"></a><dd>Should <samp><span class="command">qpdf</span></samp> be used to check the installed sizes of PDFs? Default: true if <samp><span class="command">qpdf</span></samp> is found. <br><dt><code>_R_CHECK_DOC_SIZES2_</code><a name="index-g_t_005fR_005fCHECK_005fDOC_005fSIZES2_005f-145"></a><dd>Should <samp><span class="command">gs</span></samp> be used to check the installed sizes of PDFs? This is slower than (and in addition to) the previous check, but does detect figures with excessive detail (often hidden by over-plotting) or bitmap figures with too high a resolution. Requires that <samp><span class="env">R_GSCMD</span></samp> is set to a valid program, or <samp><span class="command">gs</span></samp> (or on Windows, <samp><span class="command">gswin32.exe</span></samp> or <samp><span class="command">gswin64c.exe</span></samp>) is on the path. Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_</code><a name="index-g_t_005fR_005fCHECK_005fALWAYS_005fLOG_005fVIGNETTE_005fOUTPUT_005f-146"></a><dd>By default the output from running the R code in the vignettes is kept only if there is an error. Default: false. <br><dt><code>_R_CHECK_CLEAN_VIGN_TEST_</code><a name="index-g_t_005fR_005fCHECK_005fCLEAN_005fVIGN_005fTEST_005f-147"></a><dd>Should the <samp><span class="file">vign_test</span></samp> directory be removed if the test is successful? Default: true. <br><dt><code>_R_CHECK_REPLACING_IMPORTS_</code><a name="index-g_t_005fR_005fCHECK_005fREPLACING_005fIMPORTS_005f-148"></a><dd>Should warnings about replacing imports be reported? These sometimes come from auto-generated <samp><span class="file">NAMESPACE</span></samp> files in other packages, but most often from importing the whole of a namespace rather than using <code>importFrom</code>. Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_UNSAFE_CALLS_</code><a name="index-g_t_005fR_005fCHECK_005fUNSAFE_005fCALLS_005f-149"></a><dd>Check for calls that appear to tamper with (or allow tampering with) already loaded code not from the current package: such calls may well contravene CRAN policies. Default: true. <br><dt><code>_R_CHECK_TIMINGS_</code><a name="index-g_t_005fR_005fCHECK_005fTIMINGS_005f-150"></a><dd>Optionally report timings for installation, examples, tests and running/re-building vignettes as part of the check log. The format is ‘<samp><span class="samp">[as/bs]</span></samp>’ for the total CPU time (including child processes) ‘<samp><span class="samp">a</span></samp>’ and elapsed time ‘<samp><span class="samp">b</span></samp>’, except on Windows, when it is ‘<samp><span class="samp">[bs]</span></samp>’. In most cases timings are only given for ‘<samp><span class="samp">OK</span></samp>’ checks. Times with an elapsed component over 10 mins are reported in minutes (with abbreviation ‘<samp><span class="samp">m</span></samp>’). The value is the smallest numerical value in elapsed seconds that should be reported: non-numerical values indicate that no report is required, a value of ‘<samp><span class="samp">0</span></samp>’ that a report is always required. Default: <code>""</code>. (<code>10</code> for CRAN checks.) <br><dt><code>_R_CHECK_INSTALL_DEPENDS_</code><a name="index-g_t_005fR_005fCHECK_005fINSTALL_005fDEPENDS_005f-151"></a><dd>If set to a true value and a test installation is to be done, this is done with <code>.libPaths()</code> containing just a temporary library directory and <code>.Library</code>. The temporary library is populated by symbolic links<a rel="footnote" href="#fn-22" name="fnd-22"><sup>22</sup></a> to the installed copies of all the Depends/Imports/LinkingTo packages which are not in <code>.Library</code>. Default: false (but true for CRAN submission checks). <p>Note that this is actually implemented in <samp><span class="command">R CMD INSTALL</span></samp>, so it is available to those who first install recording to a log, then call <samp><span class="command">R CMD check</span></samp>. <br><dt><code>_R_CHECK_DEPENDS_ONLY_</code><a name="index-g_t_005fR_005fCHECK_005fDEPENDS_005fONLY_005f-152"></a><dt><code>_R_CHECK_SUGGESTS_ONLY_</code><a name="index-g_t_005fR_005fCHECK_005fSUGGESTS_005fONLY_005f-153"></a><dd>If set to a true value, running examples, tests and vignettes is done with <code>.libPaths()</code> containing just a temporary library directory and <code>.Library</code>. The temporary library is populated by symbolic links<a rel="footnote" href="#fn-23" name="fnd-23"><sup>23</sup></a> to the installed copies of all the Depends/Imports/LinkingTo and (for the second only) Suggests packages which are not in <code>.Library</code>. Default: false (but true for CRAN checks). <br><dt><code>_R_CHECK_NO_RECOMMENDED_</code><a name="index-g_t_005fR_005fCHECK_005fNO_005fRECOMMENDED_005f-154"></a><dd>If set to a true value, augment the previous checks to make recommended packages unavailable unless declared. Default: false (but true for CRAN submission checks). <p>This may give false positives on code which uses <code>grDevices::densCols</code> and <code>stats:::asSparse</code> as these invoke <a href="http://CRAN.R-project.org/package=KernSmooth"><strong>KernSmooth</strong></a> and <a href="http://CRAN.R-project.org/package=Matrix"><strong>Matrix</strong></a> respectively. <br><dt><code>_R_CHECK_CODETOOLS_PROFILE_</code><a name="index-g_t_005fR_005fCHECK_005fCODETOOLS_005fPROFILE_005f-155"></a><dd>A string with comma-separated <var>name</var><code>=</code><var>value</var> pairs (with <var>value</var> a logical constant) giving additional arguments for the <a href="http://CRAN.R-project.org/package=codetools"><strong>codetools</strong></a> functions used for analyzing package code. E.g., use <code>_R_CHECK_CODETOOLS_PROFILE_="suppressLocalUnused=FALSE"</code> to turn off suppressing warnings about unused local variables. Default: no additional arguments, corresponding to using <code>skipWith = TRUE</code>, <code>suppressPartialMatchArgs = FALSE</code> and <code>suppressLocalUnused = TRUE</code>. <br><dt><code>_R_CHECK_CRAN_INCOMING_</code><a name="index-g_t_005fR_005fCHECK_005fCRAN_005fINCOMING_005f-156"></a><dd>Check whether package is suitable for publication on CRAN. Default: false, except for CRAN submission checks. <br><dt><code>_R_CHECK_XREFS_USE_ALIASES_FROM_CRAN_</code><a name="index-g_t_005fR_005fCHECK_005fXREFS_005fUSE_005fALIASES_005fFROM_005fCRAN_005f-157"></a><dd>When checking anchored Rd xrefs, use Rd aliases from the CRAN package web areas in addition to those in the packages installed locally. Default: false. <br><dt><code>_R_SHLIB_BUILD_OBJECTS_SYMBOL_TABLES_</code><a name="index-g_t_005fR_005fSHLIB_005fBUILD_005fOBJECTS_005fSYMBOL_005fTABLES_005f-158"></a><dd>Make the checks of compiled code more accurate by recording the symbol tables for objects (<samp><span class="file">.o</span></samp> files) at installation in a file <samp><span class="file">symbols.rds</span></samp>. (Only currently supported on Linux, Solaris, OS X, Windows and FreeBSD.) Default: true. <br><dt><code>_R_CHECK_CODE_ASSIGN_TO_GLOBALENV_</code><a name="index-g_t_005fR_005fCHECK_005fCODE_005fASSIGN_005fTO_005fGLOBALENV_005f-159"></a><dd>Should the package code be checked for assignments to the global environment? Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_CODE_ATTACH_</code><a name="index-g_t_005fR_005fCHECK_005fCODE_005fATTACH_005f-160"></a><dd>Should the package code be checked for calls to <code>attach()</code>? Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_CODE_DATA_INTO_GLOBALENV_</code><a name="index-g_t_005fR_005fCHECK_005fCODE_005fDATA_005fINTO_005fGLOBALENV_005f-161"></a><dd>Should the package code be checked for calls to <code>data()</code> which load into the global environment? Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_DOT_FIRSTLIB_</code><a name="index-g_t_005fR_005fCHECK_005fDOT_005fFIRSTLIB_005f-162"></a><dd>Should the package code be checked for the presence of the obsolete function <code>.First.lib()</code>? Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_DEPRECATED_DEFUNCT_</code><a name="index-g_t_005fR_005fCHECK_005fDEPRECATED_005fDEFUNCT_005f-163"></a><dd>Should the package code be checked for the presence of recently deprecated or defunct functions (including completely removed functions). Default: false (but true for CRAN submission checks). <br><dt><code>_R_CHECK_TOPLEVEL_FILES_</code><a name="index-g_t_005fR_005fCHECK_005fTOPLEVEL_005fFILES_005f-164"></a><dd>Report on top-level files in the package sources that are not described in ‘Writing R Extensions’ nor are commonly understood (like <samp><span class="file">ChangeLog</span></samp>). Variations on standard names (e.g. <samp><span class="file">COPYRIGHT</span></samp>) are also reported. Default: false (but true for CRAN submission checks). </dl> <p>CRAN's submission checks use something like <pre class="example"> _R_CHECK_CRAN_INCOMING_=TRUE _R_CHECK_VC_DIRS_=TRUE _R_CHECK_TIMINGS_=10 _R_CHECK_INSTALL_DEPENDS_=TRUE _R_CHECK_SUGGESTS_ONLY_=TRUE _R_CHECK_NO_RECOMMENDED_=TRUE _R_CHECK_EXECUTABLES_EXCLUSIONS_=FALSE _R_CHECK_DOC_SIZES2_=TRUE _R_CHECK_CODE_ASSIGN_TO_GLOBALENV_=TRUE _R_CHECK_CODE_ATTACH_=TRUE _R_CHECK_CODE_DATA_INTO_GLOBALENV_=TRUE _R_CHECK_DOT_FIRSTLIB_=TRUE _R_CHECK_DEPRECATED_DEFUNCT_=TRUE _R_CHECK_REPLACING_IMPORTS_=TRUE _R_CHECK_TOPLEVEL_FILES_=TRUE </pre> <p class="noindent">These are turned on by <samp><span class="command">R CMD check --as-cran</span></samp>: the incoming checks also use <pre class="example"> _R_CHECK_FORCE_SUGGESTS_=FALSE </pre> <p class="noindent">since some packages do suggest other packages not available on CRAN or other commonly-used repositories. <div class="node"> <a name="R-coding-standards"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Testing-R-code">Testing R code</a>, Previous: <a rel="previous" accesskey="p" href="#Tools">Tools</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">9 R coding standards</h2> <p><a name="index-coding-standards-165"></a>R is meant to run on a wide variety of platforms, including Linux and most variants of Unix as well as Windows and OS X. Therefore, when extending R by either adding to the R base distribution or by providing an add-on package, one should not rely on features specific to only a few supported platforms, if this can be avoided. In particular, although most R developers use <acronym>GNU</acronym> tools, they should not employ the <acronym>GNU</acronym> extensions to standard tools. Whereas some other software packages explicitly rely on e.g. <acronym>GNU</acronym> make or the <acronym>GNU</acronym> C++ compiler, R does not. Nevertheless, R is a <acronym>GNU</acronym> project, and the spirit of the <cite><acronym>GNU</acronym> Coding Standards</cite> should be followed if possible. <p>The following tools can “safely be assumed” for R extensions. <ul> <li>An ISO C99 C compiler. Note that extensions such as <acronym>POSIX</acronym> 1003.1 must be tested for, typically using Autoconf unless you are sure they are supported on all mainstream R platforms (including Windows and OS X). <li>A FORTRAN 77 compiler (but not Fortran 9x, although it is nowadays widely available). <li>A simple <samp><span class="command">make</span></samp>, considering the features of <samp><span class="command">make</span></samp> in 4.2 <acronym>BSD</acronym> systems as a baseline. <a name="index-make-166"></a> <acronym>GNU</acronym> or other extensions, including pattern rules using ‘<samp><span class="samp">%</span></samp>’, the automatic variable ‘<samp><span class="samp">$^</span></samp>’, the ‘<samp><span class="samp">+=</span></samp>’ syntax to append to the value of a variable, the (“safe”) inclusion of makefiles with no error, conditional execution, and many more, must not be used (see Chapter “Features” in the <cite><acronym>GNU</acronym> Make Manual</cite> for more information). On the other hand, building R in a separate directory (not containing the sources) should work provided that <samp><span class="command">make</span></samp> supports the <code>VPATH</code> mechanism. <p>Windows-specific makefiles can assume <acronym>GNU</acronym> <samp><span class="command">make</span></samp> 3.79 or later, as no other <samp><span class="command">make</span></samp> is viable on that platform. <li>A Bourne shell and the “traditional” Unix programming tools, including <samp><span class="command">grep</span></samp>, <samp><span class="command">sed</span></samp>, and <samp><span class="command">awk</span></samp>. <p>There are <acronym>POSIX</acronym> standards for these tools, but these may not be fully supported. Baseline features could be determined from a book such as <cite>The UNIX Programming Environment</cite> by Brian W. Kernighan & Rob Pike. Note in particular that ‘<samp><span class="samp">|</span></samp>’ in a regexp is an extended regexp, and is not supported by all versions of <samp><span class="command">grep</span></samp> or <samp><span class="command">sed</span></samp>. The Open Group Base Specifications, Issue 7, which are technically identical to IEEE Std 1003.1 (POSIX), 2008, are available at <a href="http://pubs.opengroup.org/onlinepubs/9699919799/mindex.html">http://pubs.opengroup.org/onlinepubs/9699919799/mindex.html</a>. </ul> <p>Under Windows, most users will not have these tools installed, and you should not require their presence for the operation of your package. However, users who install your package from source will have them, as they can be assumed to have followed the instructions in “the Windows toolset” appendix of the “R Installation and Administration” manual to obtain them. Redirection cannot be assumed to be available via <samp><span class="command">system</span></samp> as this does not use a standard shell (let alone a Bourne shell). <p class="noindent">In addition, the following tools are needed for certain tasks. <ul> <li>Perl version 5 is only needed for a few uncommonly-used tools: <samp><span class="command">make install-info</span></samp> needs Perl installed if there is no command <samp><span class="command">install-info</span></samp> on the system, and for the maintainer-only script <samp><span class="file">tools/help2man.pl</span></samp>. <a name="index-Perl-167"></a> <li>Makeinfo version 4.7 or later is needed to build the Info files for the R manuals written in the <acronym>GNU</acronym> Texinfo system. <a name="index-makeinfo-168"></a></ul> <p>It is also important that code is written in a way that allows others to understand it. This is particularly helpful for fixing problems, and includes using self-descriptive variable names, commenting the code, and also formatting it properly. The R Core Team recommends to use a basic indentation of 4 for R and C (and most likely also Perl) code, and 2 for documentation in Rd format. Emacs (21 or later) users can implement this indentation style by putting the following in one of their startup files, and using customization to set the <code>c-default-style</code> to <code>"bsd"</code> and <code>c-basic-offset</code> to <code>4</code>.) <a name="index-emacs-169"></a> <pre class="smallexample"> ;;; ESS (add-hook 'ess-mode-hook (lambda () (ess-set-style 'C++ 'quiet) ;; Because ;; DEF GNU BSD K&R C++ ;; ess-indent-level 2 2 8 5 4 ;; ess-continued-statement-offset 2 2 8 5 4 ;; ess-brace-offset 0 0 -8 -5 -4 ;; ess-arg-function-offset 2 4 0 0 0 ;; ess-expression-offset 4 2 8 5 4 ;; ess-else-offset 0 0 0 0 0 ;; ess-close-brace-offset 0 0 0 0 0 (add-hook 'local-write-file-hooks (lambda () (ess-nuke-trailing-whitespace))))) (setq ess-nuke-trailing-whitespace-p 'ask) ;; or even ;; (setq ess-nuke-trailing-whitespace-p t) ;;; Perl (add-hook 'perl-mode-hook (lambda () (setq perl-indent-level 4))) </pre> <p class="noindent">(The ‘GNU’ styles for Emacs' C and R modes use a basic indentation of 2, which has been determined not to display the structure clearly enough when using narrow fonts.) <div class="node"> <a name="Testing-R-code"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Use-of-TeX-dialects">Use of TeX dialects</a>, Previous: <a rel="previous" accesskey="p" href="#R-coding-standards">R coding standards</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">10 Testing R code</h2> <p>When you (as R developer) add new functions to the R base (all the packages distributed with R), be careful to check if <kbd>make test-Specific</kbd> or particularly, <kbd>cd tests; make no-segfault.Rout</kbd> still works (without interactive user intervention, and on a standalone computer). If the new function, for example, accesses the Internet, or requires <acronym>GUI</acronym> interaction, please add its name to the “stop list” in <samp><span class="file">tests/no-segfault.Rin</span></samp>. <p>[To be revised: use <samp><span class="command">make check-devel</span></samp>, check the write barrier if you change internal structures.] <div class="node"> <a name="Use-of-TeX-dialects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Current-and-future-directions">Current and future directions</a>, Previous: <a rel="previous" accesskey="p" href="#Testing-R-code">Testing R code</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">11 Use of TeX dialects</h2> <p>Various dialects of TeX and used for different purposes in R. The policy is that manuals be written in ‘<samp><span class="samp">texinfo</span></samp>’, and for convenience the main and Windows FAQs are also. This has the advantage that is is easy to produce <acronym>HTML</acronym> and plain text versions as well as typeset manuals. <p>LaTeX is not used directly, but rather as an intermediate format for typeset help documents and for vignettes. <p>Care needs to be taken about the assumptions made about the R user's system: it may not have either ‘<samp><span class="samp">texinfo</span></samp>’ or a TeX system installed. We have attempted to abstract out the cross-platform differences, and almost all the setting of typeset documents is done by <code>tools::texi2dvi</code>. This is used for offline printing of help documents, preparing vignettes and for package manuals via <samp><span class="command">R CMD Rd2pdf</span></samp>. It is not currently used for the R manuals created in directory <samp><span class="file">doc/manual</span></samp>. <p><code>tools::texi2dvi</code> makes use of a system command <samp><span class="command">texi2dvi</span></samp> where available. On a Unix-alike this is usually part of ‘<samp><span class="samp">texinfo</span></samp>’, whereas on Windows if it exists at all it would be an executable, part of MiKTeX. If none is available, the R code runs a sequence of <samp><span class="command">(pdf)latex</span></samp>, <samp><span class="command">bibtex</span></samp> and <samp><span class="command">makeindex</span></samp> commands. <p>This process has been rather vulnerable to the versions of the external software used: particular issues have been <samp><span class="command">texi2dvi</span></samp> and <samp><span class="file">texinfo.tex</span></samp> updates, mismatches between the two<a rel="footnote" href="#fn-24" name="fnd-24"><sup>24</sup></a>, versions of the LaTeX package ‘<samp><span class="samp">hyperref</span></samp>’ and quirks in index production. The licenses used for LaTeX and latterly ‘<samp><span class="samp">texinfo</span></samp>’ prohibit us from including ‘known good’ versions in the R distribution. <p>On a Unix-alike <samp><span class="command">configure</span></samp> looks for the executables for TeX and friends and if found records the absolute paths in the system <samp><span class="file">Renviron</span></samp> file. This used to record ‘<samp><span class="samp">false</span></samp>’ if no command was found, but it nowadays records the name for looking up on the path at run time. The latter can be important for binary distributions: one does not want to be tied to, for example, TeXLive 2007. <div class="node"> <a name="Current-and-future-directions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Function-and-variable-index">Function and variable index</a>, Previous: <a rel="previous" accesskey="p" href="#Use-of-TeX-dialects">Use of TeX dialects</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">12 Current and future directions</h2> <p>This chapter is for notes about possible in-progress and future changes to R: there is no commitment to release such changes, let alone to a timescale. <ul class="menu"> <li><a accesskey="1" href="#Long-vectors">Long vectors</a> <li><a accesskey="2" href="#g_t64_002dbit-types">64-bit types</a> <li><a accesskey="3" href="#Large-matrices">Large matrices</a> </ul> <div class="node"> <a name="Long-vectors"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#g_t64_002dbit-types">64-bit types</a>, Previous: <a rel="previous" accesskey="p" href="#Current-and-future-directions">Current and future directions</a>, Up: <a rel="up" accesskey="u" href="#Current-and-future-directions">Current and future directions</a> </div> <h3 class="section">12.1 Long vectors</h3> <p>Vectors in R 2.x.y were limited to a length of 2^31 - 1 elements (about 2 billion), as the length is stored in the <code>SEXPREC</code> as a C <code>int</code>, and that type is used extensively to record lengths and element numbers, including in packages. <p>Note that longer vectors are effectively impossible under 32-bit platforms because of their address limit, so this section applies only on 64-bit platforms. The internals are unchanged on a 32-bit build of R. <p>A single object with 2^31 or more elements will take up at least 8GB of memory if integer or logical and 16GB if numeric or character, so routine use of such objects is still some way off. <p>There is now some support for long vectors. This applies to raw, logical, integer, numeric and character vectors, and lists and expression vectors. (Elements of character vectors (<code>CHARSXP</code>s) remain limited to 2^31 - 1 bytes.) Some considerations: <ul> <li>This has been implemented by recording the length (and true length) as <code>-1</code> and recording the actual length as a 64-bit field at the beginning of the header. Because a fair amount of code in R uses a signed type for the length, the ‘long length’ is recorded using the signed C99 type <code>ptrdiff_t</code>, which is typedef-ed to <code>R_xlen_t</code>. <li>These can in theory have 63-bit lengths, but note that current 64-bit OSes do not even theoretically offer 64-bit address spaces and there is currently a 52-bit limit (which exceeds the theoretical limit of current OSes and ensures that such lengths can be stored exactly in doubles). <li>The serialization format has been changed to accommodate longer lengths, but vectors of lengths up to 2^31-1 are stored in the same way as before. Longer vectors have their length field set to <code>-1</code> and followed by two 32-bit fields giving the upper and lower 32-bits of the actual length. There is currently a sanity check which limits lengths to 2^48 on unserialization. <li>The type <code>R_xlen_t</code> is made available to packages in C header <samp><span class="file">Rinternals.h</span></samp>: this should be fine in C code since C99 is required. People do try to use R internals in C++, but C++98 compilers are not required to support these types (and there are currently no C++11 compilers). <li>Indexing can be done via the use of doubles. The internal indexing code used to work with positive integer indices (and negative, logical and matrix indices were all converted to positive integers): it now works with either <code>INTSXP</code> or <code>REALSXP</code> indices. <li>R function <code>length</code> was documented to currently return an integer, possibly <code>NA</code>. A lot of code has been written that assumes that, and even code which calls <code>as.integer(length(x))</code> before passing to <code>.C</code>/<code>.Fortran</code> rarely checks for an <code>NA</code> result. <p>There is a new function <code>xlength</code> which works for long vectors and returns a double value if the length exceeds 2^31-1. At present <code>length</code> returns <code>NA</code> for long vectors, but it may be safer to make that an error. </ul> <div class="node"> <a name="64-bit-types"></a> <a name="g_t64_002dbit-types"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Large-matrices">Large matrices</a>, Previous: <a rel="previous" accesskey="p" href="#Long-vectors">Long vectors</a>, Up: <a rel="up" accesskey="u" href="#Current-and-future-directions">Current and future directions</a> </div> <h3 class="section">12.2 64-bit types</h3> <p>There is also some desire to be able to store larger integers in R, although the possibility of storing these as <code>double</code> is often overlooked (and e.g. file pointers as returned by <code>seek</code> are already stored as <code>double</code>). <p>Different routes have been proposed: <ul> <li>Add a new type to R and use that for lengths and indices—most likely this would be a 64-bit signed type, say <code>longint</code>. R's usual implicit coercion rules would ensure that supplying an <code>integer</code> vector for indexing or <code>length<-</code> would work. <li>A more radical alternative is to change the existing <code>integer</code> type to be 64-bit on 64-bit platforms (which was the approach taken by S-PLUS for DEC/Compaq Alpha systems). Or even on all platforms. <li>Allow either <code>integer</code> or <code>double</code> values for lengths and indices, and return <code>double</code> only when necessary. </ul> <p>The third has the advantages of minimal disruption to existing code and not increasing memory requirements. In the first and third scenarios both R's own code and user code would have to be adapted for lengths that were not of type <code>integer</code>, and in the third code branches for long vectors would be tested rarely. <p>Most users of the <code>.C</code> and <code>.Fortran</code> interfaces use <code>as.integer</code> for lengths and element numbers, but a few omit these in the knowledge that these were of type <code>integer</code>. It may be reasonable to assume that these are never intended to be used with long vectors. <p>The remaining interfaces will need to cope with the changed <code>VECTOR_SEXPREC</code> types. It seems likely that in most cases lengths are accessed by the <code>length</code> and <code>LENGTH</code> functions<a rel="footnote" href="#fn-25" name="fnd-25"><sup>25</sup></a> The current approach is to keep these returning 32-bit lengths and introduce ‘long’ versions <code>xlength</code> and <code>XLENGTH</code> which return <code>R_xlen_t</code> values. <p>See also <a href="http://www.cs.uiowa.edu/~luke/talks/useR10.pdf">http://www.cs.uiowa.edu/~luke/talks/useR10.pdf</a>. <div class="node"> <a name="Large-matrices"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#g_t64_002dbit-types">64-bit types</a>, Up: <a rel="up" accesskey="u" href="#Current-and-future-directions">Current and future directions</a> </div> <h3 class="section">12.3 Large matrices</h3> <p>Matrices are stored as vectors and so were also limited to 2^31-1 elements. Now longer vectors are allowed, matrices with more elements are supported provided that each of the dimensions is no more than 2^31-1. However, not all applications can be supported. <p>The main problem is linear algebra, on done by FORTRAN code compiled with 32-bit <code>INTEGER</code>. Although not guaranteed, it seems that all the compilers currently used with R on a 64-bit platform allow matrices each of whose dimensions is less than 2^31 but with more than 2^31 elements, and index them correctly, and a substantial part of the support software (such as <acronym>BLAS</acronym> and <acronym>LAPACK</acronym>) also work. <p>There are exceptions: for example some complex <acronym>LAPACK</acronym>) auxiliary routines do use a single <code>INTEGER</code> index and hence overflow silently and segfault or give incorrect results. One example is <code>svd()</code> on a complex matrix. <p>Since this is implementation-dependent, it is possible that optimized <acronym>BLAS</acronym> and <acronym>LAPACK</acronym> may have further restrictions, although none have yet been encountered. For matrix algebra on large matrices one almost certainly wants a machine with a lot of RAM (100s of gigabytes), many cores and a multi-threaded <acronym>BLAS</acronym>. <div class="node"> <a name="Function-and-variable-index"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Concept-index">Concept index</a>, Previous: <a rel="previous" accesskey="p" href="#Current-and-future-directions">Current and future directions</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="unnumbered">Function and variable index</h2> <ul class="index-vr" compact> <li><a href="#index-g_t_002eDevice-94"><code>.Device</code></a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-g_t_002eDevices-95"><code>.Devices</code></a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-g_t_002eInternal-109"><code>.Internal</code></a>: <a href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a></li> <li><a href="#index-g_t_002eLast_002evalue-97"><code>.Last.value</code></a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-g_t_002eOptions-96"><code>.Options</code></a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-g_t_002ePrimitive-110"><code>.Primitive</code></a>: <a href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a></li> <li><a href="#index-g_t_002eRandom_002eseed-102"><code>.Random.seed</code></a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-g_t_002eSavedPlots-104"><code>.SavedPlots</code></a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-g_t_002eTraceback-98"><code>.Traceback</code></a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fALL_005fNON_005fISO_005fC_005f-112"><code>_R_CHECK_ALL_NON_ISO_C_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fALWAYS_005fLOG_005fVIGNETTE_005fOUTPUT_005f-146"><code>_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fASCII_005fCODE_005f-136"><code>_R_CHECK_ASCII_CODE_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fASCII_005fDATA_005f-137"><code>_R_CHECK_ASCII_DATA_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCLEAN_005fVIGN_005fTEST_005f-147"><code>_R_CHECK_CLEAN_VIGN_TEST_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCODE_005fASSIGN_005fTO_005fGLOBALENV_005f-159"><code>_R_CHECK_CODE_ASSIGN_TO_GLOBALENV_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCODE_005fATTACH_005f-160"><code>_R_CHECK_CODE_ATTACH_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCODE_005fDATA_005fINTO_005fGLOBALENV_005f-161"><code>_R_CHECK_CODE_DATA_INTO_GLOBALENV_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCODETOOLS_005fPROFILE_005f-155"><code>_R_CHECK_CODETOOLS_PROFILE_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCODOC_005fS4_005fMETHODS_005f-123"><code>_R_CHECK_CODOC_S4_METHODS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCOMPACT_005fDATA_005f-138"><code>_R_CHECK_COMPACT_DATA_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fCRAN_005fINCOMING_005f-156"><code>_R_CHECK_CRAN_INCOMING_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fDEPENDS_005fONLY_005f-152"><code>_R_CHECK_DEPENDS_ONLY_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fDEPRECATED_005fDEFUNCT_005f-163"><code>_R_CHECK_DEPRECATED_DEFUNCT_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fDOC_005fSIZES2_005f-145"><code>_R_CHECK_DOC_SIZES2_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fDOC_005fSIZES_005f-144"><code>_R_CHECK_DOC_SIZES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fDOT_005fFIRSTLIB_005f-162"><code>_R_CHECK_DOT_FIRSTLIB_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fDOT_005fINTERNAL_005f-124"><code>_R_CHECK_DOT_INTERNAL_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fEXECUTABLES_005f-125"><code>_R_CHECK_EXECUTABLES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fEXECUTABLES_005fEXCLUSIONS_005f-126"><code>_R_CHECK_EXECUTABLES_EXCLUSIONS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fFF_005fCALLS_005f-128"><code>_R_CHECK_FF_CALLS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fFORCE_005fSUGGESTS_005f-113"><code>_R_CHECK_FORCE_SUGGESTS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fINSTALL_005fDEPENDS_005f-151"><code>_R_CHECK_INSTALL_DEPENDS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fLICENSE_005f-129"><code>_R_CHECK_LICENSE_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fNO_005fRECOMMENDED_005f-154"><code>_R_CHECK_NO_RECOMMENDED_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fPERMISSIONS_005f-127"><code>_R_CHECK_PERMISSIONS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fPKG_005fSIZES_005f-143"><code>_R_CHECK_PKG_SIZES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fRD_005fCHECKRD_005fMINLEVEL_005f-131"><code>_R_CHECK_RD_CHECKRD_MINLEVEL_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fRD_005fCONTENTS_005f-114"><code>_R_CHECK_RD_CONTENTS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fRD_005fEXAMPLES_005fT_005fAND_005fF_005f-130"><code>_R_CHECK_RD_EXAMPLES_T_AND_F_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fRD_005fLINE_005fWIDTHS_005f-115"><code>_R_CHECK_RD_LINE_WIDTHS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fRD_005fSTYLE_005f-116"><code>_R_CHECK_RD_STYLE_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fRD_005fXREFS_005f-117"><code>_R_CHECK_RD_XREFS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fREPLACING_005fIMPORTS_005f-148"><code>_R_CHECK_REPLACING_IMPORTS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSKIP_005fARCH_005f-139"><code>_R_CHECK_SKIP_ARCH_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSKIP_005fEXAMPLES_005fARCH_005f-141"><code>_R_CHECK_SKIP_EXAMPLES_ARCH_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSKIP_005fTESTS_005fARCH_005f-140"><code>_R_CHECK_SKIP_TESTS_ARCH_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSRC_005fMINUS_005fW_005fIMPLICIT_005f-133"><code>_R_CHECK_SRC_MINUS_W_IMPLICIT_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSRC_005fMINUS_005fW_005fUNUSED_005f-134"><code>_R_CHECK_SRC_MINUS_W_UNUSED_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSUBDIRS_005fNOCASE_005f-118"><code>_R_CHECK_SUBDIRS_NOCASE_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSUBDIRS_005fSTRICT_005f-119"><code>_R_CHECK_SUBDIRS_STRICT_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fSUGGESTS_005fONLY_005f-153"><code>_R_CHECK_SUGGESTS_ONLY_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fTIMINGS_005f-150"><code>_R_CHECK_TIMINGS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fTOPLEVEL_005fFILES_005f-164"><code>_R_CHECK_TOPLEVEL_FILES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fUNSAFE_005fCALLS_005f-149"><code>_R_CHECK_UNSAFE_CALLS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fUSE_005fCODETOOLS_005f-120"><code>_R_CHECK_USE_CODETOOLS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fUSE_005fINSTALL_005fLOG_005f-121"><code>_R_CHECK_USE_INSTALL_LOG_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fVC_005fDIRS_005f-142"><code>_R_CHECK_VC_DIRS_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fVIGNETTES_005fNLINES_005f-122"><code>_R_CHECK_VIGNETTES_NLINES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fWALL_005fFORTRAN_005f-135"><code>_R_CHECK_WALL_FORTRAN_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fXREFS_005fREPOSITORIES_005f-132"><code>_R_CHECK_XREFS_REPOSITORIES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fCHECK_005fXREFS_005fUSE_005fALIASES_005fFROM_005fCRAN_005f-157"><code>_R_CHECK_XREFS_USE_ALIASES_FROM_CRAN_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-g_t_005fR_005fSHLIB_005fBUILD_005fOBJECTS_005fSYMBOL_005fTABLES_005f-158"><code>_R_SHLIB_BUILD_OBJECTS_SYMBOL_TABLES_</code></a>: <a href="#Tools">Tools</a></li> <li><a href="#index-alloca-86"><code>alloca</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-ARGSUSED-21"><code>ARGSUSED</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-ATTRIB-43"><code>ATTRIB</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-attribute_005fhidden-107"><code>attribute_hidden</code></a>: <a href="#Hiding-C-entry-points">Hiding C entry points</a></li> <li><a href="#index-Calloc-81"><code>Calloc</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-copyMostAttributes-49"><code>copyMostAttributes</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-DDVAL-25"><code>DDVAL</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-debug-bit-12"><code>debug bit</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-DispatchGeneric-62"><code>DispatchGeneric</code></a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-DispatchOrEval-60"><code>DispatchOrEval</code></a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-dump_002eframes-103"><code>dump.frames</code></a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-DUPLICATE_005fATTRIB-45"><code>DUPLICATE_ATTRIB</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-emacs-169"><code>emacs</code></a>: <a href="#R-coding-standards">R coding standards</a></li> <li><a href="#index-error-78"><code>error</code></a>: <a href="#Warnings-and-errors">Warnings and errors</a></li> <li><a href="#index-errorcall-79"><code>errorcall</code></a>: <a href="#Warnings-and-errors">Warnings and errors</a></li> <li><a href="#index-Free-83"><code>Free</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-gp-bits-18"><code>gp bits</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-invisible-70"><code>invisible</code></a>: <a href="#Autoprinting">Autoprinting</a></li> <li><a href="#index-last_002ewarning-99"><code>last.warning</code></a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-LEVELS-19"><code>LEVELS</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-make-166"><code>make</code></a>: <a href="#R-coding-standards">R coding standards</a></li> <li><a href="#index-makeinfo-168"><code>makeinfo</code></a>: <a href="#R-coding-standards">R coding standards</a></li> <li><a href="#index-MISSING-64"><code>MISSING</code></a>: <a href="#Missingness">Missingness</a></li> <li><a href="#index-MISSING-23"><code>MISSING</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-mkChar-74"><code>mkChar</code></a>: <a href="#The-CHARSXP-cache">The CHARSXP cache</a></li> <li><a href="#index-mkCharLenCE-75"><code>mkCharLenCE</code></a>: <a href="#The-CHARSXP-cache">The CHARSXP cache</a></li> <li><a href="#index-NAMED-111"><code>NAMED</code></a>: <a href="#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a></li> <li><a href="#index-NAMED-54"><code>NAMED</code></a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-NAMED-15"><code>NAMED</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-named-bit-14"><code>named bit</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-Perl-167"><code>Perl</code></a>: <a href="#R-coding-standards">R coding standards</a></li> <li><a href="#index-PRIMPRINT-69"><code>PRIMPRINT</code></a>: <a href="#Autoprinting">Autoprinting</a></li> <li><a href="#index-PRSEEN-28"><code>PRSEEN</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-R_005falloc-80"><code>R_alloc</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-R_005fAllocStringBuffer-89"><code>R_AllocStringBuffer</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-R_005fBaseNamespace-41"><code>R_BaseNamespace</code></a>: <a href="#Namespaces">Namespaces</a></li> <li><a href="#index-R_005fCheckStack-87"><code>R_CheckStack</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-R_005fCheckStack2-88"><code>R_CheckStack2</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-R_005fFreeStringBuffer-91"><code>R_FreeStringBuffer</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-R_005fFreeStringBufferL-90"><code>R_FreeStringBufferL</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-R_005fMissingArg-65"><code>R_MissingArg</code></a>: <a href="#Missingness">Missingness</a></li> <li><a href="#index-R_005fVisible-68"><code>R_Visible</code></a>: <a href="#Autoprinting">Autoprinting</a></li> <li><a href="#index-Rdll_002ehide-108"><code>Rdll.hide</code></a>: <a href="#Hiding-C-entry-points">Hiding C entry points</a></li> <li><a href="#index-Realloc-82"><code>Realloc</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-SET_005fARGUSED-22"><code>SET_ARGUSED</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-SET_005fATTRIB-44"><code>SET_ATTRIB</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-SET_005fDDVAL-26"><code>SET_DDVAL</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-SET_005fMISSING-24"><code>SET_MISSING</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-SET_005fNAMED-16"><code>SET_NAMED</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-SETLEVELS-20"><code>SETLEVELS</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-trace-bit-13"><code>trace bit</code></a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-UseMethod-51"><code>UseMethod</code></a>: <a href="#Contexts">Contexts</a></li> <li><a href="#index-vmaxget-85"><code>vmaxget</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-vmaxset-84"><code>vmaxset</code></a>: <a href="#Memory-allocators">Memory allocators</a></li> <li><a href="#index-warning-76"><code>warning</code></a>: <a href="#Warnings-and-errors">Warnings and errors</a></li> <li><a href="#index-warningcall-77"><code>warningcall</code></a>: <a href="#Warnings-and-errors">Warnings and errors</a></li> </ul><div class="node"> <a name="Concept-index"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Function-and-variable-index">Function and variable index</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="unnumbered">Concept index</h2> <ul class="index-cp" compact> <li><a href="#index-g_t_002e_002e_002e-argument-66">... argument</a>: <a href="#Dot_002ddot_002ddot-arguments">Dot-dot-dot arguments</a></li> <li><a href="#index-g_t_002e_002e_002e-argument-27">... argument</a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-g_t_002eInternal-function-58">.Internal function</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-allocation-classes-31">allocation classes</a>: <a href="#Allocation-classes">Allocation classes</a></li> <li><a href="#index-argument-evaluation-53">argument evaluation</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-argument-list-8">argument list</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-atomic-vector-type-6">atomic vector type</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-attributes-42">attributes</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-attributes_002c-preserving-47">attributes, preserving</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-autoprinting-67">autoprinting</a>: <a href="#Autoprinting">Autoprinting</a></li> <li><a href="#index-base-environment-92">base environment</a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-base-environment-35">base environment</a>: <a href="#Environments-and-variable-lookup">Environments and variable lookup</a></li> <li><a href="#index-base-namespace-39">base namespace</a>: <a href="#Namespaces">Namespaces</a></li> <li><a href="#index-builtin-function-55">builtin function</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-coding-standards-165">coding standards</a>: <a href="#R-coding-standards">R coding standards</a></li> <li><a href="#index-context-50">context</a>: <a href="#Contexts">Contexts</a></li> <li><a href="#index-copying-semantics-46">copying semantics</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-copying-semantics-17">copying semantics</a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-environment-32">environment</a>: <a href="#Environments-and-variable-lookup">Environments and variable lookup</a></li> <li><a href="#index-environment_002c-base-93">environment, base</a>: <a href="#Base-environment">Base environment</a></li> <li><a href="#index-environment_002c-base-36">environment, base</a>: <a href="#Environments-and-variable-lookup">Environments and variable lookup</a></li> <li><a href="#index-environment_002c-global-101">environment, global</a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-expression-9">expression</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-function-10">function</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-garbage-collector-72">garbage collector</a>: <a href="#The-write-barrier">The write barrier</a></li> <li><a href="#index-generic_002c-generic-61">generic, generic</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-generic_002c-internal-59">generic, internal</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-global-environment-100">global environment</a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-language-object-7">language object</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-method-dispatch-52">method dispatch</a>: <a href="#Contexts">Contexts</a></li> <li><a href="#index-missingness-63">missingness</a>: <a href="#Missingness">Missingness</a></li> <li><a href="#index-modules-105">modules</a>: <a href="#Modules">Modules</a></li> <li><a href="#index-namespace-38">namespace</a>: <a href="#Namespaces">Namespaces</a></li> <li><a href="#index-namespace_002c-base-40">namespace, base</a>: <a href="#Namespaces">Namespaces</a></li> <li><a href="#index-node-3">node</a>: <a href="#SEXPs">SEXPs</a></li> <li><a href="#index-preserving-attributes-48">preserving attributes</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-primitive-function-57">primitive function</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-promise-29">promise</a>: <a href="#Rest-of-header">Rest of header</a></li> <li><a href="#index-S4-type-11">S4 type</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-search-path-37">search path</a>: <a href="#Search-paths">Search paths</a></li> <li><a href="#index-serialization-73">serialization</a>: <a href="#Serialization-Formats">Serialization Formats</a></li> <li><a href="#index-SEXP-1">SEXP</a>: <a href="#SEXPs">SEXPs</a></li> <li><a href="#index-SEXPRREC-2">SEXPRREC</a>: <a href="#SEXPs">SEXPs</a></li> <li><a href="#index-SEXPTYPE-4">SEXPTYPE</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-SEXPTYPE-table-5">SEXPTYPE table</a>: <a href="#SEXPTYPEs">SEXPTYPEs</a></li> <li><a href="#index-special-function-56">special function</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-user-databases-34">user databases</a>: <a href="#Environments-and-variable-lookup">Environments and variable lookup</a></li> <li><a href="#index-variable-lookup-33">variable lookup</a>: <a href="#Environments-and-variable-lookup">Environments and variable lookup</a></li> <li><a href="#index-vector-type-30">vector type</a>: <a href="#The-_0027data_0027">The 'data'</a></li> <li><a href="#index-visibility-106">visibility</a>: <a href="#Visibility">Visibility</a></li> <li><a href="#index-write-barrier-71">write barrier</a>: <a href="#The-write-barrier">The write barrier</a></li> </ul><div class="footnote"> <hr> <a name="texinfo-footnotes-in-document"></a><h4>Footnotes</h4><p class="footnote"><small>[<a name="fn-1" href="#fnd-1">1</a>]</small> strictly, a <code>SEXPREC</code> node; <code>VECTOR_SEXPREC</code> nodes are slightly smaller but followed by data in the node.</p> <p class="footnote"><small>[<a name="fn-2" href="#fnd-2">2</a>]</small> a pointer to a function or a symbol to look up the function by name, or a language object to be evaluated to give a function.</p> <p class="footnote"><small>[<a name="fn-3" href="#fnd-3">3</a>]</small> This is almost unused. The only current use is for hash tables of environments (<code>VECSXP</code>s), where <code>length</code> is the size of the table and <code>truelength</code> is the number of primary slots in use, and for the reference hash tables in serialization (<code>VECSXP</code>s), where <code>truelength</code> is the number of slots in use.</p> <p class="footnote"><small>[<a name="fn-4" href="#fnd-4">4</a>]</small> Remember that attaching a list or a saved image actually creates and populates an environment and attaches that.</p> <p class="footnote"><small>[<a name="fn-5" href="#fnd-5">5</a>]</small> There is currently one other difference: when profiling builtin functions are counted as function calls but specials are not.</p> <p class="footnote"><small>[<a name="fn-6" href="#fnd-6">6</a>]</small> the other current example is left brace, which is implemented as a primitive.</p> <p class="footnote"><small>[<a name="fn-7" href="#fnd-7">7</a>]</small> only bits 0:4 are currently used for <code>SEXPTYPE</code>s but values 241:255 are used for pseudo-<code>SEXPTYPE</code>s.</p> <p class="footnote"><small>[<a name="fn-8" href="#fnd-8">8</a>]</small> Currently the only relevant bits are 0:1, 4, 14:15.</p> <p class="footnote"><small>[<a name="fn-9" href="#fnd-9">9</a>]</small> See define <code>USE_UTF8_IF_POSSIBLE</code> in file <samp><span class="file">src/main/gram.c</span></samp>.</p> <p class="footnote"><small>[<a name="fn-10" href="#fnd-10">10</a>]</small> or UTF-16 if support for surrogates is enabled in the OS, which it is not normally so at least for Western versions of Windows, despite some claims to the contrary on the Microsoft website.</p> <p class="footnote"><small>[<a name="fn-11" href="#fnd-11">11</a>]</small> but not the GraphApp toolkit.</p> <p class="footnote"><small>[<a name="fn-12" href="#fnd-12">12</a>]</small> This can also create non-S4 objects, as in <code>new("integer")</code>.</p> <p class="footnote"><small>[<a name="fn-13" href="#fnd-13">13</a>]</small> although this is not recommended as it is less future-proof.</p> <p class="footnote"><small>[<a name="fn-14" href="#fnd-14">14</a>]</small> but apparently not on Windows.</p> <p class="footnote"><small>[<a name="fn-15" href="#fnd-15">15</a>]</small> The C code is in files <code>base.c</code>, <code>graphics.c</code>, <code>par.c</code>, <code>plot.c</code> and <code>plot3d.c</code> in directory <samp><span class="file">src/main</span></samp>.</p> <p class="footnote"><small>[<a name="fn-16" href="#fnd-16">16</a>]</small> although that needs to be handled carefully, as for example the <code>circle</code> callback is given a radius (and that should be interpreted as in the x units).</p> <p class="footnote"><small>[<a name="fn-17" href="#fnd-17">17</a>]</small> It is possible for the device to find the <code>GEDevDesc</code> which points to its <code>DevDesc</code>, and this is done often enough that there is a convenience function <code>desc2GEDesc</code> to do so.</p> <p class="footnote"><small>[<a name="fn-18" href="#fnd-18">18</a>]</small> Calling <code>R_CheckDeviceAvailable()</code> ensures there is a free slot or throws an error.</p> <p class="footnote"><small>[<a name="fn-19" href="#fnd-19">19</a>]</small> in device coordinates</p> <p class="footnote"><small>[<a name="fn-20" href="#fnd-20">20</a>]</small> It is technically possible to use alpha-blending on metafile devices such as printers, but it seems few drivers have support for this.</p> <p class="footnote"><small>[<a name="fn-21" href="#fnd-21">21</a>]</small> an Xcode project, in SVN at <a href="https://svn.r-project.org/R-packages/trunk/Mac-GUI">https://svn.r-project.org/R-packages/trunk/Mac-GUI</a>.</p> <p class="footnote"><small>[<a name="fn-22" href="#fnd-22">22</a>]</small> under Windows, junction points, or copies if environment variable <samp><span class="env">R_WIN_NO_JUNCTIONS</span></samp> has a non-empty value.</p> <p class="footnote"><small>[<a name="fn-23" href="#fnd-23">23</a>]</small> see the previous footnote.</p> <p class="footnote"><small>[<a name="fn-24" href="#fnd-24">24</a>]</small> Linux distributions tend to unbundle <samp><span class="file">texinfo.tex</span></samp> from ‘<samp><span class="samp">texinfo</span></samp>’.</p> <p class="footnote"><small>[<a name="fn-25" href="#fnd-25">25</a>]</small> but <code>LENGTH</code> is a macro under some internal uses.</p> <hr></div> </body></html> <!-- Local Variables: coding: iso-8859-1 End: -->