1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // A protocol compiler for Rust.
14 use codemap::dummy_sp;
15 use ext::base::ext_ctxt;
16 use ext::pipes::ast_builder::{append_types, ext_ctxt_ast_builder, path};
17 use ext::pipes::ast_builder::{path_global};
18 use ext::pipes::proto::*;
19 use ext::quote::rt::*;
26 use core::to_str::ToStr;
30 fn gen_send(&self, cx: ext_ctxt, try: bool) -> @ast::item;
31 fn to_ty(&self, cx: ext_ctxt) -> @ast::Ty;
34 pub trait to_type_decls {
35 fn to_type_decls(&self, cx: ext_ctxt) -> ~[@ast::item];
36 fn to_endpoint_decls(&self, cx: ext_ctxt, dir: direction) -> ~[@ast::item];
40 fn gen_init(&self, cx: ext_ctxt) -> @ast::item;
41 fn compile(&self, cx: ext_ctxt) -> @ast::item;
42 fn buffer_ty_path(&self, cx: ext_ctxt) -> @ast::Ty;
43 fn gen_buffer_type(&self, cx: ext_ctxt) -> @ast::item;
44 fn gen_buffer_init(&self, ext_cx: ext_ctxt) -> @ast::expr;
45 fn gen_init_bounded(&self, ext_cx: ext_ctxt) -> @ast::expr;
48 pub impl gen_send for message {
49 fn gen_send(&self, cx: ext_ctxt, try: bool) -> @ast::item {
50 debug!("pipec: gen_send");
52 message(ref _id, span, tys, this,
53 Some(next_state {state: ref next, tys: next_tys})) => {
54 debug!("pipec: next state exists");
55 let next = this.proto.get_state((*next));
56 assert next_tys.len() == next.ty_params.len();
57 let arg_names = tys.mapi(|i, _ty| cx.ident_of(~"x_"+i.to_str()));
59 let args_ast = (arg_names, tys).map(
63 let pipe_ty = cx.ty_path_ast_builder(
64 path(~[this.data_name()], span)
65 .add_tys(cx.ty_vars_global(this.ty_params)));
66 let args_ast = vec::append(
67 ~[cx.arg(cx.ident_of(~"pipe"),
71 let mut body = ~"{\n";
72 body += fmt!("use super::%s;\n", self.name());
74 if this.proto.is_bounded() {
75 let (sp, rp) = match (this.dir, next.dir) {
76 (send, send) => (~"c", ~"s"),
77 (send, recv) => (~"s", ~"c"),
78 (recv, send) => (~"s", ~"c"),
79 (recv, recv) => (~"c", ~"s")
82 body += ~"let b = pipe.reuse_buffer();\n";
83 body += fmt!("let %s = ::pipes::SendPacketBuffered(\
84 ::ptr::addr_of(&(b.buffer.data.%s)));\n",
86 body += fmt!("let %s = ::pipes::RecvPacketBuffered(\
87 ::ptr::addr_of(&(b.buffer.data.%s)));\n",
91 let pat = match (this.dir, next.dir) {
92 (send, send) => "(c, s)",
93 (send, recv) => "(s, c)",
94 (recv, send) => "(s, c)",
95 (recv, recv) => "(c, s)"
98 body += fmt!("let %s = ::pipes::entangle();\n", pat);
100 body += fmt!("let message = %s(%s);\n",
102 str::connect(vec::append_one(
103 arg_names.map(|x| cx.str_of(*x)),
107 body += fmt!("::pipes::send(pipe, message);\n");
108 // return the new channel
112 body += fmt!("if ::pipes::send(pipe, message) {\n \
113 ::pipes::rt::make_some(c) \
114 } else { ::pipes::rt::make_none() } }");
117 let body = cx.parse_expr(body);
119 let mut rty = cx.ty_path_ast_builder(path(~[next.data_name()],
123 rty = cx.ty_option(rty);
126 let name = cx.ident_of(if try { ~"try_" + self.name()
127 } else { self.name() } );
129 cx.item_fn_poly(name,
136 message(ref _id, span, tys, this, None) => {
137 debug!("pipec: no next state");
138 let arg_names = tys.mapi(|i, _ty| (~"x_" + i.to_str()));
140 let args_ast = (arg_names, tys).map(
141 |n, t| cx.arg(cx.ident_of(*n), *t)
144 let args_ast = vec::append(
145 ~[cx.arg(cx.ident_of(~"pipe"),
146 cx.ty_path_ast_builder(
147 path(~[this.data_name()], span)
148 .add_tys(cx.ty_vars_global(
152 let message_args = if arg_names.len() == 0 {
156 ~"(" + str::connect(arg_names.map(|x| *x),
160 let mut body = ~"{ ";
161 body += fmt!("use super::%s;\n", self.name());
162 body += fmt!("let message = %s%s;\n",
167 body += fmt!("::pipes::send(pipe, message);\n");
170 body += fmt!("if ::pipes::send(pipe, message) \
172 ::pipes::rt::make_some(()) \
174 ::pipes::rt::make_none() \
178 let body = cx.parse_expr(body);
181 ~"try_" + self.name()
183 else { self.name() };
185 cx.item_fn_poly(cx.ident_of(name),
188 cx.ty_option(cx.ty_nil_ast_builder())
190 cx.ty_nil_ast_builder()
198 fn to_ty(&self, cx: ext_ctxt) -> @ast::Ty {
199 cx.ty_path_ast_builder(path(~[cx.ident_of(self.name())], self.span())
200 .add_tys(cx.ty_vars_global(self.get_params())))
204 pub impl to_type_decls for state {
205 fn to_type_decls(&self, cx: ext_ctxt) -> ~[@ast::item] {
206 debug!("pipec: to_type_decls");
207 // This compiles into two different type declarations. Say the
208 // state is called ping. This will generate both `ping` and
209 // `ping_message`. The first contains data that the user cares
210 // about. The second is the same thing, but extended with a
211 // next packet pointer, which is used under the covers.
213 let name = self.data_name();
215 let mut items_msg = ~[];
217 for self.messages.each |m| {
218 let message(name, span, tys, this, next) = *m;
220 let tys = match next {
221 Some(next_state { state: ref next, tys: next_tys }) => {
222 let next = this.proto.get_state((*next));
223 let next_name = cx.str_of(next.data_name());
225 let dir = match this.dir {
231 cx.ty_path_ast_builder(
232 path(~[cx.ident_of(dir),
233 cx.ident_of(next_name)], span)
239 let v = cx.variant(cx.ident_of(name), span, tys);
248 ast::enum_def(enum_def_ {
251 cx.strip_bounds(self.ty_params)
256 fn to_endpoint_decls(&self, cx: ext_ctxt, dir: direction) -> ~[@ast::item] {
257 debug!("pipec: to_endpoint_decls");
258 let dir = match dir {
260 recv => (*self).dir.reverse()
263 for self.messages.each |m| {
265 items.push(m.gen_send(cx, true));
266 items.push(m.gen_send(cx, false));
270 if !self.proto.is_bounded() {
275 cx.ty_path_ast_builder(
276 path_global(~[cx.ident_of(~"pipes"),
277 cx.ident_of(dir.to_str() + ~"Packet")],
279 .add_ty(cx.ty_path_ast_builder(
280 path(~[cx.ident_of(~"super"),
283 .add_tys(cx.ty_vars_global(self.ty_params))))),
284 cx.strip_bounds(self.ty_params)));
291 cx.ty_path_ast_builder(
292 path_global(~[cx.ident_of(~"pipes"),
293 cx.ident_of(dir.to_str()
294 + ~"PacketBuffered")],
296 .add_tys(~[cx.ty_path_ast_builder(
297 path(~[cx.ident_of(~"super"),
300 .add_tys(cx.ty_vars_global(self.ty_params))),
301 self.proto.buffer_ty_path(cx)])),
302 cx.strip_bounds(self.ty_params)));
308 pub impl gen_init for protocol {
309 fn gen_init(&self, cx: ext_ctxt) -> @ast::item {
313 let start_state = self.states[0];
315 let body = if !self.is_bounded() {
316 match start_state.dir {
317 send => quote_expr!( ::pipes::entangle() ),
320 let (s, c) = ::pipes::entangle();
327 let body = self.gen_init_bounded(ext_cx);
328 match start_state.dir {
339 cx.parse_item(fmt!("pub fn init%s() -> (client::%s, server::%s)\
340 { use pipes::HasBuffer; %s }",
341 start_state.ty_params.to_source(cx),
342 start_state.to_ty(cx).to_source(cx),
343 start_state.to_ty(cx).to_source(cx),
347 fn gen_buffer_init(&self, ext_cx: ext_ctxt) -> @ast::expr {
348 ext_cx.struct_expr(path(~[ext_cx.ident_of(~"__Buffer")],
350 self.states.map_to_vec(|s| {
351 let fty = s.to_ty(ext_cx);
352 ext_cx.field_imm(ext_cx.ident_of(s.name),
354 ::pipes::mk_packet::<$fty>()
359 fn gen_init_bounded(&self, ext_cx: ext_ctxt) -> @ast::expr {
360 debug!("gen_init_bounded");
361 let buffer_fields = self.gen_buffer_init(ext_cx);
362 let buffer = quote_expr!(~::pipes::Buffer {
363 header: ::pipes::BufferHeader(),
364 data: $buffer_fields,
367 let entangle_body = ext_cx.block_expr(
369 self.states.map_to_vec(
370 |s| ext_cx.parse_stmt(
371 fmt!("data.%s.set_buffer(buffer)",
374 fmt!("::ptr::addr_of(&(data.%s))",
375 self.states[0].name))));
378 let buffer = $buffer;
379 do ::pipes::entangle_buffer(buffer) |buffer, data| {
385 fn buffer_ty_path(&self, cx: ext_ctxt) -> @ast::Ty {
386 let mut params: ~[ast::ty_param] = ~[];
387 for (copy self.states).each |s| {
388 for s.ty_params.each |tp| {
389 match params.find(|tpp| tp.ident == tpp.ident) {
390 None => params.push(*tp),
396 cx.ty_path_ast_builder(path(~[cx.ident_of(~"super"),
397 cx.ident_of(~"__Buffer")], self.span)
398 .add_tys(cx.ty_vars_global(params)))
401 fn gen_buffer_type(&self, cx: ext_ctxt) -> @ast::item {
403 let mut params: ~[ast::ty_param] = ~[];
404 let fields = do (copy self.states).map_to_vec |s| {
405 for s.ty_params.each |tp| {
406 match params.find(|tpp| tp.ident == tpp.ident) {
407 None => params.push(*tp),
411 let ty = s.to_ty(cx);
412 let fty = quote_ty!( ::pipes::Packet<$ty> );
415 node: ast::struct_field_ {
416 kind: ast::named_field(
418 ast::struct_immutable,
428 cx.ident_of(~"__Buffer"),
435 cx.strip_bounds(params))
438 fn compile(&self, cx: ext_ctxt) -> @ast::item {
439 let mut items = ~[self.gen_init(cx)];
440 let mut client_states = ~[];
441 let mut server_states = ~[];
443 for (copy self.states).each |s| {
444 items += s.to_type_decls(cx);
446 client_states += s.to_endpoint_decls(cx, send);
447 server_states += s.to_endpoint_decls(cx, recv);
450 if self.is_bounded() {
451 items.push(self.gen_buffer_type(cx))
454 items.push(cx.item_mod(cx.ident_of(~"client"),
457 items.push(cx.item_mod(cx.ident_of(~"server"),
461 cx.item_mod(cx.ident_of(self.name), self.span, items)