2 / Copyright (c) 2008 Eric Niebler
4 / Distributed under the Boost Software License, Version 1.0. (See accompanying
5 / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8 [/=======================]
9 [section Hello Calculator]
10 [/=======================]
12 "Hello, world" is nice, but it doesn't get you very far. Let's use Proto to build a
13 EDSL (embedded domain-specific language) for a lazily-evaluated calculator. We'll
14 see how to define the terminals in your mini-language, how to compose them into
15 larger expressions, and how to define an evaluation context so that your
16 expressions can do useful work. When we're done, we'll have a mini-language that
17 will allow us to declare a lazily-evaluated arithmetic expression, such as
18 `(_2 - _1) / _2 * 100`, where `_1` and `_2` are placeholders for values to be
19 passed in when the expression is evaluated.
21 [/=========================]
22 [heading Defining Terminals]
23 [/=========================]
25 The first order of business is to define the placeholders `_1` and `_2`. For that,
26 we'll use the _terminal_ metafunction.
28 // Define a placeholder type
33 // Define the Protofied placeholder terminals
34 proto::terminal<placeholder<0> >::type const _1 = {{}};
35 proto::terminal<placeholder<1> >::type const _2 = {{}};
37 The initialization may look a little odd at first, but there is a good reason
38 for doing things this way. The objects `_1` and `_2` above do not require
39 run-time construction -- they are ['statically initialized], which means they
40 are essentially initialized at compile time. See the
41 [link boost_proto.appendices.rationale.static_initialization Static
42 Initialization] section in the [link boost_proto.appendices.rationale Rationale]
43 appendix for more information.
45 [/====================================]
46 [heading Constructing Expression Trees]
47 [/====================================]
49 Now that we have terminals, we can use Proto's operator overloads to combine
50 these terminals into larger expressions. So, for instance, we can immediately
53 // This builds an expression template
56 This creates an expression tree with a node for each operator. The type of the
57 resulting object is large and complex, but we are not terribly interested in it right now.
59 So far, the object is just a tree representing the expression. It has no
60 behavior. In particular, it is not yet a calculator. Below we'll see how
61 to make it a calculator by defining an evaluation context.
63 [/==================================]
64 [heading Evaluating Expression Trees]
65 [/==================================]
67 No doubt you want your expression templates to actually /do/ something. One
68 approach is to define an ['evaluation context]. The context is like a function
69 object that associates behaviors with the node types in your expression tree.
70 The following example should make it clear. It is explained below.
72 struct calculator_context
73 : proto::callable_context< calculator_context const >
75 // Values to replace the placeholders
76 std::vector<double> args;
78 // Define the result type of the calculator.
79 // (This makes the calculator_context "callable".)
80 typedef double result_type;
82 // Handle the placeholders:
84 double operator()(proto::tag::terminal, placeholder<I>) const
90 In `calculator_context`, we specify how Proto should evaluate the placeholder
91 terminals by defining the appropriate overloads of the function call operator.
92 For any other nodes in the expression tree (e.g., arithmetic operations or
93 non-placeholder terminals), Proto will evaluate the expression in the "default"
94 way. For example, a binary plus node is evaluated by first evaluating the left
95 and right operands and adding the results. Proto's default evaluator uses the
96 _typeof_ library to compute return types.
98 Now that we have an evaluation context for our calculator, we can use it to
99 evaluate our arithmetic expressions, as below:
101 calculator_context ctx;
102 ctx.args.push_back(45); // the value of _1 is 45
103 ctx.args.push_back(50); // the value of _2 is 50
105 // Create an arithmetic expression and immediately evaluate it
106 double d = proto::eval( (_2 - _1) / _2 * 100, ctx );
109 std::cout << d << std::endl;
111 Later, we'll see how to define more interesting evaluation contexts and
112 expression transforms that give you total control over how your expressions
115 [/===================================]
116 [heading Customizing Expression Trees]
117 [/===================================]
119 Our calculator EDSL is already pretty useful, and for many EDSL scenarios, no more
120 would be needed. But let's keep going. Imagine how much nicer it would be if all
121 calculator expressions overloaded `operator()` so that they could be used as
122 function objects. We can do that by creating a calculator /domain/ and telling
123 Proto that all expressions in the calculator domain have extra members. Here is how
124 to define a calculator domain:
126 // Forward-declare an expression wrapper
127 template<typename Expr>
130 // Define a calculator domain. Expression within
131 // the calculator domain will be wrapped in the
132 // calculator<> expression wrapper.
133 struct calculator_domain
134 : proto::domain< proto::generator<calculator> >
137 The `calculator<>` type will be an expression wrapper. It will behave just like the
138 expression that it wraps, but it will have extra member functions that we will
139 define. The `calculator_domain` is what informs Proto about our wrapper. It is used
140 below in the definition of `calculator<>`. Read on for a description.
142 // Define a calculator expression wrapper. It behaves just like
143 // the expression it wraps, but with an extra operator() member
144 // function that evaluates the expression.
145 template<typename Expr>
147 : proto::extends<Expr, calculator<Expr>, calculator_domain>
150 proto::extends<Expr, calculator<Expr>, calculator_domain>
153 calculator(Expr const &expr = Expr())
157 typedef double result_type;
159 // Overload operator() to invoke proto::eval() with
160 // our calculator_context.
161 double operator()(double a1 = 0, double a2 = 0) const
163 calculator_context ctx;
164 ctx.args.push_back(a1);
165 ctx.args.push_back(a2);
167 return proto::eval(*this, ctx);
171 The `calculator<>` struct is an expression /extension/. It uses `proto::extends<>` to effectively add additional members to an expression type. When composing larger expressions from smaller ones, Proto notes what domain the smaller expressions are in. The larger expression is in the same domain and is automatically wrapped in the domain's extension wrapper.
173 All that remains to be done is to put our placeholders in the calculator domain. We do that by wrapping them in our `calculator<>` wrapper, as below:
175 // Define the Protofied placeholder terminals, in the
176 // calculator domain.
177 calculator<proto::terminal<placeholder<0> >::type> const _1;
178 calculator<proto::terminal<placeholder<1> >::type> const _2;
180 Any larger expression that contain these placeholders will automatically be wrapped in the `calculator<>` wrapper and have our `operator()` overload. That means we can use them as function objects as follows.
182 double result = ((_2 - _1) / _2 * 100)(45.0, 50.0);
183 assert(result == (50.0 - 45.0) / 50.0 * 100));
185 Since calculator expressions are now valid function objects, we can use them with standard algorithms, as shown below:
187 double a1[4] = { 56, 84, 37, 69 };
188 double a2[4] = { 65, 120, 60, 70 };
189 double a3[4] = { 0 };
191 // Use std::transform() and a calculator expression
192 // to calculate percentages given two input sequences:
193 std::transform(a1, a1+4, a2, a3, (_2 - _1) / _2 * 100);
195 Now, let's use the calculator example to explore some other useful features of Proto.
197 [/====================================]
198 [heading Detecting Invalid Expressions]
199 [/====================================]
201 You may have noticed that you didn't have to define an overloaded `operator-()` or
202 `operator/()` -- Proto defined them for you. In fact, Proto overloads /all/ the
203 operators for you, even though they may not mean anything in your domain-specific
204 language. That means it may be possible to create expressions that are invalid in
205 your domain. You can detect invalid expressions with Proto by defining the
206 /grammar/ of your domain-specific language.
208 For simplicity, assume that our calculator EDSL should only allow addition,
209 subtraction, multiplication and division. Any expression involving any other
210 operator is invalid. Using Proto, we can state this requirement by defining the
211 grammar of the calculator EDSL. It looks as follows:
213 // Define the grammar of calculator expressions
214 struct calculator_grammar
216 proto::plus< calculator_grammar, calculator_grammar >
217 , proto::minus< calculator_grammar, calculator_grammar >
218 , proto::multiplies< calculator_grammar, calculator_grammar >
219 , proto::divides< calculator_grammar, calculator_grammar >
220 , proto::terminal< proto::_ >
224 You can read the above grammar as follows: an expression tree conforms to the calculator grammar if it is a binary plus, minus, multiplies or divides node, where both child nodes also conform to the calculator grammar; or if it is a terminal. In a Proto grammar, _wild_ is a wildcard that matches any type, so `proto::terminal< proto::_ >` matches any terminal, whether it is a placeholder or a literal.
226 [note This grammar is actually a little looser than we would like. Only placeholders and literals that are convertible to doubles are valid terminals. Later on we'll see how to express things like that in Proto grammars.]
228 Once you have defined the grammar of your EDSL, you can use the _matches_ metafunction to check whether a given expression type conforms to the grammar. For instance, we might add the following to our `calculator::operator()` overload:
230 template<typename Expr>
232 : proto::extends< /* ... as before ... */ >
235 double operator()(double a1 = 0, double a2 = 0) const
237 // Check here that the expression we are about to
238 // evaluate actually conforms to the calculator grammar.
239 BOOST_MPL_ASSERT((proto::matches<Expr, calculator_grammar>));
244 The addition of the `BOOST_MPL_ASSERT()` line enforces at compile time that we only
245 evaluate expressions that conform to the calculator EDSL's grammar. With Proto
246 grammars, `proto::matches<>` and `BOOST_MPL_ASSERT()` it is very easy to give the
247 users of your EDSL short and readable compile-time errors when they accidentally
250 [note `BOOST_MPL_ASSERT()` is part of the Boost Metaprogramming Library. To use it,
251 just `#include <boost/mpl/assert.hpp>`.]
253 [/=====================================]
254 [heading Controlling Operator Overloads]
255 [/=====================================]
257 Grammars and `proto::matches<>` make it possible to detect when a user has created
258 an invalid expression and issue a compile-time error. But what if you want to
259 prevent users from creating invalid expressions in the first place? By using
260 grammars and domains together, you can disable any of Proto's operator overloads
261 that would create an invalid expression. It is as simple as specifying the EDSL's
262 grammar when you define the domain, as shown below:
264 // Define a calculator domain. Expression within
265 // the calculator domain will be wrapped in the
266 // calculator<> expression wrapper.
267 // NEW: Any operator overloads that would create an
268 // expression that does not conform to the
269 // calculator grammar is automatically disabled.
270 struct calculator_domain
271 : proto::domain< proto::generator<calculator>, calculator_grammar >
274 The only thing we changed is we added `calculator_grammar` as the second template
275 parameter to the `proto::domain<>` template when defining `calculator_domain`. With
276 this simple addition, we disable any of Proto's operator overloads that would
277 create an invalid calculator expression.
279 [/========================]
280 [heading ... And Much More]
281 [/========================]
283 Hopefully, this gives you an idea of what sorts of things Proto can do for you. But
284 this only scratches the surface. The rest of this users' guide will describe all
285 these features and others in more detail.
287 Happy metaprogramming!