| 1 |
wraptypes |
| 2 |
========= |
| 3 |
|
| 4 |
wraptypes is a general utility for creating ctypes wrappers from C header |
| 5 |
files. The front-end is ``tools/wraptypes/wrap.py``, for usage:: |
| 6 |
|
| 7 |
python tools/wraptypes/wrap.py -h |
| 8 |
|
| 9 |
There are three components to wraptypes: |
| 10 |
|
| 11 |
preprocessor.py |
| 12 |
Interprets preprocessor declarations and converts the source header files |
| 13 |
into a list of tokens. |
| 14 |
cparser.py |
| 15 |
Parses the preprocessed tokens for type and function declarations and |
| 16 |
calls ``handle_`` methods on the class CParser in a similar manner to a |
| 17 |
SAX parser. |
| 18 |
ctypesparser.py |
| 19 |
Interprets C declarations and types from CParser and creates corresponding |
| 20 |
ctypes declarations, calling ``handle_`` methods on the class |
| 21 |
CtypesParser. |
| 22 |
|
| 23 |
.. image: wraptypes-class.svg |
| 24 |
|
| 25 |
The front-end ``wrap.py`` provides a simple subclass of ``CtypesParser``, |
| 26 |
``CtypesWrapper``, which writes the ctypes declarations found to a file in a |
| 27 |
format that can be imported as a module. |
| 28 |
|
| 29 |
Parser Modifications |
| 30 |
-------------------- |
| 31 |
|
| 32 |
The parsers are built upon a modified version of `PLY`_, a Python |
| 33 |
implementation of lex and yacc. The modified source is included in |
| 34 |
the ``wraptypes`` directory. The modifications are: |
| 35 |
|
| 36 |
* Grammar is abstracted out of Parser, so multiple grammars can easily be |
| 37 |
defined in the same module. |
| 38 |
* Tokens and symbols keep track of their filename as well as line number. |
| 39 |
* Lexer state can be pushed onto a stack. |
| 40 |
|
| 41 |
The first time the parsers are run (or after they are modified), PLY creates |
| 42 |
``pptab.py`` and ``parsetab.py`` in the current directory. These are |
| 43 |
the generated state machines, which can take a few seconds to generate. |
| 44 |
The file ``parser.out`` is created if debugging is enabled, and contains the |
| 45 |
parser description (of the last parser that was generated), which is essential |
| 46 |
for debugging. |
| 47 |
|
| 48 |
.. _PLY: http://www.dabeaz.com/ply/ |
| 49 |
|
| 50 |
Preprocessor |
| 51 |
------------ |
| 52 |
|
| 53 |
The grammar and parser are defined in ``preprocessor.py``. |
| 54 |
|
| 55 |
There is only one lexer state. Each token has a type which is a string (e.g. |
| 56 |
``'CHARACTER_CONSTANT'``) and a value. Token values, when read directly from |
| 57 |
the source file are only ever strings. When tokens are written to the output |
| 58 |
list they sometimes have tuple values (for example, a ``PP_DEFINE`` token on |
| 59 |
output). |
| 60 |
|
| 61 |
Two lexer classes are defined: ``PreprocessorLexer``, which reads a stack of |
| 62 |
files (actually strings) as input, and ``TokenListLexer``, which reads from a |
| 63 |
list of already-parsed tokens (used for parsing expressions). |
| 64 |
|
| 65 |
The preprocessing entry-point is the ``PreprocessorParser`` class. This |
| 66 |
creates a ``PreprocessorLexer`` and its grammar during construction. The |
| 67 |
system include path includes the GCC search path by default but can be |
| 68 |
modified by altering the ``include_path`` and ``framework_path`` lists. The |
| 69 |
``system_headers`` dict allows header files to be implied on the search path |
| 70 |
that don't exist. For example, by setting:: |
| 71 |
|
| 72 |
system_headers['stdlib.h'] = '''#ifndef STDLIB_H |
| 73 |
#define STDLIB_H |
| 74 |
|
| 75 |
/* ... */ |
| 76 |
#endif |
| 77 |
''' |
| 78 |
|
| 79 |
you can insert your own custom header in place of the one on the filesystem. |
| 80 |
This is useful when parsing headers from network locations. |
| 81 |
|
| 82 |
Parsing begins when ``parse`` is called. Specify one or both of a filename |
| 83 |
and a string of data. If ``debug`` kwarg is True, syntax errors dump the |
| 84 |
parser state instead of just the line number where they occurred. |
| 85 |
|
| 86 |
The production rules specify the actions; these are implemented in |
| 87 |
``PreprocessorGrammar``. The actions call methods on ``PreprocessorParser``, |
| 88 |
such as: |
| 89 |
|
| 90 |
* ``include(self, header)``, to push another file onto the lexer. |
| 91 |
* ``include_system(self, header)``, to search the system path for a file to |
| 92 |
push onto the lexer |
| 93 |
* ``error(self, message, filename, line)``, to signal a parse error. Not |
| 94 |
all syntax errors get this far, due to limitations in the parser. A parse |
| 95 |
error at EOF will just print to stderr. |
| 96 |
* ``write(self, tokens)``, to write tokens to the output list. This is |
| 97 |
the default action when no preprocessing declaratives are being parsed. |
| 98 |
|
| 99 |
The parser has a stack of ``ExecutionState``, which specifies whether the |
| 100 |
current tokens being parsed are ignored or not (tokens are ignored in an |
| 101 |
``#if`` that evaluates to 0). This is a little more complicated than just a |
| 102 |
boolean flag: the parser must also ignore #elif conditions that can have no |
| 103 |
effect. The ``enable_declaratives`` and ``enable_elif_conditionals`` return |
| 104 |
True if the top-most ``ExecutionState`` allows declaratives and ``#elif`` |
| 105 |
conditionals to be parsed, respecitively. The execution state stack is |
| 106 |
modified with the ``condition_*`` methods. |
| 107 |
|
| 108 |
``PreprocessorParser`` has a ``PreprocessorNamespace`` which keeps track of |
| 109 |
the currently defined macros. You can create and specify your own namespace, |
| 110 |
or use one that is created by default. The default namespace includes GCC |
| 111 |
platform macros needed for parsing system headers, and some of the STDC |
| 112 |
macros. |
| 113 |
|
| 114 |
Macros are expanded when tokens are written to the output list, and when |
| 115 |
conditional expressions are parsed. |
| 116 |
``PreprocessorNamespace.apply_macros(tokens)`` takes care of this, replacing |
| 117 |
function parameters, variable arguments, macro objects and (mostly) avoiding |
| 118 |
infinite recursion. It does not yet handle the ``#`` and ``##`` operators, |
| 119 |
which are needed to parse the Windows system headers. |
| 120 |
|
| 121 |
The process for evaluating a conditional (``#if`` or ``#elif``) is: |
| 122 |
|
| 123 |
1. Tokens between ``PP_IF`` or ``PP_ELIF`` and ``NEWLINE`` are expanded |
| 124 |
by ``apply_macros``. |
| 125 |
2. The resulting list of tokens is used to construct a ``TokenListLexer``. |
| 126 |
3. This lexer is used as input to a ``ConstantExpressionParser``. This parser |
| 127 |
uses the ``ConstantExpressionGrammar``, which builds up an AST of |
| 128 |
``ExpressionNode`` objects. |
| 129 |
4. ``parse`` is called on the ``ConstantExpressionParser``, which returns the |
| 130 |
resulting top-level ``ExpressionNode``, or ``None`` if there was a syntax |
| 131 |
error. |
| 132 |
5. The ``evaluate`` method of the ``ExpressionNode`` is called with the |
| 133 |
preprocessor's namespace as the evaluation context. This allows the |
| 134 |
expression nodes to resolve ``defined`` operators. |
| 135 |
6. The result of ``evaluate`` is always an int; non-zero values are treated as |
| 136 |
True. |
| 137 |
|
| 138 |
Because pyglet requires special knowledge of the preprocessor declaratives |
| 139 |
that were encountered in the source, these are encoded as pseudo-tokens within |
| 140 |
the output token list. For example, after a ``#ifndef`` is evaluated, it |
| 141 |
is written to the token list as a ``PP_IFNDEF`` token. |
| 142 |
|
| 143 |
``#define`` is handled specially. After applying it to the namespace, it is |
| 144 |
parsed as an expression immediately. This is allowed (and often expected) to |
| 145 |
fail. If it does not fail, a ``PP_DEFINE_CONSTANT`` token is created, and the |
| 146 |
value is the result of evaluating the expression. Otherwise, a ``PP_DEFINE`` |
| 147 |
token is created, and the value is the string concatenation of the tokens |
| 148 |
defined. Special handling of parseable expressions makes it simple to later |
| 149 |
parse constants defined as, for example:: |
| 150 |
|
| 151 |
#define RED_SHIFT 8 |
| 152 |
#define RED_MASK (0x0f << RED_SHIFT) |
| 153 |
|
| 154 |
The preprocessor can be tested/debugged by running ``preprocessor.py`` |
| 155 |
stand-alone with a header file as the sole argument. The resulting token list |
| 156 |
will be written to stdout. |
| 157 |
|
| 158 |
CParser |
| 159 |
------- |
| 160 |
|
| 161 |
The lexer for ``CParser``, ``CLexer``, takes as input a list of tokens output |
| 162 |
from the preprocessor. The special preprocessor tokens such as ``PP_DEFINE`` |
| 163 |
are intercepted here and handled immediately; hence they can appear anywhere |
| 164 |
in the source header file without causing problems with the parser. At this |
| 165 |
point ``IDENTIFIER`` tokens which are found to be the name of a defined type |
| 166 |
(the set of defined types is updated continuously during parsing) are |
| 167 |
converted to ``TYPE_NAME`` tokens. |
| 168 |
|
| 169 |
The entry-point to parsing C source is the ``CParser`` class. This creates a |
| 170 |
preprocessor in its constructor, and defines some default types such as |
| 171 |
``wchar_t`` and ``__int64_t``. These can be disabled with kwargs. |
| 172 |
|
| 173 |
Preprocessing can be quite time-consuming, especially on OS X where thousands |
| 174 |
of ``#include`` declaratives are processed when Carbon is parsed. To minimise |
| 175 |
the time required to parse similar (or the same, while debugging) header |
| 176 |
files, the token list from preprocessing is cached and reused where possible. |
| 177 |
|
| 178 |
This is handled by ``CPreprocessorParser``, which overrides ``push_file`` to |
| 179 |
check with ``CParser`` if the desired file is cached. The cache is checked |
| 180 |
against the file's modification timestamp as well as a "memento" that |
| 181 |
describes the currently defined tokens. This is intended to avoid using a |
| 182 |
cached file that would otherwise be parsed differently due to the defined |
| 183 |
macros. It is by no means perfect; for example, it won't pick up on a macro |
| 184 |
that has been defined differently. It seems to work well enough for the |
| 185 |
header files pyglet requires. |
| 186 |
|
| 187 |
The header cache is saved and loaded automatically in the working directory |
| 188 |
as ``.header.cache``. The cache should be deleted if you make changes to the |
| 189 |
preprocessor, or are experiencing cache errors (these are usually accompanied |
| 190 |
by a "what-the?" exclamation from the user). |
| 191 |
|
| 192 |
The actions in the grammar construct parts of a "C object model" and call |
| 193 |
methods on ``CParser``. The C object model is not at all complete, containing |
| 194 |
only what pyglet (and any other ctypes-wrapping application) requires. The |
| 195 |
classes in the object model are: |
| 196 |
|
| 197 |
Declaration |
| 198 |
A single declaration occurring outside of a function body. This includes |
| 199 |
type declarations, function declarations and variable declarations. The |
| 200 |
attributes are ``declarator`` (see below), ``type`` (a Type object) and |
| 201 |
``storage`` (for example, 'typedef', 'const', 'static', 'extern', etc). |
| 202 |
Declarator |
| 203 |
A declarator is a thing being declared. Declarators have an |
| 204 |
``identifier`` (the name of it, None if the declarator is abstract, as in |
| 205 |
some function parameter declarations), an optional ``initializer`` |
| 206 |
(currently ignored), an optional linked-list of ``array`` (giving the |
| 207 |
dimensions of the array) and an optional list of ``parameters`` (if the |
| 208 |
declarator is a function). |
| 209 |
Pointer |
| 210 |
This is a type of declarator that is dereferenced via ``pointer`` to |
| 211 |
another declarator. |
| 212 |
Array |
| 213 |
Array has size (an int, its dimension, or None if unsized) and a pointer |
| 214 |
``array`` to the next array dimension, if any. |
| 215 |
Parameter |
| 216 |
A function parameter consisting of a ``type`` (Type object), ``storage`` |
| 217 |
and ``declarator``. |
| 218 |
Type |
| 219 |
Type has a list of ``qualifiers`` (e.g. 'const', 'volatile', etc) and |
| 220 |
``specifiers`` (the meaty bit). |
| 221 |
TypeSpecifier |
| 222 |
A base TypeSpecifier is just a string, such as ``'int'`` or ``'Foo'`` or |
| 223 |
``'unsigned'``. Note that types can have multiple TypeSpecifiers; not |
| 224 |
all combinations are valid. |
| 225 |
StructTypeSpecifier |
| 226 |
This is the specifier for a struct or union (if ``is_union`` is True) |
| 227 |
type. ``tag`` gives the optional ``foo`` in ``struct foo`` and |
| 228 |
``declarations`` is the meat (an empty list for an opaque or unspecified |
| 229 |
struct). |
| 230 |
EnumSpecifier |
| 231 |
This is the specifier for an enum type. ``tag`` gives the optional |
| 232 |
``foo`` in ``enum foo`` and ``enumerators`` is the list of Enumerator |
| 233 |
objects (an empty list for an unspecified enum). |
| 234 |
Enumerator |
| 235 |
Enumerators exist only within EnumSpecifier. Contains ``name`` and |
| 236 |
``expression``, an ExpressionNode object. |
| 237 |
|
| 238 |
The ``ExpressionNode`` object hierarchy is similar to that used in the |
| 239 |
preprocessor, but more fully-featured, and using a different |
| 240 |
``EvaluationContext`` which can evaluate identifiers and the ``sizeof`` |
| 241 |
operator (currently it actually just returns 0 for both). |
| 242 |
|
| 243 |
Methods are called on CParser as declarations and preprocessor declaratives |
| 244 |
are parsed. The are mostly self explanatory. For example: |
| 245 |
|
| 246 |
handle_ifndef(self, name, filename, lineno) |
| 247 |
An ``#ifndef`` was encountered testing the macro ``name`` in file |
| 248 |
``filename`` at line ``lineno``. |
| 249 |
handle_declaration(self, declaration, filename, lineno) |
| 250 |
``declaration`` is an instance of Declaration. |
| 251 |
|
| 252 |
These methods should be overridden by a subclass to provide functionality. |
| 253 |
The ``DebugCParser`` does this and prints out the arguments to each |
| 254 |
``handle_`` method. |
| 255 |
|
| 256 |
The ``CParser`` can be tested in isolation by running it stand-alone with the |
| 257 |
filename of a header as the sole argument. A ``DebugCParser`` will be |
| 258 |
constructed and used to parse the header. |
| 259 |
|
| 260 |
CtypesParser |
| 261 |
------------ |
| 262 |
|
| 263 |
``CtypesParser`` is implemented in ``ctypesparser.py``. It is a subclass of |
| 264 |
``CParser`` and implements the ``handle_`` methods to provide a more |
| 265 |
ctypes-friendly interpretation of the declarations. |
| 266 |
|
| 267 |
To use, subclass and override the methods: |
| 268 |
|
| 269 |
handle_ctypes_constant(self, name, value, filename, lineno) |
| 270 |
An integer or float constant (in a ``#define``). |
| 271 |
handle_ctypes_type_definition(self, name, ctype, filename, lineno) |
| 272 |
A ``typedef`` declaration. See below for type of ``ctype``. |
| 273 |
handle_ctypes_function(self, name, restype, argtypes, filename, lineno) |
| 274 |
A function declaration with the given return type and argument list. |
| 275 |
handle_ctypes_variable(self, name, ctype, filename, lineno) |
| 276 |
Any other non-``static`` declaration. |
| 277 |
|
| 278 |
Types are represented by instances of ``CtypesType``. This is more easily |
| 279 |
manipulated than a "real" ctypes type. There are subclasses for |
| 280 |
``CtypesPointer``, ``CtypesArray``, ``CtypesFunction``, and so on; see the |
| 281 |
module for details. |
| 282 |
|
| 283 |
Each ``CtypesType`` class implements the ``visit`` method, which can be used, |
| 284 |
Visitor pattern style, to traverse the type hierarchy. Call the ``visit`` |
| 285 |
method of any type with an implementation of ``CtypesTypeVisitor``: all |
| 286 |
pointers, array bases, function parameters and return types are traversed |
| 287 |
automatically (struct members are not, however). |
| 288 |
|
| 289 |
This is useful when writing the contents of a struct or enum. Before writing |
| 290 |
a type declaration for a struct type (which would consist only of the struct's |
| 291 |
tag), ``visit`` the type and handle the ``visit_struct`` method on the visitor |
| 292 |
to print out the struct's members first. Similarly for enums. |
| 293 |
|
| 294 |
``ctypesparser.py`` can not be run stand-alone. ``wrap.py`` provides a |
| 295 |
straight-forward implementation that writes a module of ctypes wrappers. It |
| 296 |
can filter the output based on the originating filename. See the module |
| 297 |
docstring for usage and extension details. |