<commit_before>/* Code to handle method lookups (which can be quite complex) */

import syntax::ast_map;
import middle::typeck::infer::methods; // next_ty_vars
import dvec::{dvec, extensions};

type candidate = {
    self_ty: ty::t,          // type of a in a.b()
    self_substs: ty::substs, // values for any tvars def'd on the class
    rcvr_ty: ty::t,          // type of receiver in the method def
    n_tps_m: uint,           // number of tvars defined on the method
    fty: ty::t,              // type of the method
    entry: method_map_entry
};

class lookup {
    let fcx: @fn_ctxt;
    let expr: @ast::expr;
    let self_expr: @ast::expr;
    let borrow_scope: ast::node_id;
    let node_id: ast::node_id;
    let m_name: ast::ident;
    let mut self_ty: ty::t;
    let mut derefs: uint;
    let candidates: dvec<candidate>;
    let supplied_tps: [ty::t];
    let include_private: bool;

    new(fcx: @fn_ctxt,
        expr: @ast::expr,           //expr for a.b in a.b()
        self_expr: @ast::expr,      //a in a.b(...)
        borrow_scope: ast::node_id, //scope to borrow the expr for
        node_id: ast::node_id,      //node id where to store type of fn
        m_name: ast::ident,         //b in a.b(...)
        self_ty: ty::t,             //type of a in a.b(...)
        supplied_tps: [ty::t],      //Xs in a.b::<Xs>(...)
        include_private: bool) {

        self.fcx = fcx;
        self.expr = expr;
        self.self_expr = self_expr;
        self.borrow_scope = borrow_scope;
        self.node_id = node_id;
        self.m_name = m_name;
        self.self_ty = self_ty;
        self.derefs = 0u;
        self.candidates = dvec();
        self.supplied_tps = supplied_tps;
        self.include_private = include_private;
    }

    // Entrypoint:
    fn method() -> option<method_map_entry> {
        #debug["method lookup(m_name=%s, self_ty=%s)",
               *self.m_name, self.fcx.infcx.ty_to_str(self.self_ty)];

        loop {
            // First, see whether this is an interface-bounded parameter
            alt ty::get(self.self_ty).struct {
              ty::ty_param(n, did) {
                self.add_candidates_from_param(n, did);
              }
              ty::ty_iface(did, substs) {
                self.add_candidates_from_iface(did, substs);
              }
              ty::ty_class(did, substs) {
                self.add_candidates_from_class(did, substs);
              }
              _ { }
            }

            // if we found anything, stop now.  otherwise continue to
            // loop for impls in scope.  Note: I don't love these
            // semantics, but that's what we had so I am preserving
            // it.
            if self.candidates.len() > 0u {
                break;
            }

            self.add_candidates_from_scope();

            // if we found anything, stop before attempting auto-deref.
            if self.candidates.len() > 0u {
                break;
            }

            // check whether we can autoderef and if so loop around again.
            alt ty::deref(self.tcx(), self.self_ty, false) {
              none { break; }
              some(mt) {
                self.self_ty = mt.ty;
                self.derefs += 1u;
              }
            }
        }

        if self.candidates.len() == 0u { ret none; }

        if self.candidates.len() > 1u {
            self.tcx().sess.span_err(
                self.expr.span,
                "multiple applicable methods in scope");

            for self.candidates.eachi { |i, candidate|
                alt candidate.entry.origin {
                  method_static(did) {
                    self.report_static_candidate(i, did);
                  }
                  method_param(p) {
                    self.report_param_candidate(i, p.iface_id);
                  }
                  method_iface(did, _) {
                    self.report_iface_candidate(i, did);
                  }
                }
            }
        }

        some(self.write_mty_from_candidate(self.candidates[0u]))
    }

    fn tcx() -> ty::ctxt { self.fcx.ccx.tcx }

    fn report_static_candidate(idx: uint, did: ast::def_id) {
        let span = if did.crate == ast::local_crate {
            alt check self.tcx().items.get(did.node) {
              ast_map::node_method(m, _, _) { m.span }
            }
        } else {
            self.expr.span
        };
        self.tcx().sess.span_note(
            span,
            #fmt["candidate #%u is `%s`",
                 (idx+1u),
                 ty::item_path_str(self.tcx(), did)]);
    }

    fn report_param_candidate(idx: uint, did: ast::def_id) {
        self.tcx().sess.span_note(
            self.expr.span,
            #fmt["candidate #%u derives from the bound `%s`",
                 (idx+1u),
                 ty::item_path_str(self.tcx(), did)]);
    }

    fn report_iface_candidate(idx: uint, did: ast::def_id) {
        self.tcx().sess.span_note(
            self.expr.span,
            #fmt["candidate #%u derives from the type of the receiver, \
                  which is the iface `%s`",
                 (idx+1u),
                 ty::item_path_str(self.tcx(), did)]);
    }

    fn add_candidates_from_param(n: uint, did: ast::def_id) {
        let tcx = self.tcx();
        let mut iface_bnd_idx = 0u; // count only iface bounds
        let bounds = tcx.ty_param_bounds.get(did.node);
        for vec::each(*bounds) {|bound|
            let (iid, bound_substs) = alt bound {
              ty::bound_copy | ty::bound_send | ty::bound_const {
                cont; /* ok */
              }
              ty::bound_iface(bound_t) {
                alt check ty::get(bound_t).struct {
                  ty::ty_iface(i, substs) { (i, substs) }
                }
              }
            };

            let ifce_methods = ty::iface_methods(tcx, iid);
            alt vec::position(*ifce_methods, {|m| m.ident == self.m_name}) {
              none {
                /* check next bound */
                iface_bnd_idx += 1u;
              }

              some(pos) {
                // Replace any appearance of `self` with the type of the
                // generic parameter itself.  Note that this is the only case
                // where this replacement is necessary: in all other cases, we
                // are either invoking a method directly from an impl or class
                // (where the self type is not permitted), or from a iface
                // type (in which case methods that refer to self are not
                // permitted).
                let substs = {self_ty: some(self.self_ty)
                              with bound_substs};

                self.add_candidates_from_m(
                    substs, ifce_methods[pos],
                    method_param({iface_id:iid,
                                  method_num:pos,
                                  param_num:n,
                                  bound_num:iface_bnd_idx}));
              }
            }
        }

    }

    fn add_candidates_from_iface(did: ast::def_id, iface_substs: ty::substs) {

        #debug["method_from_iface"];

        let ms = *ty::iface_methods(self.tcx(), did);
        for ms.eachi {|i, m|
            if m.ident != self.m_name { cont; }

            let m_fty = ty::mk_fn(self.tcx(), m.fty);

            if ty::type_has_self(m_fty) {
                self.tcx().sess.span_err(
                    self.expr.span,
                    "can not call a method that contains a \
                     self type through a boxed iface");
            }

            if (*m.tps).len() > 0u {
                self.tcx().sess.span_err(
                    self.expr.span,
                    "can not call a generic method through a \
                     boxed iface");
            }

            // Note: although it is illegal to invoke a method that uses self
            // through a iface instance, we use a dummy subst here so that we
            // can soldier on with the compilation.
            let substs = {self_ty: some(self.self_ty)
                          with iface_substs};

            self.add_candidates_from_m(
                substs, m, method_iface(did, i));
        }
    }

    fn add_candidates_from_class(did: ast::def_id, class_substs: ty::substs) {

        #debug["method_from_class"];

        let ms = *ty::iface_methods(self.tcx(), did);

        for ms.each {|m|
            if m.ident != self.m_name { cont; }

            if m.vis == ast::private && !self.include_private {
                self.tcx().sess.span_fatal(
                    self.expr.span,
                    "Call to private method not allowed outside \
                     its defining class");
            }

            // look up method named <name>.
            let m_declared = ty::lookup_class_method_by_name(
                self.tcx(), did, self.m_name, self.expr.span);

            self.add_candidates_from_m(
                class_substs, m, method_static(m_declared));
        }
    }

    fn ty_from_did(did: ast::def_id) -> ty::t {
        alt check ty::get(ty::lookup_item_type(self.tcx(), did).ty).struct {
          ty::ty_fn(fty) {
            ty::mk_fn(self.tcx(), {proto: ast::proto_box with fty})
          }
        }
        /*
        if did.crate == ast::local_crate {
            alt check self.tcx().items.get(did.node) {
              ast_map::node_method(m, _, _) {
                // NDM iface/impl regions
                let mt = ty_of_method(self.fcx.ccx, m, ast::rp_none);
                ty::mk_fn(self.tcx(), {proto: ast::proto_box with mt.fty})
              }
            }
        } else {
            alt check ty::get(csearch::get_type(self.tcx(), did).ty).struct {
              ty::ty_fn(fty) {
                ty::mk_fn(self.tcx(), {proto: ast::proto_box with fty})
              }
            }
        }
        */
    }

    fn add_candidates_from_scope() {
        let impls_vecs = self.fcx.ccx.impl_map.get(self.expr.id);
        let mut added_any = false;

        #debug["method_from_scope"];

        for list::each(impls_vecs) {|impls|
            for vec::each(*impls) {|im|
                // Check whether this impl has a method with the right name.
                for im.methods.find({|m| m.ident == self.m_name}).each {|m|

                    // determine the `self` of the impl with fresh
                    // variables for each parameter:
                    let {substs: impl_substs, ty: impl_ty} =
                        impl_self_ty(self.fcx, im.did);

                    // if we can assign the caller to the callee, that's a
                    // potential match.  Collect those in the vector.
                    let can_assign = self.fcx.can_mk_assignty(
                        self.self_expr, self.borrow_scope,
                        self.self_ty, impl_ty);
                    #debug["can_assign = %?", can_assign];
                    alt can_assign {
                      result::err(_) { /* keep looking */ }
                      result::ok(_) {
                        let fty = self.ty_from_did(m.did);
                        self.candidates.push(
                            {self_ty: self.self_ty,
                             self_substs: impl_substs,
                             rcvr_ty: impl_ty,
                             n_tps_m: m.n_tps,
                             fty: fty,
                             entry: {derefs: self.derefs,
                                     origin: method_static(m.did)}});
                        added_any = true;
                      }
                    }
                }
            }

            // we want to find the innermost scope that has any
            // matches and then ignore outer scopes
            if added_any {ret;}
        }
    }

    fn add_candidates_from_m(self_substs: ty::substs,
                             m: ty::method,
                             origin: method_origin) {
        let tcx = self.fcx.ccx.tcx;

        // a bit hokey, but the method unbound has a bare protocol, whereas
        // a.b has a protocol like fn@() (perhaps eventually fn&()):
        let fty = ty::mk_fn(tcx, {proto: ast::proto_box with m.fty});

        self.candidates.push(
            {self_ty: self.self_ty,
             self_substs: self_substs,
             rcvr_ty: self.self_ty,
             n_tps_m: (*m.tps).len(),
             fty: fty,
             entry: {derefs: self.derefs, origin: origin}});
    }

    fn write_mty_from_candidate(cand: candidate) -> method_map_entry {
        let tcx = self.fcx.ccx.tcx;

        #debug["write_mty_from_candidate(n_tps_m=%u, fty=%s, entry=%?)",
               cand.n_tps_m,
               self.fcx.infcx.ty_to_str(cand.fty),
               cand.entry];

        // Make the actual receiver type (cand.self_ty) assignable to the
        // required receiver type (cand.rcvr_ty).  If this method is not
        // from an impl, this'll basically be a no-nop.
        alt self.fcx.mk_assignty(self.self_expr, self.borrow_scope,
                                 cand.self_ty, cand.rcvr_ty) {
          result::ok(_) {}
          result::err(_) {
            self.tcx().sess.span_bug(
                self.expr.span,
                #fmt["%s was assignable to %s but now is not?",
                     self.fcx.infcx.ty_to_str(cand.self_ty),
                     self.fcx.infcx.ty_to_str(cand.rcvr_ty)]);
          }
        }

        // Construct the full set of type parameters for the method,
        // which is equal to the class tps + the method tps.
        let n_tps_supplied = self.supplied_tps.len();
        let n_tps_m = cand.n_tps_m;
        let m_substs = {
            if n_tps_supplied == 0u {
                self.fcx.infcx.next_ty_vars(n_tps_m)
            } else if n_tps_m == 0u {
                tcx.sess.span_err(
                    self.expr.span,
                    "this method does not take type parameters");
                self.fcx.infcx.next_ty_vars(n_tps_m)
            } else if n_tps_supplied != n_tps_m {
                tcx.sess.span_err(
                    self.expr.span,
                    "incorrect number of type \
                     parameters given for this method");
                self.fcx.infcx.next_ty_vars(n_tps_m)
            } else {
                self.supplied_tps
            }
        };

        let all_substs = {tps: cand.self_substs.tps + m_substs
                          with cand.self_substs};

        self.fcx.write_ty_substs(self.node_id, cand.fty, all_substs);

        ret cand.entry;
    }
}

<commit_msg>Move vector addition out of trans and into libcore.<commit_after>/* Code to handle method lookups (which can be quite complex) */

import syntax::ast_map;
import middle::typeck::infer::methods; // next_ty_vars
import dvec::{dvec, extensions};

type candidate = {
    self_ty: ty::t,          // type of a in a.b()
    self_substs: ty::substs, // values for any tvars def'd on the class
    rcvr_ty: ty::t,          // type of receiver in the method def
    n_tps_m: uint,           // number of tvars defined on the method
    fty: ty::t,              // type of the method
    entry: method_map_entry
};

class lookup {
    let fcx: @fn_ctxt;
    let expr: @ast::expr;
    let self_expr: @ast::expr;
    let borrow_scope: ast::node_id;
    let node_id: ast::node_id;
    let m_name: ast::ident;
    let mut self_ty: ty::t;
    let mut derefs: uint;
    let candidates: dvec<candidate>;
    let supplied_tps: [ty::t];
    let include_private: bool;

    new(fcx: @fn_ctxt,
        expr: @ast::expr,           //expr for a.b in a.b()
        self_expr: @ast::expr,      //a in a.b(...)
        borrow_scope: ast::node_id, //scope to borrow the expr for
        node_id: ast::node_id,      //node id where to store type of fn
        m_name: ast::ident,         //b in a.b(...)
        self_ty: ty::t,             //type of a in a.b(...)
        supplied_tps: [ty::t],      //Xs in a.b::<Xs>(...)
        include_private: bool) {

        self.fcx = fcx;
        self.expr = expr;
        self.self_expr = self_expr;
        self.borrow_scope = borrow_scope;
        self.node_id = node_id;
        self.m_name = m_name;
        self.self_ty = self_ty;
        self.derefs = 0u;
        self.candidates = dvec();
        self.supplied_tps = supplied_tps;
        self.include_private = include_private;
    }

    // Entrypoint:
    fn method() -> option<method_map_entry> {
        #debug["method lookup(m_name=%s, self_ty=%s)",
               *self.m_name, self.fcx.infcx.ty_to_str(self.self_ty)];

        loop {
            // First, see whether this is an interface-bounded parameter
            alt ty::get(self.self_ty).struct {
              ty::ty_param(n, did) {
                self.add_candidates_from_param(n, did);
              }
              ty::ty_iface(did, substs) {
                self.add_candidates_from_iface(did, substs);
              }
              ty::ty_class(did, substs) {
                self.add_candidates_from_class(did, substs);
              }
              _ { }
            }

            // if we found anything, stop now.  otherwise continue to
            // loop for impls in scope.  Note: I don't love these
            // semantics, but that's what we had so I am preserving
            // it.
            if self.candidates.len() > 0u {
                break;
            }

            self.add_candidates_from_scope();

            // if we found anything, stop before attempting auto-deref.
            if self.candidates.len() > 0u {
                break;
            }

            // check whether we can autoderef and if so loop around again.
            alt ty::deref(self.tcx(), self.self_ty, false) {
              none { break; }
              some(mt) {
                self.self_ty = mt.ty;
                self.derefs += 1u;
              }
            }
        }

        if self.candidates.len() == 0u { ret none; }

        if self.candidates.len() > 1u {
            self.tcx().sess.span_err(
                self.expr.span,
                "multiple applicable methods in scope");

            for self.candidates.eachi { |i, candidate|
                alt candidate.entry.origin {
                  method_static(did) {
                    self.report_static_candidate(i, did);
                  }
                  method_param(p) {
                    self.report_param_candidate(i, p.iface_id);
                  }
                  method_iface(did, _) {
                    self.report_iface_candidate(i, did);
                  }
                }
            }
        }

        some(self.write_mty_from_candidate(self.candidates[0u]))
    }

    fn tcx() -> ty::ctxt { self.fcx.ccx.tcx }

    fn report_static_candidate(idx: uint, did: ast::def_id) {
        let span = if did.crate == ast::local_crate {
            alt check self.tcx().items.get(did.node) {
              ast_map::node_method(m, _, _) { m.span }
            }
        } else {
            self.expr.span
        };
        self.tcx().sess.span_note(
            span,
            #fmt["candidate #%u is `%s`",
                 (idx+1u),
                 ty::item_path_str(self.tcx(), did)]);
    }

    fn report_param_candidate(idx: uint, did: ast::def_id) {
        self.tcx().sess.span_note(
            self.expr.span,
            #fmt["candidate #%u derives from the bound `%s`",
                 (idx+1u),
                 ty::item_path_str(self.tcx(), did)]);
    }

    fn report_iface_candidate(idx: uint, did: ast::def_id) {
        self.tcx().sess.span_note(
            self.expr.span,
            #fmt["candidate #%u derives from the type of the receiver, \
                  which is the iface `%s`",
                 (idx+1u),
                 ty::item_path_str(self.tcx(), did)]);
    }

    fn add_candidates_from_param(n: uint, did: ast::def_id) {
        #debug["candidates_from_param"];

        let tcx = self.tcx();
        let mut iface_bnd_idx = 0u; // count only iface bounds
        let bounds = tcx.ty_param_bounds.get(did.node);
        for vec::each(*bounds) {|bound|
            let (iid, bound_substs) = alt bound {
              ty::bound_copy | ty::bound_send | ty::bound_const {
                cont; /* ok */
              }
              ty::bound_iface(bound_t) {
                alt check ty::get(bound_t).struct {
                  ty::ty_iface(i, substs) { (i, substs) }
                }
              }
            };

            let ifce_methods = ty::iface_methods(tcx, iid);
            alt vec::position(*ifce_methods, {|m| m.ident == self.m_name}) {
              none {
                /* check next bound */
                iface_bnd_idx += 1u;
              }

              some(pos) {
                // Replace any appearance of `self` with the type of the
                // generic parameter itself.  Note that this is the only case
                // where this replacement is necessary: in all other cases, we
                // are either invoking a method directly from an impl or class
                // (where the self type is not permitted), or from a iface
                // type (in which case methods that refer to self are not
                // permitted).
                let substs = {self_ty: some(self.self_ty)
                              with bound_substs};

                self.add_candidates_from_m(
                    substs, ifce_methods[pos],
                    method_param({iface_id:iid,
                                  method_num:pos,
                                  param_num:n,
                                  bound_num:iface_bnd_idx}));
              }
            }
        }

    }

    fn add_candidates_from_iface(did: ast::def_id, iface_substs: ty::substs) {

        #debug["method_from_iface"];

        let ms = *ty::iface_methods(self.tcx(), did);
        for ms.eachi {|i, m|
            if m.ident != self.m_name { cont; }

            let m_fty = ty::mk_fn(self.tcx(), m.fty);

            if ty::type_has_self(m_fty) {
                self.tcx().sess.span_err(
                    self.expr.span,
                    "can not call a method that contains a \
                     self type through a boxed iface");
            }

            if (*m.tps).len() > 0u {
                self.tcx().sess.span_err(
                    self.expr.span,
                    "can not call a generic method through a \
                     boxed iface");
            }

            // Note: although it is illegal to invoke a method that uses self
            // through a iface instance, we use a dummy subst here so that we
            // can soldier on with the compilation.
            let substs = {self_ty: some(self.self_ty)
                          with iface_substs};

            self.add_candidates_from_m(
                substs, m, method_iface(did, i));
        }
    }

    fn add_candidates_from_class(did: ast::def_id, class_substs: ty::substs) {

        #debug["method_from_class"];

        let ms = *ty::iface_methods(self.tcx(), did);

        for ms.each {|m|
            if m.ident != self.m_name { cont; }

            if m.vis == ast::private && !self.include_private {
                self.tcx().sess.span_fatal(
                    self.expr.span,
                    "Call to private method not allowed outside \
                     its defining class");
            }

            // look up method named <name>.
            let m_declared = ty::lookup_class_method_by_name(
                self.tcx(), did, self.m_name, self.expr.span);

            self.add_candidates_from_m(
                class_substs, m, method_static(m_declared));
        }
    }

    fn ty_from_did(did: ast::def_id) -> ty::t {
        alt check ty::get(ty::lookup_item_type(self.tcx(), did).ty).struct {
          ty::ty_fn(fty) {
            ty::mk_fn(self.tcx(), {proto: ast::proto_box with fty})
          }
        }
        /*
        if did.crate == ast::local_crate {
            alt check self.tcx().items.get(did.node) {
              ast_map::node_method(m, _, _) {
                // NDM iface/impl regions
                let mt = ty_of_method(self.fcx.ccx, m, ast::rp_none);
                ty::mk_fn(self.tcx(), {proto: ast::proto_box with mt.fty})
              }
            }
        } else {
            alt check ty::get(csearch::get_type(self.tcx(), did).ty).struct {
              ty::ty_fn(fty) {
                ty::mk_fn(self.tcx(), {proto: ast::proto_box with fty})
              }
            }
        }
        */
    }

    fn add_candidates_from_scope() {
        let impls_vecs = self.fcx.ccx.impl_map.get(self.expr.id);
        let mut added_any = false;

        #debug["method_from_scope"];

        for list::each(impls_vecs) {|impls|
            for vec::each(*impls) {|im|
                // Check whether this impl has a method with the right name.
                for im.methods.find({|m| m.ident == self.m_name}).each {|m|

                    // determine the `self` of the impl with fresh
                    // variables for each parameter:
                    let {substs: impl_substs, ty: impl_ty} =
                        impl_self_ty(self.fcx, im.did);

                    // if we can assign the caller to the callee, that's a
                    // potential match.  Collect those in the vector.
                    let can_assign = self.fcx.can_mk_assignty(
                        self.self_expr, self.borrow_scope,
                        self.self_ty, impl_ty);
                    #debug["can_assign = %?", can_assign];
                    alt can_assign {
                      result::err(_) { /* keep looking */ }
                      result::ok(_) {
                        let fty = self.ty_from_did(m.did);
                        self.candidates.push(
                            {self_ty: self.self_ty,
                             self_substs: impl_substs,
                             rcvr_ty: impl_ty,
                             n_tps_m: m.n_tps,
                             fty: fty,
                             entry: {derefs: self.derefs,
                                     origin: method_static(m.did)}});
                        added_any = true;
                      }
                    }
                }
            }

            // we want to find the innermost scope that has any
            // matches and then ignore outer scopes
            if added_any {ret;}
        }
    }

    fn add_candidates_from_m(self_substs: ty::substs,
                             m: ty::method,
                             origin: method_origin) {
        let tcx = self.fcx.ccx.tcx;

        // a bit hokey, but the method unbound has a bare protocol, whereas
        // a.b has a protocol like fn@() (perhaps eventually fn&()):
        let fty = ty::mk_fn(tcx, {proto: ast::proto_box with m.fty});

        self.candidates.push(
            {self_ty: self.self_ty,
             self_substs: self_substs,
             rcvr_ty: self.self_ty,
             n_tps_m: (*m.tps).len(),
             fty: fty,
             entry: {derefs: self.derefs, origin: origin}});
    }

    fn write_mty_from_candidate(cand: candidate) -> method_map_entry {
        let tcx = self.fcx.ccx.tcx;

        #debug["write_mty_from_candidate(n_tps_m=%u, fty=%s, entry=%?)",
               cand.n_tps_m,
               self.fcx.infcx.ty_to_str(cand.fty),
               cand.entry];

        // Make the actual receiver type (cand.self_ty) assignable to the
        // required receiver type (cand.rcvr_ty).  If this method is not
        // from an impl, this'll basically be a no-nop.
        alt self.fcx.mk_assignty(self.self_expr, self.borrow_scope,
                                 cand.self_ty, cand.rcvr_ty) {
          result::ok(_) {}
          result::err(_) {
            self.tcx().sess.span_bug(
                self.expr.span,
                #fmt["%s was assignable to %s but now is not?",
                     self.fcx.infcx.ty_to_str(cand.self_ty),
                     self.fcx.infcx.ty_to_str(cand.rcvr_ty)]);
          }
        }

        // Construct the full set of type parameters for the method,
        // which is equal to the class tps + the method tps.
        let n_tps_supplied = self.supplied_tps.len();
        let n_tps_m = cand.n_tps_m;
        let m_substs = {
            if n_tps_supplied == 0u {
                self.fcx.infcx.next_ty_vars(n_tps_m)
            } else if n_tps_m == 0u {
                tcx.sess.span_err(
                    self.expr.span,
                    "this method does not take type parameters");
                self.fcx.infcx.next_ty_vars(n_tps_m)
            } else if n_tps_supplied != n_tps_m {
                tcx.sess.span_err(
                    self.expr.span,
                    "incorrect number of type \
                     parameters given for this method");
                self.fcx.infcx.next_ty_vars(n_tps_m)
            } else {
                self.supplied_tps
            }
        };

        let all_substs = {tps: cand.self_substs.tps + m_substs
                          with cand.self_substs};

        self.fcx.write_ty_substs(self.node_id, cand.fty, all_substs);

        ret cand.entry;
    }
}

<|endoftext|>


<commit_before><commit_msg>Fix libimagcontact for new StoreId interface with Entries iterator<commit_after><|endoftext|>


<commit_before><commit_msg>Add debug output<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #37124 - nikomatsakis:incr-comp-benchmark, r=michaelwoerister<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test where we change the body of a private method in an impl.
// We then test what sort of functions must be rebuilt as a result.

// revisions:rpass1 rpass2
// compile-flags: -Z query-dep-graph

#![feature(rustc_attrs)]
#![feature(stmt_expr_attributes)]
#![allow(dead_code)]

#![rustc_partition_translated(module="struct_point-point", cfg="rpass2")]

// FIXME(#37121) -- the following two modules *should* be reused but are not
#![rustc_partition_translated(module="struct_point-fn_calls_methods_in_same_impl", cfg="rpass2")]
#![rustc_partition_translated(module="struct_point-fn_calls_methods_in_another_impl", cfg="rpass2")]
#![rustc_partition_reused(module="struct_point-fn_make_struct", cfg="rpass2")]
#![rustc_partition_reused(module="struct_point-fn_read_field", cfg="rpass2")]
#![rustc_partition_reused(module="struct_point-fn_write_field", cfg="rpass2")]

mod point {
    pub struct Point {
        pub x: f32,
        pub y: f32,
    }

    impl Point {
        fn distance_squared(&self) -> f32 {
            #[cfg(rpass1)]
            return self.x + self.y;

            #[cfg(rpass2)]
            return self.x * self.x + self.y * self.y;
        }

        pub fn distance_from_origin(&self) -> f32 {
            self.distance_squared().sqrt()
        }
    }

    impl Point {
        pub fn translate(&mut self, x: f32, y: f32) {
            self.x += x;
            self.y += y;
        }
    }

}

/// A fn item that calls (public) methods on `Point` from the same impl which changed
mod fn_calls_methods_in_same_impl {
    use point::Point;

    // FIXME(#37121) -- we should not need to typeck this again
    #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")]
    pub fn check() {
        let x = Point { x: 2.0, y: 2.0 };
        x.distance_from_origin();
    }
}

/// A fn item that calls (public) methods on `Point` from another impl
mod fn_calls_methods_in_another_impl {
    use point::Point;

    // FIXME(#37121) -- we should not need to typeck this again
    #[rustc_dirty(label="TypeckItemBody", cfg="rpass2")]
    pub fn check() {
        let mut x = Point { x: 2.0, y: 2.0 };
        x.translate(3.0, 3.0);
    }
}

/// A fn item that makes an instance of `Point` but does not invoke methods
mod fn_make_struct {
    use point::Point;

    #[rustc_clean(label="TypeckItemBody", cfg="rpass2")]
    pub fn make_origin() -> Point {
        Point { x: 2.0, y: 2.0 }
    }
}

/// A fn item that reads fields from `Point` but does not invoke methods
mod fn_read_field {
    use point::Point;

    #[rustc_clean(label="TypeckItemBody", cfg="rpass2")]
    pub fn get_x(p: Point) -> f32 {
        p.x
    }
}

/// A fn item that writes to a field of `Point` but does not invoke methods
mod fn_write_field {
    use point::Point;

    #[rustc_clean(label="TypeckItemBody", cfg="rpass2")]
    pub fn inc_x(p: &mut Point) {
        p.x += 1.0;
    }
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Comments!<commit_after><|endoftext|>


<commit_before>pub use std::mem::uninitialized;
pub use std::collections::TreeMap;
pub use http::server::response::ResponseWriter;
pub use http::headers::response::HeaderCollection;
pub use iron::*;
pub use super::*;
pub use super::headers::*;
pub use super::super::cookie::*;
use serialize::json::Json;

pub fn get_cookie<'a>(headers: HeaderCollection, secret: Option<String>, key: &str, value: &str) -> String {
    let mut res = unsafe{ ResponseWriter::new(uninitialized()) };
    let signer = Cookie::new(secret);
    let cookie = (key.to_string(), value.to_string());
    res.set_cookie(&signer, cookie, headers);
    res.headers.extensions.find(&"Set-Cookie".to_string()).unwrap().clone()
}

pub fn get_json_cookie<'a>(headers: HeaderCollection, secret: Option<String>, key: &str, value: &Json) -> String {
    let mut res = unsafe{ ResponseWriter::new(uninitialized()) };
    let signer = Cookie::new(secret);
    let cookie = (key.to_string(), value.clone());
    res.set_json_cookie(&signer, cookie, headers);
    res.headers.extensions.find(&"Set-Cookie".to_string()).unwrap().clone()
}

#[test]
fn check_cookie() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_cookie(headers, None, "thing", "thing"), "thing=thing".to_string());
}

#[test]
fn check_escaping() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_cookie(headers, None, "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'", "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'"),
        "~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27=\
         ~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27".to_string());
}

#[test]
fn check_headers() {
    let mut headers = HeaderCollection {
        expires:    None,
        max_age:    Some(42),
        domain:     Some("example.com".to_string()),
        path:       Some("/a/path".to_string()),
        secure:     true,
        http_only:  true,
        extensions: Some(TreeMap::<String, Option<String>>::new())
    };
    headers.extensions.as_mut().unwrap().insert("foo".to_string(), Some("bar".to_string()));
    headers.extensions.as_mut().unwrap().insert("@zzmp".to_string(), None);
    assert_eq!(get_cookie(headers, None, "thing", "thing"),
        "thing=thing; Max-Age=42; Domain=example.com; Path=/a/path; Secure; Http-Only; @zzmp; foo=bar".to_string());
}

#[test]
fn check_signature() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_cookie(headers, Some("@zzmp".to_string()), "thing", "thung"),
        // Hash of @zzmpthung
        "thing=s:thung.2bc9a8b82a4a393ab67b2b8aaff0e3ab33cb4aca05ef4a0ba201141fbb029f42".to_string());
}

//TO DO
#[test]
fn check_json() {

}

#[test]
fn check_signed_json() {

}
<commit_msg>(test) Json.<commit_after>pub use std::mem::uninitialized;
pub use std::collections::TreeMap;
pub use http::server::response::ResponseWriter;
pub use http::headers::response::HeaderCollection;
pub use iron::*;
pub use super::*;
pub use super::headers::*;
pub use super::super::cookie::*;
use serialize::json::{Json, ToJson};

pub fn get_cookie<'a>(headers: HeaderCollection, secret: Option<String>, key: &str, value: &str) -> String {
    let mut res = unsafe{ ResponseWriter::new(uninitialized()) };
    let signer = Cookie::new(secret);
    let cookie = (key.to_string(), value.to_string());
    res.set_cookie(&signer, cookie, headers);
    res.headers.extensions.find(&"Set-Cookie".to_string()).unwrap().clone()
}

pub fn get_json_cookie<'a>(headers: HeaderCollection, secret: Option<String>, key: &str, value: Json) -> String {
    let mut res = unsafe{ ResponseWriter::new(uninitialized()) };
    let signer = Cookie::new(secret);
    let cookie = (key.to_string(), value);
    res.set_json_cookie(&signer, cookie, headers);
    res.headers.extensions.find(&"Set-Cookie".to_string()).unwrap().clone()
}

#[test]
fn check_cookie() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_cookie(headers, None, "thing", "thing"), "thing=thing".to_string());
}

#[test]
fn check_escaping() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_cookie(headers, None, "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'", "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'"),
        // Url component encoding
        "~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27=\
         ~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27".to_string());
}

#[test]
fn check_headers() {
    let mut headers = HeaderCollection {
        expires:    None,
        max_age:    Some(42),
        domain:     Some("example.com".to_string()),
        path:       Some("/a/path".to_string()),
        secure:     true,
        http_only:  true,
        extensions: Some(TreeMap::<String, Option<String>>::new())
    };
    headers.extensions.as_mut().unwrap().insert("foo".to_string(), Some("bar".to_string()));
    headers.extensions.as_mut().unwrap().insert("@zzmp".to_string(), None);
    assert_eq!(get_cookie(headers, None, "thing", "thing"),
        "thing=thing; Max-Age=42; Domain=example.com; Path=/a/path; Secure; Http-Only; @zzmp; foo=bar".to_string());
}

#[test]
fn check_signature() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_cookie(headers, Some("@zzmp".to_string()), "thing", "thung"),
        // Hash of @zzmpthung
        "thing=s:thung.2bc9a8b82a4a393ab67b2b8aaff0e3ab33cb4aca05ef4a0ba201141fbb029f42".to_string());
}

//TO DO
#[test]
fn check_json() {
    let headers = HeaderCollection::empty();
    assert_eq!(get_json_cookie(headers, None, "thing", "{\"foo\":\"bar\"}".to_string().to_json()),
        // Url component encoded
        "thing=j%3A%22%7B%22foo%22%3A%22bar%22%7D%22".to_string());
}
<|endoftext|>


<commit_before><commit_msg>Add "retrieve" variants for retrieving instances<commit_after><|endoftext|>


<commit_before>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A nice wrapper to consume dataflow results at several CFG
//! locations.

use rustc::mir::{BasicBlock, Location};
use rustc_data_structures::indexed_set::{IdxSetBuf, Iter};
use rustc_data_structures::indexed_vec::Idx;

use dataflow::{BitDenotation, BlockSets, DataflowResults};
use dataflow::move_paths::{HasMoveData, MovePathIndex};

use std::iter;

/// A trait for "cartesian products" of multiple FlowAtLocation.
///
/// There's probably a way to auto-impl this, but I think
/// it is cleaner to have manual visitor impls.
pub trait FlowsAtLocation {
    /// Reset the state bitvector to represent the entry to block `bb`.
    fn reset_to_entry_of(&mut self, bb: BasicBlock);

    /// Build gen + kill sets for statement at `loc`.
    ///
    /// Note that invoking this method alone does not change the
    /// `curr_state` -- you must invoke `apply_local_effect`
    /// afterwards.
    fn reconstruct_statement_effect(&mut self, loc: Location);

    /// Build gen + kill sets for terminator for `loc`.
    ///
    /// Note that invoking this method alone does not change the
    /// `curr_state` -- you must invoke `apply_local_effect`
    /// afterwards.
    fn reconstruct_terminator_effect(&mut self, loc: Location);

    /// Apply current gen + kill sets to `flow_state`.
    ///
    /// (`loc` parameters can be ignored if desired by
    /// client. For the terminator, the `stmt_idx` will be the number
    /// of statements in the block.)
    fn apply_local_effect(&mut self, loc: Location);
}

/// Represents the state of dataflow at a particular
/// CFG location, both before and after it is
/// executed.
///
/// Data flow results are typically computed only as basic block
/// boundaries. A `FlowInProgress` allows you to reconstruct the
/// effects at any point in the control-flow graph by starting with
/// the state at the start of the basic block (`reset_to_entry_of`)
/// and then replaying the effects of statements and terminators
/// (e.g. via `reconstruct_statement_effect` and
/// `reconstruct_terminator_effect`; don't forget to call
/// `apply_local_effect`).
pub struct FlowAtLocation<BD>
where
    BD: BitDenotation,
{
    base_results: DataflowResults<BD>,
    curr_state: IdxSetBuf<BD::Idx>,
    stmt_gen: IdxSetBuf<BD::Idx>,
    stmt_kill: IdxSetBuf<BD::Idx>,
}

impl<BD> FlowAtLocation<BD>
where
    BD: BitDenotation,
{
    /// Iterate over each bit set in the current state.
    pub fn each_state_bit<F>(&self, f: F)
    where
        F: FnMut(BD::Idx),
    {
        self.curr_state.iter().for_each(f)
    }

    /// Iterate over each `gen` bit in the current effect (invoke
    /// `reconstruct_statement_effect` or
    /// `reconstruct_terminator_effect` first).
    pub fn each_gen_bit<F>(&self, f: F)
    where
        F: FnMut(BD::Idx),
    {
        self.stmt_gen.iter().for_each(f)
    }

    pub fn new(results: DataflowResults<BD>) -> Self {
        let bits_per_block = results.sets().bits_per_block();
        let curr_state = IdxSetBuf::new_empty(bits_per_block);
        let stmt_gen = IdxSetBuf::new_empty(bits_per_block);
        let stmt_kill = IdxSetBuf::new_empty(bits_per_block);
        FlowAtLocation {
            base_results: results,
            curr_state: curr_state,
            stmt_gen: stmt_gen,
            stmt_kill: stmt_kill,
        }
    }

    /// Access the underlying operator.
    pub fn operator(&self) -> &BD {
        self.base_results.operator()
    }

    pub fn contains(&self, x: &BD::Idx) -> bool {
        self.curr_state.contains(x)
    }

    /// Returns an iterator over the elements present in the current state.
    pub fn iter_incoming(&self) -> iter::Peekable<Iter<BD::Idx>> {
        self.curr_state.iter().peekable()
    }

    /// Creates a clone of the current state and applies the local
    /// effects to the clone (leaving the state of self intact).
    /// Invokes `f` with an iterator over the resulting state.
    pub fn with_iter_outgoing<F>(&self, f: F)
    where
        F: FnOnce(Iter<BD::Idx>),
    {
        let mut curr_state = self.curr_state.clone();
        curr_state.union(&self.stmt_gen);
        curr_state.subtract(&self.stmt_kill);
        f(curr_state.iter());
    }
}

impl<BD> FlowsAtLocation for FlowAtLocation<BD>
    where BD: BitDenotation
{
    fn reset_to_entry_of(&mut self, bb: BasicBlock) {
        (*self.curr_state).clone_from(self.base_results.sets().on_entry_set_for(bb.index()));
    }

    fn reconstruct_statement_effect(&mut self, loc: Location) {
        self.stmt_gen.clear();
        self.stmt_kill.clear();
        {
            let mut sets = BlockSets {
                on_entry: &mut self.curr_state,
                gen_set: &mut self.stmt_gen,
                kill_set: &mut self.stmt_kill,
            };
            self.base_results
                .operator()
                .before_statement_effect(&mut sets, loc);
        }
        self.apply_local_effect(loc);

        let mut sets = BlockSets {
            on_entry: &mut self.curr_state,
            gen_set: &mut self.stmt_gen,
            kill_set: &mut self.stmt_kill,
        };
        self.base_results
            .operator()
            .statement_effect(&mut sets, loc);
    }

    fn reconstruct_terminator_effect(&mut self, loc: Location) {
        self.stmt_gen.clear();
        self.stmt_kill.clear();
        {
            let mut sets = BlockSets {
                on_entry: &mut self.curr_state,
                gen_set: &mut self.stmt_gen,
                kill_set: &mut self.stmt_kill,
            };
            self.base_results
                .operator()
                .before_terminator_effect(&mut sets, loc);
        }
        self.apply_local_effect(loc);

        let mut sets = BlockSets {
            on_entry: &mut self.curr_state,
            gen_set: &mut self.stmt_gen,
            kill_set: &mut self.stmt_kill,
        };
        self.base_results
            .operator()
            .terminator_effect(&mut sets, loc);
    }

    fn apply_local_effect(&mut self, _loc: Location) {
        self.curr_state.union(&self.stmt_gen);
        self.curr_state.subtract(&self.stmt_kill);
    }
}

impl<'tcx, T> FlowAtLocation<T>
where
    T: HasMoveData<'tcx> + BitDenotation<Idx = MovePathIndex>,
{
    pub fn has_any_child_of(&self, mpi: T::Idx) -> Option<T::Idx> {
        let move_data = self.operator().move_data();

        let mut todo = vec![mpi];
        let mut push_siblings = false; // don't look at siblings of original `mpi`.
        while let Some(mpi) = todo.pop() {
            if self.contains(&mpi) {
                return Some(mpi);
            }
            let move_path = &move_data.move_paths[mpi];
            if let Some(child) = move_path.first_child {
                todo.push(child);
            }
            if push_siblings {
                if let Some(sibling) = move_path.next_sibling {
                    todo.push(sibling);
                }
            } else {
                // after we've processed the original `mpi`, we should
                // always traverse the siblings of any of its
                // children.
                push_siblings = true;
            }
        }
        return None;
    }
}
<commit_msg>Avoid allocations in `has_any_child_of`.<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A nice wrapper to consume dataflow results at several CFG
//! locations.

use rustc::mir::{BasicBlock, Location};
use rustc_data_structures::indexed_set::{IdxSetBuf, Iter};
use rustc_data_structures::indexed_vec::Idx;

use dataflow::{BitDenotation, BlockSets, DataflowResults};
use dataflow::move_paths::{HasMoveData, MovePathIndex};

use std::iter;

/// A trait for "cartesian products" of multiple FlowAtLocation.
///
/// There's probably a way to auto-impl this, but I think
/// it is cleaner to have manual visitor impls.
pub trait FlowsAtLocation {
    /// Reset the state bitvector to represent the entry to block `bb`.
    fn reset_to_entry_of(&mut self, bb: BasicBlock);

    /// Build gen + kill sets for statement at `loc`.
    ///
    /// Note that invoking this method alone does not change the
    /// `curr_state` -- you must invoke `apply_local_effect`
    /// afterwards.
    fn reconstruct_statement_effect(&mut self, loc: Location);

    /// Build gen + kill sets for terminator for `loc`.
    ///
    /// Note that invoking this method alone does not change the
    /// `curr_state` -- you must invoke `apply_local_effect`
    /// afterwards.
    fn reconstruct_terminator_effect(&mut self, loc: Location);

    /// Apply current gen + kill sets to `flow_state`.
    ///
    /// (`loc` parameters can be ignored if desired by
    /// client. For the terminator, the `stmt_idx` will be the number
    /// of statements in the block.)
    fn apply_local_effect(&mut self, loc: Location);
}

/// Represents the state of dataflow at a particular
/// CFG location, both before and after it is
/// executed.
///
/// Data flow results are typically computed only as basic block
/// boundaries. A `FlowInProgress` allows you to reconstruct the
/// effects at any point in the control-flow graph by starting with
/// the state at the start of the basic block (`reset_to_entry_of`)
/// and then replaying the effects of statements and terminators
/// (e.g. via `reconstruct_statement_effect` and
/// `reconstruct_terminator_effect`; don't forget to call
/// `apply_local_effect`).
pub struct FlowAtLocation<BD>
where
    BD: BitDenotation,
{
    base_results: DataflowResults<BD>,
    curr_state: IdxSetBuf<BD::Idx>,
    stmt_gen: IdxSetBuf<BD::Idx>,
    stmt_kill: IdxSetBuf<BD::Idx>,
}

impl<BD> FlowAtLocation<BD>
where
    BD: BitDenotation,
{
    /// Iterate over each bit set in the current state.
    pub fn each_state_bit<F>(&self, f: F)
    where
        F: FnMut(BD::Idx),
    {
        self.curr_state.iter().for_each(f)
    }

    /// Iterate over each `gen` bit in the current effect (invoke
    /// `reconstruct_statement_effect` or
    /// `reconstruct_terminator_effect` first).
    pub fn each_gen_bit<F>(&self, f: F)
    where
        F: FnMut(BD::Idx),
    {
        self.stmt_gen.iter().for_each(f)
    }

    pub fn new(results: DataflowResults<BD>) -> Self {
        let bits_per_block = results.sets().bits_per_block();
        let curr_state = IdxSetBuf::new_empty(bits_per_block);
        let stmt_gen = IdxSetBuf::new_empty(bits_per_block);
        let stmt_kill = IdxSetBuf::new_empty(bits_per_block);
        FlowAtLocation {
            base_results: results,
            curr_state: curr_state,
            stmt_gen: stmt_gen,
            stmt_kill: stmt_kill,
        }
    }

    /// Access the underlying operator.
    pub fn operator(&self) -> &BD {
        self.base_results.operator()
    }

    pub fn contains(&self, x: &BD::Idx) -> bool {
        self.curr_state.contains(x)
    }

    /// Returns an iterator over the elements present in the current state.
    pub fn iter_incoming(&self) -> iter::Peekable<Iter<BD::Idx>> {
        self.curr_state.iter().peekable()
    }

    /// Creates a clone of the current state and applies the local
    /// effects to the clone (leaving the state of self intact).
    /// Invokes `f` with an iterator over the resulting state.
    pub fn with_iter_outgoing<F>(&self, f: F)
    where
        F: FnOnce(Iter<BD::Idx>),
    {
        let mut curr_state = self.curr_state.clone();
        curr_state.union(&self.stmt_gen);
        curr_state.subtract(&self.stmt_kill);
        f(curr_state.iter());
    }
}

impl<BD> FlowsAtLocation for FlowAtLocation<BD>
    where BD: BitDenotation
{
    fn reset_to_entry_of(&mut self, bb: BasicBlock) {
        (*self.curr_state).clone_from(self.base_results.sets().on_entry_set_for(bb.index()));
    }

    fn reconstruct_statement_effect(&mut self, loc: Location) {
        self.stmt_gen.clear();
        self.stmt_kill.clear();
        {
            let mut sets = BlockSets {
                on_entry: &mut self.curr_state,
                gen_set: &mut self.stmt_gen,
                kill_set: &mut self.stmt_kill,
            };
            self.base_results
                .operator()
                .before_statement_effect(&mut sets, loc);
        }
        self.apply_local_effect(loc);

        let mut sets = BlockSets {
            on_entry: &mut self.curr_state,
            gen_set: &mut self.stmt_gen,
            kill_set: &mut self.stmt_kill,
        };
        self.base_results
            .operator()
            .statement_effect(&mut sets, loc);
    }

    fn reconstruct_terminator_effect(&mut self, loc: Location) {
        self.stmt_gen.clear();
        self.stmt_kill.clear();
        {
            let mut sets = BlockSets {
                on_entry: &mut self.curr_state,
                gen_set: &mut self.stmt_gen,
                kill_set: &mut self.stmt_kill,
            };
            self.base_results
                .operator()
                .before_terminator_effect(&mut sets, loc);
        }
        self.apply_local_effect(loc);

        let mut sets = BlockSets {
            on_entry: &mut self.curr_state,
            gen_set: &mut self.stmt_gen,
            kill_set: &mut self.stmt_kill,
        };
        self.base_results
            .operator()
            .terminator_effect(&mut sets, loc);
    }

    fn apply_local_effect(&mut self, _loc: Location) {
        self.curr_state.union(&self.stmt_gen);
        self.curr_state.subtract(&self.stmt_kill);
    }
}

impl<'tcx, T> FlowAtLocation<T>
where
    T: HasMoveData<'tcx> + BitDenotation<Idx = MovePathIndex>,
{
    pub fn has_any_child_of(&self, mpi: T::Idx) -> Option<T::Idx> {
        // We process `mpi` before the loop below, for two reasons:
        // - it's a little different from the loop case (we don't traverse its
        //   siblings);
        // - ~99% of the time the loop isn't reached, and this code is hot, so
        //   we don't want to allocate `todo` unnecessarily.
        if self.contains(&mpi) {
            return Some(mpi);
        }
        let move_data = self.operator().move_data();
        let move_path = &move_data.move_paths[mpi];
        let mut todo = if let Some(child) = move_path.first_child {
            vec![child]
        } else {
            return None;
        };

        while let Some(mpi) = todo.pop() {
            if self.contains(&mpi) {
                return Some(mpi);
            }
            let move_path = &move_data.move_paths[mpi];
            if let Some(child) = move_path.first_child {
                todo.push(child);
            }
            // After we've processed the original `mpi`, we should always
            // traverse the siblings of any of its children.
            if let Some(sibling) = move_path.next_sibling {
                todo.push(sibling);
            }
        }
        return None;
    }
}
<|endoftext|>


<commit_before><commit_msg>Add temporary file to investigate callbacks<commit_after>use russell_lab::Vector;

struct Processor<'a> {
    callback: Box<dyn FnMut(&mut Vector, &[f64]) + 'a>,
}

impl<'a> Processor<'a> {
    fn set_callback(&mut self, c: impl FnMut(&mut Vector, &[f64]) + 'a) {
        self.callback = Box::new(c);
    }

    fn process_events(&mut self) {
        let ksi = vec![0.0; 2];
        let mut x = Vector::new(2);
        (self.callback)(&mut x, &ksi);
        println!("got x =\n{}", x);
    }
}

fn simple_callback(x: &mut Vector, ksi: &[f64]) {
    println!("ksi = {:?}", ksi);
    println!("{}", x);
}

fn main() {
    let mut p = Processor {
        callback: Box::new(simple_callback),
    };
    p.process_events();
    let v = Vector::from(&[1.0, 2.0]);
    let x0 = 1.0;
    let x1 = 2.0;
    let my_fun = move |x: &mut Vector, ksi: &[f64]| {
        println!("using ksi = {:?}", ksi);
        x[0] = v[0];
        x[1] = v[1];
    };
    println!("x0 = {}", x0);
    println!("x1 = {}", x1);
    // println!("v = {:?}", v);
    p.set_callback(my_fun);
    p.process_events();
}
<|endoftext|>


<commit_before><commit_msg>Began writing a wrapper that transforms a flat TimeSteward to a full one<commit_after>//! A wrapper that turns a flat TimeSteward into an inefficient fall TimeSteward.
//!
//! This is done by storing snapshots and reverting to the previous snapshot whenever you try to query the past.
//!

use {DeterministicRandomId, ColumnId, FieldId, PredictorId, Column, ExtendedTime, StewardRc,
             Basics, FieldRc, TimeSteward, FiatEventOperationError, ValidSince, PredictorFn, TimeStewardSettings,ColumnList, ColumnListUser};
use std::collections::{HashMap, BTreeMap};
use std::cmp::max;
use std::marker::PhantomData;
use Snapshot as SuperSnapshot;

pub struct Steward<B: Basics, Steward0: TimeSteward<B> > {
  steward: Steward0,
  invalid_before: ValidSince <B::Time>,
  constants: B::Constants,
  settings: Steward0::Settings,
  fiat_events: BTreeMap<B::Time, i32>,
  snapshots: Vec<Steward0::Snapshot>,
}

impl<B: Basics, Steward0: TimeSteward<B> > TimeSteward<B> for Steward<B, Steward0> {
  type Snapshot = Steward0::Snapshot;
  type Settings = Steward0::Settings;

  fn valid_since(&self) -> ValidSince<B::Time> {
    self.invalid_before.clone()
  }
  fn new_empty(constants: B::Constants, settings: Self::Settings) -> Self {
    Steward::<B, Steward0> {
      steward: TimeSteward::new_empty (constants.clone(), settings.clone()),
      invalid_before: ValidSince::TheBeginning,
      constants: constants,
      settings: settings,
      fiat_events: BTreeMap::new(),
      snapshots: Vec::new(),
    }
  }

  fn from_snapshot<'a, S: ::Snapshot<B>>(snapshot: & 'a S,
                                              settings: Self::Settings)
                                              -> Self
                                              where & 'a S: IntoIterator <Item = ::SnapshotEntry <'a, B>> {
    let steward = TimeSteward::from_snapshot::<'a, S> (snapshot, settings.clone());
    Steward::<B, Steward0> {
      steward: steward,
      invalid_before: ValidSince::Before (snapshot.now().clone()),
      constants: snapshot.constants().clone(),
      settings: settings,
      fiat_events: BTreeMap::new(),
      snapshots: vec![steward.snapshot_before (snapshot.now())],
    }
  }
  fn insert_fiat_event <E: ::EventFn <B>> (&mut self,
                       time: B::Time,
                       id: DeterministicRandomId,
                       event: E)
                       -> Result<(), FiatEventOperationError> {
    if self.valid_since() > time {
      return Err(FiatEventOperationError::InvalidTime);
    }

  }
  fn erase_fiat_event(&mut self,
                      time: &B::Time,
                      id: DeterministicRandomId)
                      -> Result<(), FiatEventOperationError> {
    if self.valid_since() > *time {
      return Err(FiatEventOperationError::InvalidTime);
    }

  }

  fn snapshot_before<'b>(&'b mut self, time: &'b B::Time) -> Option<Self::Snapshot> {
    if self.valid_since() > *time {
      return None;
    }
    if self.steward.valid_since() > *time {
      while self.snapshots.last().map_or (false, | snapshot | snapshot.now() > time) {
        self.snapshots.pop();
      }
      self.steward = match self.snapshots.last() {
        None => TimeSteward::new_empty (self.constants.clone(), self.settings.clone()),
        Some (snapshot) => TimeSteward::from_snapshot::<Self::Snapshot> (snapshot, self.settings.clone()),
      }
    }
    self.snapshots.push (self.steward.snapshot_before (time));
    self.steward.snapshot_before (time)
  }
}

<|endoftext|>


<commit_before>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-android: FIXME(#10381)

// compile-flags:--debuginfo=1

// Make sure functions have proper names
// debugger:info functions
// check:static void [...]main();
// check:static void [...]some_function();
// check:static void [...]some_other_function();
// check:static void [...]zzz();

// debugger:rbreak zzz
// debugger:run

// Make sure there is no information about locals
// debugger:finish
// debugger:info locals
// check:No locals.
// debugger:continue

#[allow(unused_variable)];

struct Struct {
    a: i64,
    b: i32
}

fn main() {
    some_function(101, 202);
}

fn zzz() {()}

fn some_function(a: int, b: int) {
    let some_variable = Struct { a: 11, b: 22 };
    let some_other_variable = 23;
    zzz();
}

fn some_other_function(a: int, b: int) -> bool { true }
<commit_msg>debuginfo: Make limited-debuginfo test case more robust against GDB output variations.<commit_after>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-android: FIXME(#10381)

// compile-flags:--debuginfo=1

// Make sure functions have proper names
// debugger:info functions
// check:[...]void[...]main([...]);
// check:[...]void[...]some_function([...]);
// check:[...]void[...]some_other_function([...]);
// check:[...]void[...]zzz([...]);

// debugger:rbreak zzz
// debugger:run

// Make sure there is no information about locals
// debugger:finish
// debugger:info locals
// check:No locals.
// debugger:continue

#[allow(unused_variable)];

struct Struct {
    a: i64,
    b: i32
}

fn main() {
    some_function(101, 202);
}

fn zzz() {()}

fn some_function(a: int, b: int) {
    let some_variable = Struct { a: 11, b: 22 };
    let some_other_variable = 23;
    zzz();
}

fn some_other_function(a: int, b: int) -> bool { true }
<|endoftext|>


<commit_before>#[cfg(bogus)]
const b: bool = false;

const b: bool = true;

#[cfg(bogus)]
#[abi = "cdecl"]
extern mod rustrt {
    // This symbol doesn't exist and would be a link error if this
    // module was translated
    fn bogus();
}

#[abi = "cdecl"]
extern mod rustrt { }

#[cfg(bogus)]
type t = int;

type t = bool;

#[cfg(bogus)]
enum tg { foo, }

enum tg { bar, }

#[cfg(bogus)]
struct r {
  let i: int;
  new(i:int) { self.i = i; }
}

struct r {
  let i: int;
  new(i:int) { self.i = i; }
}

#[cfg(bogus)]
mod m {
    // This needs to parse but would fail in typeck. Since it's not in
    // the current config it should not be typechecked.
    fn bogus() { return 0; }
}

mod m {

    // Submodules have slightly different code paths than the top-level
    // module, so let's make sure this jazz works here as well
    #[cfg(bogus)]
    fn f() { }

    fn f() { }
}

// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
fn main() { fail }

fn main() {
    // Exercise some of the configured items in ways that wouldn't be possible
    // if they had the bogus definition
    assert (b);
    let x: t = true;
    let y: tg = bar;

    test_in_fn_ctxt();
}

fn test_in_fn_ctxt() {
    #[cfg(bogus)]
    fn f() { fail }
    fn f() { }
    f();

    #[cfg(bogus)]
    const i: int = 0;
    const i: int = 1;
    assert (i == 1);
}

mod test_foreign_items {
    #[abi = "cdecl"]
    extern mod rustrt {
        #[cfg(bogus)]
        fn vec_from_buf_shared();
        fn vec_from_buf_shared();
    }
}

mod test_use_statements {
    #[cfg(bogus)]
    use flippity_foo;

    extern mod rustrt {
        #[cfg(bogus)]
        use flippity_foo;
    }
}<commit_msg>Fix test case<commit_after>#[cfg(bogus)]
const b: bool = false;

const b: bool = true;

#[cfg(bogus)]
#[abi = "cdecl"]
extern mod rustrt {
    // This symbol doesn't exist and would be a link error if this
    // module was translated
    fn bogus();
}

#[abi = "cdecl"]
extern mod rustrt { }

#[cfg(bogus)]
type t = int;

type t = bool;

#[cfg(bogus)]
enum tg { foo, }

enum tg { bar, }

#[cfg(bogus)]
struct r {
  let i: int;
  new(i:int) { self.i = i; }
}

struct r {
  let i: int;
  new(i:int) { self.i = i; }
}

#[cfg(bogus)]
mod m {
    // This needs to parse but would fail in typeck. Since it's not in
    // the current config it should not be typechecked.
    fn bogus() { return 0; }
}

mod m {

    // Submodules have slightly different code paths than the top-level
    // module, so let's make sure this jazz works here as well
    #[cfg(bogus)]
    fn f() { }

    fn f() { }
}

// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
fn main() { fail }

fn main() {
    // Exercise some of the configured items in ways that wouldn't be possible
    // if they had the bogus definition
    assert (b);
    let x: t = true;
    let y: tg = bar;

    test_in_fn_ctxt();
}

fn test_in_fn_ctxt() {
    #[cfg(bogus)]
    fn f() { fail }
    fn f() { }
    f();

    #[cfg(bogus)]
    const i: int = 0;
    const i: int = 1;
    assert (i == 1);
}

mod test_foreign_items {
    #[abi = "cdecl"]
    extern mod rustrt {
        #[cfg(bogus)]
        fn rust_getcwd() -> *();
        fn rust_getcwd() -> *();
    }
}

mod test_use_statements {
    #[cfg(bogus)]
    use flippity_foo;

    extern mod rustrt {
        #[cfg(bogus)]
        use flippity_foo;
    }
}<|endoftext|>


<commit_before><commit_msg>Fix: Do not pass --rtp in testing environment<commit_after><|endoftext|>


<commit_before><commit_msg>Add a run-pass test for existential traits in ARCs.<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Tests that a heterogeneous list of existential types can be put inside an ARC
// and shared between tasks as long as all types fulfill Const+Owned.

// xfail-fast

extern mod extra;
use extra::arc;
use std::comm;
use std::task;
use std::cell;

trait Pet {
    fn name(&self, blk: &fn(&str));
    fn num_legs(&self) -> uint;
    fn of_good_pedigree(&self) -> bool;
}

struct Catte {
    num_whiskers: uint,
    name: ~str,
}

struct Dogge {
    bark_decibels: uint,
    tricks_known: uint,
    name: ~str,
}

struct Goldfyshe {
    swim_speed: uint,
    name: ~str,
}

impl Pet for Catte {
    fn name(&self, blk: &fn(&str)) { blk(self.name) }
    fn num_legs(&self) -> uint { 4 }
    fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
    fn name(&self, blk: &fn(&str)) { blk(self.name) }
    fn num_legs(&self) -> uint { 4 }
    fn of_good_pedigree(&self) -> bool {
        self.bark_decibels < 70 || self.tricks_known > 20
    }
}
impl Pet for Goldfyshe {
    fn name(&self, blk: &fn(&str)) { blk(self.name) }
    fn num_legs(&self) -> uint { 0 }
    fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}

fn main() {
    let catte = Catte { num_whiskers: 7, name: ~"alonzo_church" };
    let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: ~"alan_turing" };
    let dogge2 = Dogge { bark_decibels: 55,  tricks_known: 11, name: ~"albert_einstein" };
    let fishe = Goldfyshe { swim_speed: 998, name: ~"alec_guinness" };
    let arc = arc::ARC(~[~catte  as ~Pet:Const+Owned,
                         ~dogge1 as ~Pet:Const+Owned,
                         ~fishe  as ~Pet:Const+Owned,
                         ~dogge2 as ~Pet:Const+Owned]);
    let (p1,c1) = comm::stream();
    let arc1 = cell::Cell::new(arc.clone());
    do task::spawn { check_legs(arc1.take()); c1.send(()); }
    let (p2,c2) = comm::stream();
    let arc2 = cell::Cell::new(arc.clone());
    do task::spawn { check_names(arc2.take()); c2.send(()); }
    let (p3,c3) = comm::stream();
    let arc3 = cell::Cell::new(arc.clone());
    do task::spawn { check_pedigree(arc3.take()); c3.send(()); }
    p1.recv();
    p2.recv();
    p3.recv();
}

fn check_legs(arc: arc::ARC<~[~Pet:Const+Owned]>) {
    let mut legs = 0;
    for arc.get().iter().advance |pet| {
        legs += pet.num_legs();
    }
    assert!(legs == 12);
}
fn check_names(arc: arc::ARC<~[~Pet:Const+Owned]>) {
    for arc.get().iter().advance |pet| {
        do pet.name |name| {
            assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
        }
    }
}
fn check_pedigree(arc: arc::ARC<~[~Pet:Const+Owned]>) {
    for arc.get().iter().advance |pet| {
        assert!(pet.of_good_pedigree());
    }
}
<|endoftext|>


<commit_before><commit_msg>feat(geektime_algo): add 35 trie<commit_after>// [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/)

#[derive(Default, Debug)]
struct Trie {
    is_ending: bool,
    nodes:     [Option<Box<Trie>>; 26],
}

impl Trie {
    fn new() -> Self {
        Default::default()
    }

    fn insert(&mut self, word: &str) {
        let mut curr = self;
        for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
            curr = curr.nodes[i].get_or_insert_with(Box::new(Trie::new()));
        }
        curr.is_ending = true;
    }

    fn find(&self, word: &str) -> bool {
        let mut curr = self;
        for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
            match curr.nodes[i].as_ref() {
                Some(node) => { curr = node; },
                None => { return false; },
            }
        }
        curr.is_ending
    }
}

fn main() {
    let mut m = Trie::new();
    m.insert("hello");
    m.insert("she");
    println!("{:?}", m);
    let r = m.search("hello");
    println!("{}", r); // true
}
<|endoftext|>


<commit_before><commit_msg>Move log level to config struct<commit_after><|endoftext|>


<commit_before><commit_msg>rustc suggestion.<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1906<commit_after>// https://leetcode.com/problems/minimum-absolute-difference-queries/
pub fn min_difference(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> {
    todo!()
}

fn main() {
    println!(
        "{:?}",
        min_difference(
            vec![1, 3, 4, 8],
            vec![vec![0, 1], vec![1, 2], vec![2, 3], vec![0, 3]]
        )
    ); // [2,1,4,1]
    println!(
        "{:?}",
        min_difference(
            vec![4, 5, 2, 2, 7, 10],
            vec![vec![2, 3], vec![0, 2], vec![0, 5], vec![3, 5]]
        )
    ); // [-1,1,1,3]
}
<|endoftext|>


<commit_before>fn main() {
    let x = @{mut a: @10, b: @20};
    match x {
      @{a, b} => { assert *a == 10; (*x).a = @30; assert *a == 30; }
    }
}
<commit_msg>test: Remove alt-implicit-copy.rs test. Incompatible with current borrow check semantics. rs=bustage<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #27<commit_after>// p(n) = n^2 + an + b is prime for n = 0 .. N
// p(0) = b         => b must be prime
// p(1) = 1 + a + b => a > -(1+b)
// p(2) = 4 + 2a + b

extern mod euler;
use euler::prime::{ Prime };

fn get_len(a: int, b: int, ps: &Prime) -> uint {
    let mut nu = 0;
    loop {
        let n = nu as int;
        let mut val = n * n + a * n + b;
        for ps.each |p| {
            if (p as int) == val {
                nu += 1;
                break;
            }
            if (p as int) > val {
                return nu;
            }
        }
    }
}

fn main() {
    let ps = Prime();
    let mut ans = { len: 0, a: 0, b: 0 };
    for ps.each |bu| {
        if bu >= 1000 { break; }
        let b = bu as int;
        for int::range(-b, 1000) |a| {
            let len = get_len(a, b, &ps);
            if len > ans.len {
                ans.len = len;
                ans.a = a;
                ans.b = b;
            }
        }
    }
    io::println(fmt!("n^2 + %dn + %d => %u len", ans.a, ans.b, ans.len));
    io::println(fmt!("a * b = %d", ans.a * ans.b));
}
<|endoftext|>


<commit_before>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that changing a tracked commandline argument invalidates
// the cache while changing an untracked one doesn't.

// revisions:rpass1 rpass2 rpass3

#![feature(rustc_attrs)]

#![rustc_partition_translated(module="commandline_args", cfg="rpass2")]
#![rustc_partition_reused(module="commandline_args", cfg="rpass3")]

// Between revisions 1 and 2, we are changing the debuginfo-level, which should
// invalidate the cache. Between revisions 2 and 3, we are adding `--verbose`
// which should have no effect on the cache:
//[rpass1] compile-flags: -C debuginfo=0
//[rpass2] compile-flags: -C debuginfo=2
//[rpass3] compile-flags: -C debuginfo=2 --verbose

pub fn main() {
    println!("hello world");
}
<commit_msg>Fix incremental/commandline-args test.<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that changing a tracked commandline argument invalidates
// the cache while changing an untracked one doesn't.

// revisions:rpass1 rpass2 rpass3

#![feature(rustc_attrs)]

#![rustc_partition_translated(module="commandline_args", cfg="rpass2")]
#![rustc_partition_reused(module="commandline_args", cfg="rpass3")]

// Between revisions 1 and 2, we are changing the debuginfo-level, which should
// invalidate the cache. Between revisions 2 and 3, we are adding `--verbose`
// which should have no effect on the cache:
//[rpass1] compile-flags: -C debuginfo=0
//[rpass2] compile-flags: -C debuginfo=2
//[rpass3] compile-flags: -C debuginfo=2 --verbose

pub fn main() {
    // empty
}
<|endoftext|>


<commit_before><commit_msg>Support query syntax.<commit_after>use ::{Points, Value};

/// Resolve the points to line protocol format
pub fn line_serialization(points: Points) -> String {
    let mut line = Vec::new();
    for point in points.point {
        line.push(point.measurement);

        for (tag, value) in point.tags.iter() {
            line.push(",".to_string());
            line.push(tag.to_string());
            line.push("=".to_string());

            match value {
                &Value::String(ref s) => line.push(s.to_string()),
                &Value::Float(ref f) => line.push(f.to_string()),
                &Value::Integer(ref i) => line.push(i.to_string()),
                &Value::Boolean(b) => line.push({ if b { "true".to_string() } else { "false".to_string() } })
            }
        }

        let mut was_first = true;

        for (field, value) in point.fields.iter() {
            line.push({
                if was_first {
                    was_first = false;
                    " "
                } else { "," }
            }.to_string());
            line.push(field.to_string());
            line.push("=".to_string());

            match value {
                &Value::String(ref s) => line.push(s.to_string()),
                &Value::Float(ref f) => line.push(f.to_string()),
                &Value::Integer(ref i) => line.push(i.to_string()),
                &Value::Boolean(b) => line.push({ if b { "true".to_string() } else { "false".to_string() } })
            }
        }

        match point.timestamp {
            Some(t) => {
                line.push(" ".to_string());
                line.push(t.to_string());
            }
            _ => {}
        }

        line.push("\n".to_string())
    }

    line.join("")
}
<|endoftext|>


<commit_before><commit_msg>Add const_fn in generics test<commit_after>// run-pass

#![feature(min_const_generics)]

const fn identity<const T: u32>() -> u32 { T }

#[derive(Eq, PartialEq, Debug)]
pub struct ConstU32<const U: u32>;

pub fn new() -> ConstU32<{ identity::<3>() }> {
  ConstU32::<{ identity::<3>() }>
}

fn main() {
  let v = new();
  assert_eq!(v, ConstU32::<3>);
}
<|endoftext|>


<commit_before>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// error-pattern: requires at least a format string argument
// error-pattern: bad-format-args.rs:19:5: 19:15: note: in this expansion

// error-pattern: expected token: `,`
// error-pattern: bad-format-args.rs:20:5: 20:19: note: in this expansion
// error-pattern: bad-format-args.rs:21:5: 21:22: note: in this expansion

fn main() {
    format!();
    format!("" 1);
    format!("", 1 1);
}
<commit_msg>Fix touchy test to work with old and new error format<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// error-pattern: requires at least a format string argument
// error-pattern: in this expansion

// error-pattern: expected token: `,`
// error-pattern: in this expansion
// error-pattern: in this expansion

fn main() {
    format!();
    format!("" 1);
    format!("", 1 1);
}
<|endoftext|>