Skip to content
richardxia edited this page Sep 14, 2011 · 13 revisions

Tutorials

Templating and the ArrayDoubler Specializer

This section will explain the ArrayDoubler example specializer, which comes packaged with Asp in the specializers/array_doubler/ directory. The ArrayDoubler specializer is meant to introduce developers to the templating features of Asp. ArrayDoubler itself simply takes an input list of numbers and returns the result of multiplying each of the elements by 2. If you look at tests/arraydoubler_test.py, you can see how an ArrayDoubler object is instantiated and how its pure Python implementation and its more efficient C implementation are called.

In array_doubler.py, you will see two methods for ArrayDoubler: double(), which is the pure Python implementation, and double_using_template(), which uses a template to output C code. Asp uses Mako as its templating engine. The template file is located at templates/double_template.mako, but since this is a trivial example, the only specialization used here is to set the upper bound of the for loop. Back in double_using_template(), the template is rendered as a string containing the code and is passed into an instance of ASPModule with the add_function() method, which handles the dynamic compilation and linking.

Generating C code using templates is the fastest way of writing a specializer for Asp, but it is limited in power compared to using tree transformations.

Clone this wiki locally