text:
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::message::beacon::Beacon;
use crate::message::message_client::MessageClient;
use crate::message::messenger::{Messenger, MessengerClient};
use crate::message::receptor::Receptor;
use futures::channel::mpsc::UnboundedSender;
use futures::channel::oneshot::Sender;
use std::fmt::Debug;
use std::hash::Hash;
use thiserror::Error;

/// Trait alias for types of data that can be used as the payload in a
/// MessageHub.
pub trait Payload: Clone + Debug + Send + Sync {}
impl<T: Clone + Debug + Send + Sync> Payload for T {}

/// Trait alias for types of data that can be used as an address in a
/// MessageHub.
pub trait Address: Clone + Debug + Eq + Hash + Send + Sync {}
impl<T: Clone + Debug + Eq + Hash + Send + Sync> Address for T {}

/// A MessageEvent defines the data that can be returned through a message
/// receptor.
pub enum MessageEvent<P: Payload + 'static, A: Address + 'static> {
    /// A message that has been delivered, either as a new message directed at to
    /// the recipient's address or a reply to a previously sent message
    /// (dependent on the receptor's context).
    Message(P, MessageClient<P, A>),
    /// A status update for the message that spawned the receptor delivering this
    /// update.
    Status(DeliveryStatus),
}

#[derive(Error, Debug, Clone)]
pub enum MessageError<A: Address + 'static> {
    #[error("Address conflig:{address:?} already exists")]
    AddressConflict { address: A },
    #[error("Unexpected Error")]
    Unexpected,
}

/// The types of results possible from sending or replying.
#[derive(Clone, PartialEq, Debug)]
pub enum DeliveryStatus {
    // Sent to some audience, potentially no one.
    Broadcasted,
    // Received by the intended address.
    Received,
    // Could not be delivered to the specified target.
    Undeliverable,
}

/// The intended recipients for a message.
#[derive(Clone)]
pub enum Audience<A> {
    // All non-broker messengers outside of the sender.
    Broadcast,
    // The messenger at the specified address.
    Address(A),
}

/// The messengers that can participate in messaging
#[derive(Clone)]
pub enum MessengerType<A: Address + 'static> {
    /// An endpoint in the messenger graph. Can have messages specifically
    /// addressed to it and can author new messages.
    Addressable(A),
    /// A intermediary messenger. Will receive every forwarded message. Brokers
    /// are able to send and reply to messages, but the main purpose is to observe
    /// messages.
    Broker,
}

/// MessageType captures details about the Message's source.
#[derive(Clone)]
pub enum MessageType<P: Payload + 'static, A: Address + 'static> {
    /// A completely new message that is intended for the specified audience.
    Origin(Audience<A>),
    /// A response to a previously received message. Note that the value must
    /// be boxed to mitigate recursive sizing issues as MessageType is held by
    /// Message.
    Reply(Box<Message<P, A>>),
}

/// The core messaging unit. A Message may be annotated by messengers, but is
/// not associated with a particular Messenger instance.
#[derive(Clone)]
pub struct Message<P: Payload + 'static, A: Address + 'static> {
    payload: P,
    message_type: MessageType<P, A>,
    // The return path is generated while the message is passed from messenger
    // to messenger on the way to the intended recipient. It indicates the
    // messengers that would like to be informed of replies to this message.
    // The message author is always the last element in this vector. New
    // participants are pushed to the front.
    return_path: Vec<Beacon<P, A>>,
}

impl<P: Payload + 'static, A: Address + 'static> Message<P, A> {
    /// Returns a new Message instance. Only the MessageHub can mint new messages.
    pub(super) fn new(payload: P, message_type: MessageType<P, A>) -> Message<P, A> {
        Message { payload: payload, message_type: message_type, return_path: vec![] }
    }

    /// Adds an entity to be notified on any replies.
    pub(super) fn add_participant(&mut self, participant: Beacon<P, A>) {
        self.return_path.insert(0, participant);
    }

    /// Returns the list of participants for the reply return path.
    pub(super) fn get_return_path(&self) -> Vec<Beacon<P, A>> {
        return self.return_path.clone();
    }

    /// Returns the message's type.
    pub(super) fn get_message_type(&self) -> MessageType<P, A> {
        return self.message_type.clone();
    }

    /// Returns a copy of the message's payload.
    pub fn payload(&self) -> P {
        self.payload.clone()
    }

    /// Delivers the supplied status to all participants in the return path.
    pub(super) async fn report_status(&mut self, status: DeliveryStatus) {
        for beacon in self.return_path.clone() {
            beacon.status(status.clone()).await.ok();
        }
    }
}

/// Type definition for a sender handed by the MessageHub to messengers to
/// send actions.
pub(super) type ActionSender<P, A> =
    UnboundedSender<(MessengerId, MessageAction<P, A>, Option<Beacon<P, A>>)>;

/// An internal identifier used by the MessageHub to identify messengers.
pub(super) type MessengerId = usize;

pub(super) type CreateMessengerResult<P, A> =
    Result<(MessengerClient<P, A>, Receptor<P, A>), MessageError<A>>;

/// Callback for handing back a messenger
pub(super) type MessengerSender<P, A> = Sender<CreateMessengerResult<P, A>>;

/// Type definition for a sender handed by the MessageHub to spawned components
/// (messenger factories and messengers) to control messengers.
pub(super) type MessengerActionSender<P, A> = UnboundedSender<MessengerAction<P, A>>;

/// Internal representation of possible actions around a messenger.
pub(super) enum MessengerAction<P: Payload + 'static, A: Address + 'static> {
    // Creates a top level messenger
    Create(MessengerType<A>, MessengerSender<P, A>),
    // Deletes a given messenger
    Delete(Messenger<P, A>),
}

/// Internal representation for possible actions on a message.
pub(super) enum MessageAction<P: Payload + 'static, A: Address + 'static> {
    // A new message sent to the specified audience.
    Send(P, MessageType<P, A>),
    // The message has been forwarded by the current holder.
    Forward(Message<P, A>),
}


text:
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;

use font::Metrics;

use alacritty_terminal::index::{Column, Point};
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::color::Rgb;
use alacritty_terminal::term::{RenderableCell, SizeInfo};

#[derive(Debug, Copy, Clone)]
pub struct RenderRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub color: Rgb,
    pub alpha: f32,
}

impl RenderRect {
    pub fn new(x: f32, y: f32, width: f32, height: f32, color: Rgb, alpha: f32) -> Self {
        RenderRect { x, y, width, height, color, alpha }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct RenderLine {
    pub start: Point,
    pub end: Point,
    pub color: Rgb,
}

impl RenderLine {
    pub fn rects(&self, flag: Flags, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        let mut rects = Vec::new();

        let mut start = self.start;
        while start.line < self.end.line {
            let mut end = start;
            end.col = size.cols() - 1;
            rects.push(Self::create_rect(metrics, size, flag, start, end, self.color));

            start.col = Column(0);
            start.line += 1;
        }

        rects.push(Self::create_rect(metrics, size, flag, start, self.end, self.color));

        rects
    }

    fn create_rect(
        metrics: &Metrics,
        size: &SizeInfo,
        flag: Flags,
        start: Point,
        end: Point,
        color: Rgb,
    ) -> RenderRect {
        let start_x = start.col.0 as f32 * size.cell_width;
        let end_x = (end.col.0 + 1) as f32 * size.cell_width;
        let width = end_x - start_x;

        let (position, mut height) = match flag {
            Flags::UNDERLINE => (metrics.underline_position, metrics.underline_thickness),
            Flags::STRIKEOUT => (metrics.strikeout_position, metrics.strikeout_thickness),
            _ => unimplemented!("Invalid flag for cell line drawing specified"),
        };

        // Make sure lines are always visible
        height = height.max(1.);

        let line_bottom = (start.line.0 as f32 + 1.) * size.cell_height;
        let baseline = line_bottom + metrics.descent;

        let mut y = (baseline - position - height / 2.).ceil();
        let max_y = line_bottom - height;
        if y > max_y {
            y = max_y;
        }

        RenderRect::new(start_x + size.padding_x, y + size.padding_y, width, height, color, 1.)
    }
}

/// Lines for underline and strikeout.
#[derive(Default)]
pub struct RenderLines {
    inner: HashMap<Flags, Vec<RenderLine>>,
}

impl RenderLines {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn rects(&self, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        self.inner
            .iter()
            .map(|(flag, lines)| -> Vec<RenderRect> {
                lines.iter().map(|line| line.rects(*flag, metrics, size)).flatten().collect()
            })
            .flatten()
            .collect()
    }

    /// Update the stored lines with the next cell info.
    pub fn update(&mut self, cell: RenderableCell) {
        for flag in &[Flags::UNDERLINE, Flags::STRIKEOUT] {
            if !cell.flags.contains(*flag) {
                continue;
            }

            // Check if there's an active line
            if let Some(line) = self.inner.get_mut(flag).and_then(|lines| lines.last_mut()) {
                if cell.fg == line.color
                    && cell.column == line.end.col + 1
                    && cell.line == line.end.line
                {
                    // Update the length of the line
                    line.end = cell.into();
                    continue;
                }
            }

            // Start new line if there currently is none
            let line = RenderLine { start: cell.into(), end: cell.into(), color: cell.fg };
            match self.inner.get_mut(flag) {
                Some(lines) => lines.push(line),
                None => {
                    self.inner.insert(*flag, vec![line]);
                },
            }
        }
    }
}

domain: rust


text:
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{error::Error, safety_rules::next_round, SafetyRules};
use aptos_crypto::{ed25519::Ed25519Signature, hash::CryptoHash, HashValue};
use aptos_types::{block_info::BlockInfo, ledger_info::LedgerInfo};
use consensus_types::{
    block::Block,
    safety_data::SafetyData,
    timeout_2chain::{TwoChainTimeout, TwoChainTimeoutCertificate},
    vote::Vote,
    vote_proposal::MaybeSignedVoteProposal,
};

/// 2-chain safety rules implementation
impl SafetyRules {
    pub(crate) fn guarded_sign_timeout_with_qc(
        &mut self,
        timeout: &TwoChainTimeout,
        timeout_cert: Option<&TwoChainTimeoutCertificate>,
    ) -> Result<Ed25519Signature, Error> {
        self.signer()?;
        let mut safety_data = self.persistent_storage.safety_data()?;
        self.verify_epoch(timeout.epoch(), &safety_data)?;
        timeout
            .verify(&self.epoch_state()?.verifier)
            .map_err(|e| Error::InvalidTimeout(e.to_string()))?;
        if let Some(tc) = timeout_cert {
            self.verify_tc(tc)?;
        }

        self.safe_to_timeout(timeout, timeout_cert, &safety_data)?;
        if timeout.round() < safety_data.last_voted_round {
            return Err(Error::IncorrectLastVotedRound(
                timeout.round(),
                safety_data.last_voted_round,
            ));
        }
        if timeout.round() > safety_data.last_voted_round {
            self.verify_and_update_last_vote_round(timeout.round(), &mut safety_data)?;
            self.persistent_storage.set_safety_data(safety_data)?;
        }

        let signature = self.sign(&timeout.signing_format())?;
        Ok(signature)
    }

    pub(crate) fn guarded_construct_and_sign_vote_two_chain(
        &mut self,
        maybe_signed_vote_proposal: &MaybeSignedVoteProposal,
        timeout_cert: Option<&TwoChainTimeoutCertificate>,
    ) -> Result<Vote, Error> {
        // Exit early if we cannot sign
        self.signer()?;

        let vote_data = self.verify_proposal(maybe_signed_vote_proposal)?;
        if let Some(tc) = timeout_cert {
            self.verify_tc(tc)?;
        }
        let proposed_block = maybe_signed_vote_proposal.vote_proposal.block();
        let mut safety_data = self.persistent_storage.safety_data()?;

        // if already voted on this round, send back the previous vote
        // note: this needs to happen after verifying the epoch as we just check the round here
        if let Some(vote) = safety_data.last_vote.clone() {
            if vote.vote_data().proposed().round() == proposed_block.round() {
                return Ok(vote);
            }
        }

        // Two voting rules
        self.verify_and_update_last_vote_round(
            proposed_block.block_data().round(),
            &mut safety_data,
        )?;
        self.safe_to_vote(proposed_block, timeout_cert)?;

        // Record 1-chain data
        self.observe_qc(proposed_block.quorum_cert(), &mut safety_data);
        // Construct and sign vote
        let author = self.signer()?.author();
        let ledger_info = self.construct_ledger_info_2chain(proposed_block, vote_data.hash())?;
        let signature = self.sign(&ledger_info)?;
        let vote = Vote::new_with_signature(vote_data, author, ledger_info, signature);

        safety_data.last_vote = Some(vote.clone());
        self.persistent_storage.set_safety_data(safety_data)?;

        Ok(vote)
    }

    /// Core safety timeout rule for 2-chain protocol. Return success if 1 and 2 are true
    /// 1. round == timeout.qc.round + 1 || round == tc.round + 1
    /// 2. timeout.qc.round >= one_chain_round
    fn safe_to_timeout(
        &self,
        timeout: &TwoChainTimeout,
        maybe_tc: Option<&TwoChainTimeoutCertificate>,
        safety_data: &SafetyData,
    ) -> Result<(), Error> {
        let round = timeout.round();
        let qc_round = timeout.hqc_round();
        let tc_round = maybe_tc.map_or(0, |tc| tc.round());
        if (round == next_round(qc_round)? || round == next_round(tc_round)?)
            && qc_round >= safety_data.one_chain_round
        {
            Ok(())
        } else {
            Err(Error::NotSafeToTimeout(
                round,
                qc_round,
                tc_round,
                safety_data.one_chain_round,
            ))
        }
    }

    /// Core safety voting rule for 2-chain protocol. Return success if 1 or 2 is true
    /// 1. block.round == block.qc.round + 1
    /// 2. block.round == tc.round + 1 && block.qc.round >= tc.highest_hqc.round
    fn safe_to_vote(
        &self,
        block: &Block,
        maybe_tc: Option<&TwoChainTimeoutCertificate>,
    ) -> Result<(), Error> {
        let round = block.round();
        let qc_round = block.quorum_cert().certified_block().round();
        let tc_round = maybe_tc.map_or(0, |tc| tc.round());
        let hqc_round = maybe_tc.map_or(0, |tc| tc.highest_hqc_round());
        if round == next_round(qc_round)?
            || (round == next_round(tc_round)? && qc_round >= hqc_round)
        {
            Ok(())
        } else {
            Err(Error::NotSafeToVote(round, qc_round, tc_round, hqc_round))
        }
    }

    fn verify_tc(&self, tc: &TwoChainTimeoutCertificate) -> Result<(), Error> {
        let epoch_state = self.epoch_state()?;

        tc.verify(&epoch_state.verifier)
            .map_err(|e| Error::InvalidTimeoutCertificate(e.to_string()))?;
        Ok(())
    }

    /// Produces a LedgerInfo that either commits a block based upon the 2-chain
    /// commit rule or an empty LedgerInfo for no commit. The 2-chain commit rule is: B0 and its
    /// prefixes can be committed if there exist certified block B1 that satisfy:
    /// 1) B0 <- B1 <--
    /// 2) round(B0) + 1 = round(B1)
    fn construct_ledger_info_2chain(
        &self,
        proposed_block: &Block,
        consensus_data_hash: HashValue,
    ) -> Result<LedgerInfo, Error> {
        let block1 = proposed_block.round();
        let block0 = proposed_block.quorum_cert().certified_block().round();

        // verify 2-chain rule
        let commit = next_round(block0)? == block1;

        // create a ledger info
        let commit_info = if commit {
            proposed_block.quorum_cert().certified_block().clone()
        } else {
            BlockInfo::empty()
        };

        Ok(LedgerInfo::new(commit_info, consensus_data_hash))
    }
}


text:
/*  artifact: the requirements tracking tool made for developers
 * Copyright (C) 2018 Rett Berg <@vitiral, vitiral@gmail.com>
 *
 * The source code is Licensed under either of
 *
 * * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
 *   http://www.apache.org/licenses/LICENSE-2.0)
 * * MIT license ([LICENSE-MIT](LICENSE-MIT) or
 *   http://opensource.org/licenses/MIT)
 *
 * at your option.
 *
 * Unless you explicitly state otherwise, any contribution intentionally submitted
 * for inclusion in the work by you, as defined in the Apache-2.0 license, shall
 * be dual licensed as above, without any additional terms or conditions.
 * */
use yew_simple;

use crate::dev_prelude::*;
use crate::graph;
use artifact_ser;

lazy_static! {
    static ref NAME_URL: Regex = expect!(Regex::new(&format!(
        r"(?i)(?:artifacts/)?({})",
        NAME_VALID_STR
    )));
    static ref EDIT_URL: Regex = expect!(Regex::new(r"(?i)edit/(\d+)"));
    static ref REPLACE_TEXT_RE: Regex = expect!(Regex::new(
        r#"(?xim)
        (?:^```dot\s*\n(?P<dot>[\s\S]+?\n)```$)  # graphviz dot rendering
        "#,
    ));
}

/// The function used for routing urls.
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn router_fn(info: yew_simple::RouteInfo) -> Msg {
    let hash = info.url.fragment().unwrap_or_default();
    let view = View::from_hash(hash);
    Msg::SetView(view)
}

impl View {
    pub(crate) fn from_hash(hash: &str) -> View {
        if hash.to_ascii_lowercase() == "graph" || hash == "" {
            View::Graph
        } else if let Some(cap) = NAME_URL.captures(hash) {
            let name = name!(&cap[1]);
            View::Artifact(name)
        } else if let Some(cap) = EDIT_URL.captures(hash) {
            let id = match usize::from_str(&cap[1]) {
                Ok(id) => id,
                Err(_) => return View::NotFound,
            };
            View::Edit(id)
        } else {
            View::NotFound
        }
    }
}

/// Render the markdown correctly.
///
/// `parent` is the parent's name, which may or may not exist/be-valid.
pub(crate) fn markdown_html(model: &Model, parent: &str, markdown: &str) -> HtmlApp {
    let md = ser_markdown(model);
    let markdown = md.replace_markdown(parent, markdown);
    let markdown = replace_markdown(&markdown).to_string();
    let value = js! {
        var reader = new commonmark.Parser();
        var writer = new commonmark.HtmlRenderer();
        var parsed = reader.parse(@{markdown});
        return writer.render(parsed);
    };

    let mut md_html = expect!(value.into_string(), "markdown not a string");
    md_html.insert_str(0, "
");
    md_html.push_str("
");
    let node = expect!(Node::from_html(md_html.trim()), "md-html: {}", md_html);
    VNode::VRef(node)
}

/// Return the default SerMarkdown object for the frontend.
pub(crate) fn ser_markdown(model: &Model) -> artifact_ser::markdown::SerMarkdown<'_> {
    use artifact_ser::markdown::*;
    let settings = SerMarkdownSettings {
        code_url: model.shared.settings.code_url.clone(),
        family: SettingsMdFamily::Dot,
        dot: SettingsMdDot::Ignore,
        name_prefix: "".to_string(),
        // md_plain: false,
        // md_details: SettingsMdDetails::default(),
    };

    SerMarkdown::with_settings(&model.shared, settings)
}

fn replace_markdown<'t>(markdown: &'t str) -> Cow<'t, str> {
    let replacer = |cap: &::ergo_std::regex::Captures<'_>| -> String {
        if let Some(dot) = cap.name("dot") {
            replace_markdown_dot(dot.as_str())
        } else {
            panic!("Got unknown match in md: {:?}", cap);
        }
    };
    REPLACE_TEXT_RE.replace_all(markdown, replacer)
}

fn replace_markdown_dot(dot: &str) -> String {
    let html = graph::dot_html_string(dot);
    format!("\n\n{0}\n\n", html)
}


text:
// Copyright 2012 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.

#[derive(Copy, Clone, Debug)]
enum foo { large, small, }

impl PartialEq for foo {
    fn eq(&self, other: &foo) -> bool {
        ((*self) as usize) == ((*other) as usize)
    }
    fn ne(&self, other: &foo) -> bool { !(*self).eq(other) }
}

pub fn main() {
    let a = (1, 2, 3);
    let b = (1, 2, 3);
    assert_eq!(a, b);
    assert!((a != (1, 2, 4)));
    assert!((a < (1, 2, 4)));
    assert!((a <= (1, 2, 4)));
    assert!(((1, 2, 4) > a));
    assert!(((1, 2, 4) >= a));
    let x = foo::large;
    let y = foo::small;
    assert!((x != y));
    assert_eq!(x, foo::large);
    assert!((x != foo::small));
}


text:
use crate::Property;

/// This element contains a single value which is compared with the target ('pattern', 'font', 'scan' or 'default') property "property" (substitute any of the property names seen above).
/// 'compare' can be one of "eq", "not_eq", "less", "less_eq", "more", "more_eq", "contains" or "not_contains".
/// 'qual' may either be the default, "any", in which case the match succeeds if any value associated with the property matches the test value,
/// or "all", in which case all of the values associated with the property must match the test value. 'ignore-blanks' takes a boolean value.
/// if 'ignore-blanks' is set "true", any blanks in the string will be ignored on its comparison. this takes effects only when compare="eq" or compare="not_eq".
/// When used in a <match target="font"> element, the target= attribute in the <test> element selects between matching the original pattern or the font.
/// "default" selects whichever target the outer <match> element has selected.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Test {
    pub qual: TestQual,
    pub target: TestTarget,
    pub compare: TestCompare,
    pub value: Property,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TestTarget {
    Default,
    Pattern,
    Font,
    Scan,
}

parse_enum! {
    TestTarget,
    (Default, "default"),
    (Pattern, "pattern"),
    (Font, "font"),
    (Scan, "scan"),
}

impl Default for TestTarget {
    fn default() -> Self {
        TestTarget::Default
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TestCompare {
    Eq,
    NotEq,
    Less,
    LessEq,
    More,
    MoreEq,
    Contains,
    NotContains,
}

parse_enum! {
    TestCompare,
    (Eq, "eq"),
    (NotEq, "not_eq"),
    (Less, "less"),
    (LessEq, "less_eq"),
    (More, "more"),
    (MoreEq, "more_eq"),
    (Contains, "contains"),
    (NotContains, "not_contains"),
}

impl Default for TestCompare {
    fn default() -> Self {
        TestCompare::Eq
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TestQual {
    Any,
    All,
}

parse_enum! {
    TestQual,
    (Any, "any"),
    (All, "all"),
}

impl Default for TestQual {
    fn default() -> Self {
        TestQual::Any
    }
}


text:
use serde_derive::{Deserialize, Serialize};

use crate::client::{Client, Response};
use crate::ids::{CustomerId, PaymentMethodId};
use crate::resources::PaymentMethod;

/// The parameters for `PaymentMethod::attach`
///
/// For more details see <https://stripe.com/docs/api/payment_methods/attach>.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AttachPaymentMethod {
    pub customer: CustomerId,
}

impl PaymentMethod {
    /// Attach a payment method to a customer
    ///
    /// For more details see <https://stripe.com/docs/api/payment_methods/attach>.
    pub fn attach(
        client: &Client,
        payment_method_id: &PaymentMethodId,
        params: AttachPaymentMethod,
    ) -> Response<PaymentMethod> {
        client.post_form(&format!("/payment_methods/{}/attach", payment_method_id), params)
    }

    /// Detach a PaymentMethod from a Customer
    ///
    /// For more details see <https://stripe.com/docs/api/payment_methods/detach>.
    pub fn detach(client: &Client, payment_method_id: &PaymentMethodId) -> Response<PaymentMethod> {
        client.post(&format!("/payment_methods/{}/detach", payment_method_id))
    }
}


text:
use crate::{convert, gen, PROTOCOL_VERSION};
use chain_core::property;
use network_core::client::block::HandshakeError;

use futures::prelude::*;

use std::marker::PhantomData;

type ResponseFuture = tower_grpc::client::unary::ResponseFuture<
    gen::node::HandshakeResponse,
    tower_hyper::client::ResponseFuture<hyper::client::conn::ResponseFuture>,
    hyper::Body,
>;

pub struct HandshakeFuture<Id> {
    inner: ResponseFuture,
    _phantom: PhantomData<Id>,
}

impl<Id> HandshakeFuture<Id> {
    pub fn new(inner: ResponseFuture) -> Self {
        HandshakeFuture {
            inner,
            _phantom: PhantomData,
        }
    }
}

impl<Id> Future for HandshakeFuture<Id>
where
    Id: property::BlockId + property::Deserialize,
{
    type Item = Id;
    type Error = HandshakeError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let res = match self.inner.poll() {
            Ok(Async::NotReady) => return Ok(Async::NotReady),
            Ok(Async::Ready(res)) => res.into_inner(),
            Err(status) => return Err(HandshakeError::Rpc(convert::error_from_grpc(status))),
        };
        if res.version != PROTOCOL_VERSION {
            return Err(HandshakeError::UnsupportedVersion(
                res.version.to_string().into(),
            ));
        }
        let block0_id = convert::deserialize_bytes(&res.block0)?;
        Ok(Async::Ready(block0_id))
    }
}


text:
// traits1.rs
// Time to implement some traits!
//
// Your task is to implement the trait
// `AppendBar' for the type `String'.
//
// The trait AppendBar has only one function,
// which appends "Bar" to any object
// implementing this trait.

trait AppendBar {
    fn append_bar(self) -> Self;
}

impl AppendBar for String {
    //Add your code here
    fn append_bar(mut self) -> Self {
        self += "Bar";
        self
    }
}

fn main() {
    let s = String::from("Foo");
    let s = s.append_bar();
    println!("s: {}", s);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_FooBar() {
        assert_eq!(String::from("Foo").append_bar(), String::from("FooBar"));
    }

    #[test]
    fn is_BarBar() {
        assert_eq!(
            String::from("").append_bar().append_bar(),
            String::from("BarBar")
        );
    }
}


text:
//! A simple library that hides away all the details and gives you a simple message stream to consume.
//!
//! At the moment only AMPQ is supported through lapin, eiffelvis_gen support is planned.
//!
//! # Glosary
//!
//! ```no_run
//! # async {
//! let mut stream = eiffelvis_stream::ampq::AmpqStream::new(
//!         "amqp://localhost:5672/%2f".into(),
//!         "hello".into(),
//!         "eiffelvis".into(),
//!     )
//!     .await
//!     .expect("Failed to connect to ampq server");
//!
//! let message: Option<Vec<u8>> = stream.next().await;
//! # };
//! ```
//!
//! *note: tokio is used as async executor*
//!

/// Provides an event stream from an ampq connection
pub mod ampq;

/// Provides an event stream produced by eiffelvis_gen
pub mod gen;


text:
#![cfg(any(feature = "bpf_c", feature = "bpf_rust"))]

#[macro_use]
extern crate solana_bpf_loader_program;

use itertools::izip;
use solana_account_decoder::parse_bpf_loader::{
    parse_bpf_upgradeable_loader, BpfUpgradeableLoaderAccountType,
};
use solana_bpf_loader_program::{
    create_vm,
    serialization::{deserialize_parameters, serialize_parameters},
    syscalls::register_syscalls,
    ThisInstructionMeter,
};
use solana_cli_output::display::println_transaction;
use solana_rbpf::vm::{Config, Executable, Tracer};
use solana_runtime::{
    bank::{Bank, ExecuteTimings, NonceRollbackInfo, TransactionBalancesSet, TransactionResults},
    bank_client::BankClient,
    genesis_utils::{create_genesis_config, GenesisConfigInfo},
    loader_utils::{
        load_buffer_account, load_program, load_upgradeable_program, set_upgrade_authority,
        upgrade_program,
    },
};
use solana_sdk::{
    account::AccountSharedData,
    bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable,
    client::SyncClient,
    clock::{DEFAULT_SLOTS_PER_EPOCH, MAX_PROCESSING_AGE},
    entrypoint::{MAX_PERMITTED_DATA_INCREASE, SUCCESS},
    instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError},
    keyed_account::KeyedAccount,
    message::Message,
    process_instruction::{InvokeContext, MockInvokeContext},
    pubkey::Pubkey,
    signature::{keypair_from_seed, Keypair, Signer},
    system_instruction,
    sysvar::{
        clock, epoch_schedule, fees, instructions, recent_blockhashes, rent, slot_hashes,
        slot_history, stake_history,
    },
    transaction::{Transaction, TransactionError},
};
use solana_transaction_status::{
    token_balances::collect_token_balances, ConfirmedTransaction, InnerInstructions,
    TransactionStatusMeta, TransactionWithStatusMeta, UiTransactionEncoding,
};
use std::{
    cell::RefCell, collections::HashMap, env, fs::File, io::Read, path::PathBuf, str::FromStr,
    sync::Arc,
};

/// BPF program file extension
const PLATFORM_FILE_EXTENSION_BPF: &str = "so";

/// Create a BPF program file name
fn create_bpf_path(name: &str) -> PathBuf {
    let mut pathbuf = {
        let current_exe = env::current_exe().unwrap();
        PathBuf::from(current_exe.parent().unwrap().parent().unwrap())
    };
    pathbuf.push("bpf/");
    pathbuf.push(name);
    pathbuf.set_extension(PLATFORM_FILE_EXTENSION_BPF);
    pathbuf
}

fn load_bpf_program(
    bank_client: &BankClient,
    loader_id: &Pubkey,
    payer_keypair: &Keypair,
    name: &str,
) -> Pubkey {
    let elf = read_bpf_program(name);
    load_program(bank_client, payer_keypair, loader_id, elf)
}

fn read_bpf_program(name: &str) -> Vec<u8> {
    let path = create_bpf_path(name);
    let mut file = File::open(&path).unwrap_or_else(|err| {
        panic!("Failed to open {}: {}", path.display(), err);
    });
    let mut elf = Vec::new();
    file.read_to_end(&mut elf).unwrap();

    elf
}

#[cfg(feature = "bpf_rust")]
fn write_bpf_program(
    bank_client: &BankClient,
    loader_id: &Pubkey,
    payer_keypair: &Keypair,
    program_keypair: &Keypair,
    elf: &[u8],
) {
    use solana_sdk::loader_instruction;

    let chunk_size = 256; // Size of chunk just needs to fit into tx
    let mut offset = 0;
    for chunk in elf.chunks(chunk_size) {
        let instruction =
            loader_instruction::write(&program_keypair.pubkey(), loader_id, offset, chunk.to_vec());
        let message = Message::new(&[instruction], Some(&payer_keypair.pubkey()));

        bank_client
            .send_and_confirm_message(&[payer_keypair, &program_keypair], message)
            .unwrap();

        offset += chunk_size as u32;
    }
}

fn load_upgradeable_bpf_program(
    bank_client: &BankClient,
    payer_keypair: &Keypair,
    buffer_keypair: &Keypair,
    executable_keypair: &Keypair,
    authority_keypair: &Keypair,
    name: &str,
) {
    let path = create_bpf_path(name);
    let mut file = File::open(&path).unwrap_or_else(|err| {
        panic!("Failed to open {}: {}", path.display(), err);
    });
    let mut elf = Vec::new();
    file.read_to_end(&mut elf).unwrap();
    load_upgradeable_program(
        bank_client,
        payer_keypair,
        buffer_keypair,
        executable_keypair,
        authority_keypair,
        elf,
    );
}

fn load_upgradeable_buffer(
    bank_client: &BankClient,
    payer_keypair: &Keypair,
    buffer_keypair: &Keypair,
    buffer_authority_keypair: &Keypair,
    name: &str,
) {
    let path = create_bpf_path(name);
    let mut file = File::open(&path).unwrap_or_else(|err| {
        panic!("Failed to open {}: {}", path.display(), err);
    });
    let mut elf = Vec::new();
    file.read_to_end(&mut elf).unwrap();
    load_buffer_account(
        bank_client,
        payer_keypair,
        &buffer_keypair,
        buffer_authority_keypair,
        &elf,
    );
}

fn upgrade_bpf_program(
    bank_client: &BankClient,
    payer_keypair: &Keypair,
    buffer_keypair: &Keypair,
    executable_pubkey: &Pubkey,
    authority_keypair: &Keypair,
    name: &str,
) {
    load_upgradeable_buffer(
        bank_client,
        payer_keypair,
        buffer_keypair,
        authority_keypair,
        name,
    );
    upgrade_program(
        bank_client,
        payer_keypair,
        executable_pubkey,
        &buffer_keypair.pubkey(),
        &authority_keypair,
        &payer_keypair.pubkey(),
    );
}

fn run_program(
    name: &str,
    program_id: &Pubkey,
    parameter_accounts: &[KeyedAccount],
    instruction_data: &[u8],
) -> Result<u64, InstructionError> {
    let path = create_bpf_path(name);
    let mut file = File::open(path).unwrap();

    let mut data = vec![];
    file.read_to_end(&mut data).unwrap();
    let loader_id = bpf_loader::id();
    let mut invoke_context = MockInvokeContext::default();
    let parameter_bytes = serialize_parameters(
        &bpf_loader::id(),
        program_id,
        parameter_accounts,
        &instruction_data,
    )
    .unwrap();
    let compute_meter = invoke_context.get_compute_meter();
    let mut instruction_meter = ThisInstructionMeter { compute_meter };

    let config = Config {
        max_call_depth: 20,
        stack_frame_size: 4096,
        enable_instruction_meter: true,
        enable_instruction_tracing: true,
    };
    let mut executable = Executable::from_elf(&data, None, config).unwrap();
    executable.set_syscall_registry(register_syscalls(&mut invoke_context).unwrap());
    executable.jit_compile().unwrap();

    let mut instruction_count = 0;
    let mut tracer = None;
    for i in 0..2 {
        let mut parameter_bytes = parameter_bytes.clone();
        let mut vm = create_vm(
            &loader_id,
            executable.as_ref(),
            parameter_bytes.as_slice_mut(),
            parameter_accounts,
            &mut invoke_context,
        )
        .unwrap();
        let result = if i == 0 {
            vm.execute_program_interpreted(&mut instruction_meter)
        } else {
            vm.execute_program_jit(&mut instruction_meter)
        };
        assert_eq!(SUCCESS, result.unwrap());
        deserialize_parameters(
            &bpf_loader::id(),
            parameter_accounts,
            parameter_bytes.as_slice(),
            true,
        )
        .unwrap();
        if i == 1 {
            assert_eq!(instruction_count, vm.get_total_instruction_count());
        }
        instruction_count = vm.get_total_instruction_count();
        if config.enable_instruction_tracing {
            if i == 1 {
                if !Tracer::compare(tracer.as_ref().unwrap(), vm.get_tracer()) {
                    let mut tracer_display = String::new();
                    tracer
                        .as_ref()
                        .unwrap()
                        .write(&mut tracer_display, vm.get_program())
                        .unwrap();
                    println!("TRACE (interpreted): {}", tracer_display);
                    let mut tracer_display = String::new();
                    vm.get_tracer()
                        .write(&mut tracer_display, vm.get_program())
                        .unwrap();
                    println!("TRACE (jit): {}", tracer_display);
                    assert!(false);
                }
            }
            tracer = Some(vm.get_tracer().clone());
        }
    }

    Ok(instruction_count)
}

fn process_transaction_and_record_inner(
    bank: &Bank,
    tx: Transaction,
) -> (Result<(), TransactionError>, Vec<Vec<CompiledInstruction>>) {
    let signature = tx.signatures.get(0).unwrap().clone();
    let txs = vec![tx];
    let tx_batch = bank.prepare_batch(txs.iter());
    let (mut results, _, mut inner, _transaction_logs) = bank.load_execute_and_commit_transactions(
        &tx_batch,
        MAX_PROCESSING_AGE,
        false,
        true,
        false,
        &mut ExecuteTimings::default(),
    );
    let inner_instructions = if inner.is_empty() {
        Some(vec![vec![]])
    } else {
        inner.swap_remove(0)
    };
    let result = results
        .fee_collection_results
        .swap_remove(0)
        .and_then(|_| bank.get_signature_status(&signature).unwrap());
    (
        result,
        inner_instructions.expect("cpi recording should be enabled"),
    )
}

fn execute_transactions(bank: &Bank, txs: &[Transaction]) -> Vec<ConfirmedTransaction> {
    let batch = bank.prepare_batch(txs.iter());
    let mut timings = ExecuteTimings::default();
    let mut mint_decimals = HashMap::new();
    let tx_pre_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals);
    let (
        TransactionResults {
            execution_results, ..
        },
        TransactionBalancesSet {
            pre_balances,
            post_balances,
            ..
        },
        mut inner_instructions,
        mut transaction_logs,
    ) = bank.load_execute_and_commit_transactions(
        &batch,
        std::usize::MAX,
        true,
        true,
        true,
        &mut timings,
    );
    let tx_post_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals);

    for _ in 0..(txs.len() - transaction_logs.len()) {
        transaction_logs.push(vec![]);
    }
    for _ in 0..(txs.len() - inner_instructions.len()) {
        inner_instructions.push(None);
    }

    izip!(
        txs.iter(),
        execution_results.into_iter(),
        inner_instructions.into_iter(),
        pre_balances.into_iter(),
        post_balances.into_iter(),
        tx_pre_token_balances.into_iter(),
        tx_post_token_balances.into_iter(),
        transaction_logs.into_iter(),
    )
    .map(
        |(
            tx,
            (execute_result, nonce_rollback),
            inner_instructions,
            pre_balances,
            post_balances,
            pre_token_balances,
            post_token_balances,
            log_messages,
        )| {
            let fee_calculator = nonce_rollback
                .map(|nonce_rollback| nonce_rollback.fee_calculator())
                .unwrap_or_else(|| bank.get_fee_calculator(&tx.message().recent_blockhash))
                .expect("FeeCalculator must exist");
            let fee = fee_calculator.calculate_fee(tx.message());

            let inner_instructions = inner_instructions.map(|inner_instructions| {
                inner_instructions
                    .into_iter()
                    .enumerate()
                    .map(|(index, instructions)| InnerInstructions {
                        index: index as u8,
                        instructions,
                    })
                    .filter(|i| !i.instructions.is_empty())
                    .collect()
            });

            let tx_status_meta = TransactionStatusMeta {
                status: execute_result,
                fee,
                pre_balances,
                post_balances,
                pre_token_balances: Some(pre_token_balances),
                post_token_balances: Some(post_token_balances),
                inner_instructions,
                log_messages: Some(log_messages),
                rewards: None,
            };

            ConfirmedTransaction {
                slot: bank.slot(),
                transaction: TransactionWithStatusMeta {
                    transaction: tx.clone(),
                    meta: Some(tx_status_meta),
                },
                block_time: None,
            }
        },
    )
    .collect()
}

fn print_confirmed_tx(name: &str, confirmed_tx: ConfirmedTransaction) {
    let block_time = confirmed_tx.block_time;
    let tx = confirmed_tx.transaction.transaction.clone();
    let encoded = confirmed_tx.encode(UiTransactionEncoding::JsonParsed);
    println!("EXECUTE {} (slot {})", name, encoded.slot);
    println_transaction(&tx, &encoded.transaction.meta, "  ", None, block_time);
}

#[test]
#[cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
fn test_program_bpf_sanity() {
    solana_logger::setup();

    let mut programs = Vec::new();
    #[cfg(feature = "bpf_c")]
    {
        programs.extend_from_slice(&[
            ("alloc", true),
            ("bpf_to_bpf", true),
            ("multiple_static", true),
            ("noop", true),
            ("noop++", true),
            ("panic", false),
            ("relative_call", true),
            ("sanity", true),
            ("sanity++", true),
            ("sha", true),
            ("struct_pass", true),
            ("struct_ret", true),
        ]);
    }
    #[cfg(feature = "bpf_rust")]
    {
        programs.extend_from_slice(&[
            ("solana_bpf_rust_128bit", true),
            ("solana_bpf_rust_alloc", true),
            ("solana_bpf_rust_custom_heap", true),
            ("solana_bpf_rust_dep_crate", true),
            ("solana_bpf_rust_external_spend", false),
            ("solana_bpf_rust_iter", true),
            ("solana_bpf_rust_many_args", true),
            ("solana_bpf_rust_mem", true),
            ("solana_bpf_rust_noop", true),
            ("solana_bpf_rust_panic", false),
            ("solana_bpf_rust_param_passing", true),
            ("solana_bpf_rust_rand", true),
            ("solana_bpf_rust_sanity", true),
            ("solana_bpf_rust_sha", true),
        ]);
    }

    for program in programs.iter() {
        println!("Test program: {:?}", program.0);

        let GenesisConfigInfo {
            genesis_config,
            mint_keypair,
            ..
        } = create_genesis_config(50);
        let mut bank = Bank::new(&genesis_config);
        let (name, id, entrypoint) = solana_bpf_loader_program!();
        bank.add_builtin(&name, id, entrypoint);
        let bank = Arc::new(bank);

        // Create bank with a specific slot, used by solana_bpf_rust_sysvar test
        let bank = Bank::new_from_parent(&bank, &Pubkey::default(), DEFAULT_SLOTS_PER_EPOCH + 1);
        let bank_client = BankClient::new(bank);

        // Call user program
        let program_id =
            load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.0);
        let account_metas = vec![
            AccountMeta::new(mint_keypair.pubkey(), true),
            AccountMeta::new(Keypair::new().pubkey(), false),
            AccountMeta::new_readonly(clock::id(), false),
            AccountMeta::new_readonly(epoch_schedule::id(), false),
            AccountMeta::new_readonly(fees::id(), false),
            AccountMeta::new_readonly(instructions::id(), false),
            AccountMeta::new_readonly(recent_blockhashes::id(), false),
            AccountMeta::new_readonly(rent::id(), false),
            AccountMeta::new_readonly(slot_hashes::id(), false),
            AccountMeta::new_readonly(slot_history::id(), false),
            AccountMeta::new_readonly(stake_history::id(), false),
        ];
        let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas);
        let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
        if program.1 {
            assert!(result.is_ok());
        } else {
            assert!(result.is_err());
        }
    }
}

#[test]
#[cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
fn test_program_bpf_loader_deprecated() {
    solana_logger::setup();

    let mut programs = Vec::new();
    #[cfg(feature = "bpf_c")]
    {
        programs.extend_from_slice(&[("deprecated_loader")]);
    }
    #[cfg(feature = "bpf_rust")]
    {
        programs.extend_from_slice(&[("solana_bpf_rust_deprecated_loader")]);
    }

    for program in programs.iter() {
        println!("Test program: {:?}", program);

        let GenesisConfigInfo {
            genesis_config,
            mint_keypair,
            ..
        } = create_genesis_config(50);
        let mut bank = Bank::new(&genesis_config);
        let (name, id, entrypoint) = solana_bpf_loader_deprecated_program!();
        bank.add_builtin(&name, id, entrypoint);
        let bank_client = BankClient::new(bank);

        let program_id = load_bpf_program(
            &bank_client,
            &bpf_loader_deprecated::id(),
            &mint_keypair,
            program,
        );
        let account_metas = vec![AccountMeta::new(mint_keypair.pubkey(), true)];
        let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas);
        let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
        assert!(result.is_ok());
    }
}

#[test]
fn test_program_bpf_duplicate_accounts() {
    solana_logger::setup();

    let mut programs = Vec::new();
    #[cfg(feature = "bpf_c")]
    {
        programs.extend_from_slice(&[("dup_accounts")]);
    }
    #[cfg(feature = "bpf_rust")]
    {
        programs.extend_from_slice(&[("solana_bpf_rust_dup_accounts")]);
    }

    for program in programs.iter() {
        println!("Test program: {:?}", program);

        let GenesisConfigInfo {
            genesis_config,
            mint_keypair,
            ..
        } = create_genesis_config(50);
        let mut bank = Bank::new(&genesis_config);
        let (name, id, entrypoint) = solana_bpf_loader_program!();
        bank.add_builtin(&name, id, entrypoint);
        let bank = Arc::new(bank);
        let bank_client = BankClient::new_shared(&bank);
        let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program);
        let payee_account = AccountSharedData::new(10, 1, &program_id);
        let payee_pubkey = solana_sdk::pubkey::new_rand();
        bank.store_account(&payee_pubkey, &payee_account);
        let account = AccountSharedData::new(10, 1, &program_id);

        let pubkey = solana_sdk::pubkey::new_rand();
        let account_metas = vec![
            AccountMeta::new(mint_keypair.pubkey(), true),
            AccountMeta::new(payee_pubkey, false),
            AccountMeta::new(pubkey, false),
            AccountMeta::new(pubkey, false),
        ];

        bank.store_account(&pubkey, &account);
        let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas.clone());
        let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
        let data = bank_client.get_account_data(&pubkey).unwrap().unwrap();
        assert!(result.is_ok());
        assert_eq!(data[0], 1);

        bank.store_account(&pubkey, &account);
        let instruction = Instruction::new_with_bytes(program_id, &[2], account_metas.clone());
        let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
        let data = bank_client.get_account_data(&pubkey).unwrap().unwrap();
        assert!(result.is_ok());
        assert_eq!(data[0], 2);

        bank.store_account(&pubkey, &account);
        let instruction = Instruction::new_with_bytes(program_id, &[3], account_metas.clone());
        let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction);
        let data = bank_client.get_account_data(&pubkey).unwrap().unwrap();
        assert!(result.is_ok());
        assert_eq!(data[0], 3);


text:
use crate::{
    array::{Array, BooleanArray, PrimitiveArray},
    buffer::MutableBuffer,
    types::Index,
};

use super::SortOptions;

/// Returns the indices that would sort a [`BooleanArray`].
pub fn sort_boolean<I: Index>(
    values: &BooleanArray,
    value_indices: Vec<I>,
    null_indices: Vec<I>,
    options: &SortOptions,
    limit: Option<usize>,
) -> PrimitiveArray<I> {
    let descending = options.descending;

    // create tuples that are used for sorting
    let mut valids = value_indices
        .into_iter()
        .map(|index| (index, values.value(index.to_usize())))
        .collect::<Vec<(I, bool)>>();

    let mut nulls = null_indices;

    if !descending {
        valids.sort_by(|a, b| a.1.cmp(&b.1));
    } else {
        valids.sort_by(|a, b| b.1.cmp(&a.1));
        // reverse to keep a stable ordering
        nulls.reverse();
    }

    let mut values = MutableBuffer::<I>::with_capacity(values.len());

    if options.nulls_first {
        values.extend_from_slice(nulls.as_slice());
        valids.iter().for_each(|x| values.push(x.0));
    } else {
        // nulls last
        valids.iter().for_each(|x| values.push(x.0));
        values.extend_from_slice(nulls.as_slice());
    }

    // un-efficient; there are much more performant ways of sorting nulls above, anyways.
    if let Some(limit) = limit {
        values.truncate(limit);
        values.shrink_to_fit();
    }

    PrimitiveArray::<I>::from_data(I::DATA_TYPE, values.into(), None)
}


text:
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! Demonstrates how to perform Kademlia queries on the IPFS network.
//!
//! You can pass as parameter a base58 peer ID to search for. If you don't pass any parameter, a
//! peer ID will be generated randomly.

use futures::prelude::*;
use libp2p::{
    PeerId,
    identity
};

fn main() {
    // Create a random key for ourselves.
    let local_key = identity::Keypair::generate_ed25519();
    let local_peer_id = PeerId::from(local_key.public());

    // Set up a an encrypted DNS-enabled TCP Transport over the Mplex protocol
    let transport = libp2p::build_development_transport(local_key);

    // Create a swarm to manage peers and events.
    let mut swarm = {
        // Create a Kademlia behaviour.
        // Note that normally the Kademlia process starts by performing lots of request in order
        // to insert our local node in the DHT. However here we use `without_init` because this
        // example is very ephemeral and we don't want to pollute the DHT. In a real world
        // application, you want to use `new` instead.
        let mut behaviour = libp2p::kad::Kademlia::without_init(local_peer_id.clone());
        behaviour.add_connected_address(&"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ".parse().unwrap(), "/ip4/104.131.131.82/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM".parse().unwrap(), "/ip4/104.236.179.241/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64".parse().unwrap(), "/ip4/104.236.76.40/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu".parse().unwrap(), "/ip4/128.199.219.111/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd".parse().unwrap(), "/ip4/178.62.158.247/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu".parse().unwrap(), "/ip6/2400:6180:0:d0::151:6001/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM".parse().unwrap(), "/ip6/2604:a880:1:20::203:d001/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64".parse().unwrap(), "/ip6/2604:a880:800:10::4a:5001/tcp/4001".parse().unwrap());
        behaviour.add_connected_address(&"QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd".parse().unwrap(), "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001".parse().unwrap());
        libp2p::core::Swarm::new(transport, behaviour, local_peer_id)
    };

    // Order Kademlia to search for a peer.
    let to_search: PeerId = if let Some(peer_id) = std::env::args().nth(1) {
        peer_id.parse().expect("Failed to parse peer ID to find")
    } else {
        identity::Keypair::generate_ed25519().public().into()
    };
    println!("Searching for {:?}", to_search);
    swarm.find_node(to_search);

    // Kick it off!
    tokio::run(futures::future::poll_fn(move || -> Result<_, ()> {
        loop {
            match swarm.poll().expect("Error while polling swarm") {
                Async::Ready(Some(ev @ libp2p::kad::KademliaOut::FindNodeResult { .. })) => {
                    println!("Result: {:#?}", ev);
                    return Ok(Async::Ready(()));
                },
                Async::Ready(Some(_)) => (),
                Async::Ready(None) | Async::NotReady => break,
            }
        }

        Ok(Async::NotReady)
    }));
}


text:
macro_rules! opt_leading_space {
    ($emitter:expr, $e:expr) => {
        if let Some(ref e) = $e {
            formatting_space!($emitter);
            emit!($emitter, e);
        }
    };
}

macro_rules! opt {
    ($emitter:expr, $e:expr) => {{
        if let Some(ref expr) = $e {
            emit!($emitter, expr);
        }
    }};
    ($emitter:expr, $e:expr,) => {{
        opt!($emitter, $e)
    }};
}

macro_rules! emit {
    ($emitter:expr, $e:expr) => {{
        crate::Node::emit_with(&$e, $emitter)?;
    }};
}

macro_rules! keyword {
    ($emitter:expr, $span:expr, $s:expr) => {
        $emitter.wr.write_keyword(Some($span), $s)?
    };
    ($emitter:expr, $s:expr) => {
        $emitter.wr.write_keyword(None, $s)?
    };
}

macro_rules! punct {
    ($emitter:expr, $sp:expr, ";") => {
        $emitter.wr.write_semi(Some($sp))?;
    };
    ($emitter:expr, $sp:expr, $s:expr) => {
        $emitter.wr.write_punct(Some($sp), $s)?;
    };

    ($emitter:expr, ";") => {
        $emitter.wr.write_semi(None)?
    };
    ($emitter:expr, $s:expr) => {
        $emitter.wr.write_punct(None, $s)?
    };
}

macro_rules! operator {
    ($emitter:expr, $sp:expr, $s:expr) => {
        $emitter.wr.write_operator(Some($sp), $s)?;
    };

    ($emitter:expr, $s:expr) => {
        $emitter.wr.write_operator(None, $s)?;
    };
}

macro_rules! space {
    ($emitter:expr) => {
        $emitter.wr.write_space()?
    };
    ($emitter:expr,) => {
        space!($emitter)
    };
}

macro_rules! formatting_space {
    ($emitter:expr) => {
        if !$emitter.cfg.minify {
            $emitter.wr.write_space()?;
        }
    };
    ($emitter:expr,) => {
        formatting_space!($emitter)
    };
}

/// This macro *may* emit a semicolon, if it's required in this context.
macro_rules! formatting_semi {
    ($emitter:expr) => {
        punct!($emitter, ";")
    };
    ($emitter:expr, ) => {
        punct!($emitter, ";")
    };
}

/// This macro *always* emits a semicolon, as it's required by the structure we
/// emit.
macro_rules! semi {
    ($emitter:expr, $sp:expr) => {
        $emitter.wr.write_semi(Some($sp))?;
    };
    ($emitter:expr) => {
        $emitter.wr.write_semi(None)?;
    };
}

///
/// - `srcmap!(true)` for start (span.lo)
/// - `srcmap!(false)` for end (span.hi)
macro_rules! srcmap {
    ($emitter:expr, $n:expr, true) => {{
        let bp = $n.span().lo;
        if !bp.is_dummy() {
            $emitter.wr.add_srcmap(bp)?;
        }
    }};
    ($emitter:expr, $n:expr, false) => {
        let hi = $n.span().hi;
        if !hi.is_dummy() {
            $emitter.wr.add_srcmap(hi)?;
        }
    };
}


text:
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum JobStatus {
  #[serde(rename = "unknown")]
  Unknown,
  #[serde(rename = "completed")]
  Completed,
  #[serde(rename = "error")]
  Error,
}

impl Default for JobStatus {
  fn default() -> Self {
    JobStatus::Unknown
  }
}

#[test]
pub fn test_job_status_json() {
  let json = serde_json::to_string(&JobStatus::Unknown).unwrap();
  assert_eq!("\"unknown\"", &json);
  let json = serde_json::to_string(&JobStatus::Completed).unwrap();
  assert_eq!("\"completed\"", &json);
  let json = serde_json::to_string(&JobStatus::Error).unwrap();
  assert_eq!("\"error\"", &json);
}


text:
//! Opens an empty window.

use amethyst::{
    input::is_key_down, prelude::*, utils::application_root_dir, window::WindowBundle,
    winit::VirtualKeyCode,
};

struct ExampleState;

impl SimpleState for ExampleState {
    fn handle_event(&mut self, _: StateData<'_, GameData>, event: StateEvent) -> SimpleTrans {
        if let StateEvent::Window(event) = event {
            if is_key_down(&event, VirtualKeyCode::Escape) {
                Trans::Quit
            } else {
                Trans::None
            }
        } else {
            Trans::None
        }
    }
}

fn main() -> amethyst::Result<()> {
    amethyst::start_logger(Default::default());

    let app_root = application_root_dir()?;
    let display_config_path = app_root.join("examples/window/config/display.ron");

    let assets_dir = app_root.join("examples/window/assets/");

    let game_data = GameDataBuilder::default()
        .with_bundle(WindowBundle::from_config_path(display_config_path)?);

    let mut game = Application::new(assets_dir, ExampleState, game_data)?;
    game.run();

    Ok(())
}


text:
//! Evaluation of a Nickel term.
//! The implementation of the Nickel abstract machine which evaluates a term. Note that this
//! machine is not currently formalized somewhere and is just a convenient name to designate the
//! current implementation.
//!
//! # The Nickel Abstract Machine
//! The abstract machine is a stack machine composed of the following elements:
//! - The term being currently evaluated
//! - The main stack, storing arguments, thunks and pending computations
//! - A pair of [environments](type.Environment.html), mapping identifiers to [closures](type.Closure.html):
//!     * The global environment contains builtin functions accessible from anywhere, and alive
//!     during the whole evaluation
//!     * The local environment contains the variables in scope of the current term and is subject
//!     to garbage collection (currently reference counting based)
//! - A [callstack](type.CallStack.html), mainly for error reporting purpose
//!
//! Depending on the shape of the current term, the following actions are preformed:
//!
//! ## Core calculus
//! - **Var(id)**: the term bound to `id` in the environment is fetched, and an update thunk is
//! pushed on the stack to indicate that once this term has been evaluated, the content of the
//! variable must be updated
//! - **App(func, arg)**: a closure containing the argument and the current environment is pushed
//! on the stack, and the applied term `func` is evaluated
//! - **Let(id, term, body)**: `term` is bound to `id` in the environment, and the machine proceeds with the evaluation of the body
//! - **Fun(id, body)**: Try to pop an argument from the stack. If there is some, we bound it to
//! `id` in the environment, and proceed with the body of the function. Otherwise, we are done: the
//! end result is an unapplied function
//! - **Thunk on stack**: If the evaluation of the current term is done, and there is one (or
//! several) thunk on the stack, this means we have to perform an update. Consecutive thunks are
//! popped from the stack and are updated to point to the current evaluated term.
//! - **Import**: Import must have been resolved before the evaluation starts. An unresolved import
//! causes an [`InternalError`](../error/enum.EvalError.html#variant.InternalError). A resolved
//! import, identified by a `FileId`, is retrieved from the import resolver and evaluation proceeds.
//!
//! ## Contracts
//!
//! - **`Assume(type, label, term)`** (or `Promise(type, label, term)`): replace the current term
//! with the contract corresponding to `types`, applied to label and term (`contract label term`).
//!
//! ## Operators
//!
//! Operators are strict by definition. To evaluate say `exp1 + exp2`, the following steps
//! have to be performed:
//! - `exp1` needs to be evaluated. The result must be saved somewhere, together with the resulting
//! environment
//! - `exp2`: same thing for `exp2`
//! - Finally, the implementation of `+` can proceed with the computation
//!
//! We detail the case of binary operators, as the case of unary ones is similar and simpler.
//!
//! - **Op(op, first, second)**: push an `OpFirst` element on the stack, which saves the operator
//! `op`, the second argument `second` and the current environment, and proceed with the evaluation
//! of `first`
//! - **OpFirst on stack**: if the evaluation of the current term is done and there is an `OpFirst`
//! marker on the stack, then:
//!     1. Extract the saved operator, the second argument and the environment `env2` from the marker
//!     2. Push an `OpSecond` marker, saving the operator and the evaluated form of the first
//!        argument with its environment
//!     3. Proceed with the evaluation of the second argument in environment `env2`
//! - **OpSecond on stack**: once the second term is evaluated, we can get back the operator and
//! the first term evaluated, and forward all both arguments evaluated and their respective
//! environment to the specific implementation of the operator (located in
//! [operation](../operation/index.html), or in [merge](../merge/index.html) for `merge`).
//!
//! ## Enriched values
//!
//! The evaluation of enriched values is controlled by the parameter `enriched_strict`. If it is
//! set to true (which is usually the case), the machine tries to extract a simple value from it:
//!  - **Contract**: raise an error. This usually means that an access to a field was attempted,
//!  and that this field had a contract to satisfy, but it was never defined.
//!  - **Default(value)**: an access to a field which has a default value. Proceed with the
//!  evaluation of this value
//!  - **ContractDefault(type, label, value)**: same as above, but the field also has an attached
//!  contract.  Proceed with the evaluation of `Assume(type, label, value)` to ensure that the
//!  default value satisfies this contract.
//!
//!  If `enriched_strict` is set to false, as it is when evaluating `merge`, the machine does not
//!  evaluate enriched values further, and consider the term evaluated.
//!
//! # Garbage collection
//!
//! Currently the machine relies on Rust's reference counting to manage memory. Precisely, the
//! environment stores `Rc<RefCell<Closure>>` objects, which are reference-counted pointers to a
//! mutable memory cell. This means that we do not deep copy everything everywhere, but this is
//! probably suboptimal for a functional language and is unable to collect cyclic data, which may
//! appear inside recursive records in the future. An adapted garbage collector is probably
//! something to consider at some point.
use crate::cache::ImportResolver;
use crate::environment::Environment as GenericEnvironment;
use crate::error::EvalError;
use crate::identifier::Ident;
use crate::mk_app;
use crate::operation::{continuate_operation, OperationCont};
use crate::position::TermPos;
use crate::stack::Stack;
use crate::term::{make as mk_term, BinaryOp, MetaValue, RichTerm, StrChunk, Term, UnaryOp};
use std::cell::{Ref, RefCell, RefMut};
use std::rc::{Rc, Weak};

/// The state of a thunk.
///
/// When created, a thunk is flagged as suspended. When accessed for the first time, a corresponding
/// [`ThunkUpdateFrame`](./struct.ThunkUpdateFrame.html) is pushed on the stack and the thunk is
/// flagged as black-hole. This prevents direct infinite recursions, since if a thunk is
/// re-accessed while still in a black-hole state, we are sure that the evaluation will loop, and
/// we can thus error out before overflowing the stack or looping forever. Finally, once the
/// content of a thunk has been evaluated, the thunk is updated with the new value and flagged as
/// evaluated, so that future accesses won't even push an update frame on the stack.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ThunkState {
    Blackholed,
    Suspended,
    Evaluated,
}

/// The mutable data stored inside a thunk.
#[derive(Clone, Debug, PartialEq)]
pub struct ThunkData {
    closure: Closure,
    state: ThunkState,
}

impl ThunkData {
    pub fn new(closure: Closure) -> Self {
        ThunkData {
            closure,
            state: ThunkState::Suspended,
        }
    }
}

/// A thunk.
///
/// A thunk is a shared suspended computation. It is the primary device for the implementation of
/// lazy evaluation.
#[derive(Clone, Debug, PartialEq)]
pub struct Thunk {
    data: Rc<RefCell<ThunkData>>,
    ident_kind: IdentKind,
}

/// A black-holed thunk was accessed, which would lead to infinite recursion.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BlackholedError;

impl Thunk {
    pub fn new(closure: Closure, ident_kind: IdentKind) -> Self {
        Thunk {
            data: Rc::new(RefCell::new(ThunkData::new(closure))),
            ident_kind,
        }
    }

    pub fn state(&self) -> ThunkState {
        self.data.borrow().state
    }

    /// Set the state to evaluated.
    pub fn set_evaluated(&mut self) {
        self.data.borrow_mut().state = ThunkState::Evaluated;
    }

    /// Generate an update frame from this thunk and set the state to `Blackholed`. Return an
    /// error if the thunk was already black-holed.
    pub fn mk_update_frame(&mut self) -> Result<ThunkUpdateFrame, BlackholedError> {
        if self.data.borrow().state == ThunkState::Blackholed {
            return Err(BlackholedError);
        }

        self.data.borrow_mut().state = ThunkState::Blackholed;

        Ok(ThunkUpdateFrame {
            data: Rc::downgrade(&self.data),
            ident_kind: self.ident_kind,
        })
    }

    /// Immutably borrow the inner closure. Panic if there is another active mutable borrow.
    pub fn borrow(&self) -> Ref<'_, Closure> {
        let (closure, _) = Ref::map_split(self.data.borrow(), |data| {
            let ThunkData {
                ref closure,
                ref state,
            } = data;
            (closure, state)
        });

        closure
    }

    /// Mutably borrow the inner closure. Panic if there is any other active borrow.
    pub fn borrow_mut(&mut self) -> RefMut<'_, Closure> {
        let (closure, _) = RefMut::map_split(self.data.borrow_mut(), |data| {
            let ThunkData {
                ref mut closure,
                ref mut state,
            } = data;
            (closure, state)
        });

        closure
    }

    /// Get an owned clone of the inner closure.
    pub fn get_owned(&self) -> Closure {
        self.data.borrow().closure.clone()
    }

    pub fn ident_kind(&self) -> IdentKind {
        self.ident_kind
    }

    /// Consume the thunk and return an owned closure. Avoid cloning if this thunk is the only
    /// reference to the inner closure.
    pub fn into_closure(self) -> Closure {
        match Rc::try_unwrap(self.data) {
            Ok(inner) => inner.into_inner().closure,
            Err(rc) => rc.borrow().clone().closure,
        }
    }
}

/// A thunk update frame.
///
/// A thunk update frame is put on the stack whenever a variable is entered, such that once this
/// variable is evaluated, the corresponding thunk can be updated. It is similar to a thunk but it
/// holds a weak reference to the inner closure, to avoid unnecessarily keeping the underlying
/// closure alive.
#[derive(Clone, Debug)]
pub struct ThunkUpdateFrame {
    data: Weak<RefCell<ThunkData>>,
    ident_kind: IdentKind,
}

impl ThunkUpdateFrame {
    /// Update the corresponding thunk with a closure. Set the state to `Evaluated`
    ///
    /// # Return
    ///
    /// - `true` if the thunk was successfully updated
    /// - `false` if the corresponding closure has been dropped since
    pub fn update(self, closure: Closure) -> bool {
        if let Some(data) = Weak::upgrade(&self.data) {
            *data.borrow_mut() = ThunkData {
                closure,
                state: ThunkState::Evaluated,
            };
            true
        } else {
            false
        }
    }
}

/// A call stack, saving the history of function calls.
///
/// In a lazy language as Nickel, there are no well delimited stack frames due to how function
/// application is evaluated. This can make things hard to debug for the user, hence additional
/// information about the history of function calls is stored in the call stack, for error
/// reporting and debugging purposes.
pub type CallStack = Vec<StackElem>;

/// A call stack element.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum StackElem {
    /// A function body was entered. The position is the position of the original application.
    App(TermPos),
    /// A variable was entered.
    Var(IdentKind, Ident, TermPos),
}

/// Kind of an identifier.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum IdentKind {
    Let(),
    Lam(),
    Record(),
}

/// A closure, a term together with an environment.
#[derive(Clone, Debug, PartialEq)]
pub struct Closure {
    pub body: RichTerm,
    pub env: Environment,
}

impl Closure {
    pub fn atomic_closure(body: RichTerm) -> Closure {
        Closure {
            body,
            env: Environment::new(),
        }
    }
}

pub type Environment = GenericEnvironment<Ident, Thunk>;

/// Raised when trying to build an environment from a term which is not a record.
#[derive(Clone, Debug)]
pub enum EnvBuildError {
    NotARecord(RichTerm),
}

/// Add the bindings of a record to an environment. Ignore the fields defined by interpolation.
pub fn env_add_term(env: &mut Environment, rt: RichTerm) -> Result<(), EnvBuildError> {
    let RichTerm { term, pos } = rt;

    match *term {
        Term::Record(bindings, _) | Term::RecRecord(bindings, ..) => {
            let ext = bindings.into_iter().map(|(id, t)| {
                (
                    id,
                    Thunk::new(Closure::atomic_closure(t), IdentKind::Record()),
                )
            });

            env.extend(ext);
            Ok(())
        }
        t => Err(EnvBuildError::NotARecord(RichTerm::new(t, pos))),
    }
}

/// Bind a closure in an environment.
pub fn env_add(env: &mut Environment, id: Ident, rt: RichTerm, local_env: Environment) {
    let closure = Closure {
        body: rt,
        env: local_env,
    };
    env.insert(id, Thunk::new(closure, IdentKind::Let()));
}

/// Determine if a thunk is worth being put on the stack for future update.
///
/// Typically, WHNFs and enriched values will not be evaluated to a simpler expression and are not
/// worth updating.
fn should_update(t: &Term) -> bool {
    !t.is_whnf() && !t.is_metavalue()
}

/// Evaluate a Nickel term. Wrapper around [eval_closure](fn.eval_closure.html) that starts from an
/// empty local environment and drops the final environment.
pub fn eval<R>(t0: RichTerm, global_env: &Environment, resolver: &mut R) -> Result<Term, EvalError>
where
    R: ImportResolver,
{
    eval_closure(Closure::atomic_closure(t0), global_env, resolver, true).map(|(term, _)| term)
}

/// Fully evaluate a Nickel term: the result is not a WHNF but to a value with all variables substituted.
pub fn eval_full<R>(
    t0: RichTerm,
    global_env: &Environment,
    resolver: &mut R,
) -> Result<Term, EvalError>
where
    R: ImportResolver,
{
    use crate::transformations::fresh_var;

    let var = fresh_var();
    // Desugar to let x = term in deepSeq x x
    let wrapper = mk_term::let_in(
        var.clone(),
        t0,
        mk_app!(
            mk_term::op1(UnaryOp::DeepSeq(), Term::Var(var.clone())),
            Term::Var(var)
        ),
    );
    eval_closure(Closure::atomic_closure(wrapper), global_env, resolver, true)
        .map(|(term, env)| subst(term.into(), &global_env, &env).into())
}

/// Evaluate a Nickel Term, stopping when a meta value is encountered at the top-level without
/// unwrapping it. Then evaluate the underlying value, and substitute variables in order to obtain
/// a WHNF that is printable.
///
/// Used to query the metadata of a value.
pub fn eval_meta<R>(
    t: RichTerm,
    global_env: &Environment,
    resolver: &mut R,
) -> Result<Term, EvalError>
where
    R: ImportResolver,
{
    let (term, env) = eval_closure(Closure::atomic_closure(t), &global_env, resolver, false)?;

    match term {
        Term::MetaValue(mut meta) => {
            if let Some(t) = meta.value.take() {
                let pos = t.pos;
                let (evaluated, env) =
                    eval_closure(Closure { body: t, env }, global_env, resolver, true)?;
                let substituted = subst(RichTerm::new(evaluated, pos), global_env, &env);

                meta.value.replace(substituted);
            }

            Ok(Term::MetaValue(meta))
        }
        term => Ok(term),
    }
}

/// The main loop of evaluation.
///
/// Implement the evaluation of the core language, which includes application, thunk update,
/// evaluation of the arguments of operations, and a few others. The specific implementations of
/// primitive operations is delegated to the modules [operation](../operation/index.html) and
/// [merge](../merge/index.html).
///
/// # Arguments
///
/// - `t0`: the term to evaluate
/// - `global_env`: the global environment containing the builtin functions of the language. Accessible from anywhere in the
/// program.
/// - `resolver`: the interface to fetch imports.
/// - `enriched_strict`: if evaluation is strict with respect to enriched values (metavalues).
///   Standard evaluation should be strict, but set to false when extracting the metadata of value.
///
/// # Return
///
/// Either:
///  - an evaluation error
///  - the evaluated term with its final environment
pub fn eval_closure<R>(
    mut clos: Closure,
    global_env: &Environment,
    resolver: &mut R,
    mut enriched_strict: bool,
) -> Result<(Term, Environment), EvalError>
where
    R: ImportResolver,
{
    let mut call_stack = CallStack::new();
    let mut stack = Stack::new();

    loop {
        let Closure {
            body: RichTerm {
                term: boxed_term,
                pos,
            },
            mut env,
        } = clos;
        let term = *boxed_term;

        clos = match term {
            Term::Var(x) => {
                let mut thunk = env
                    .get(&x)
                    .or_else(|| global_env.get(&x))
                    .ok_or_else(|| EvalError::UnboundIdentifier(x.clone(), pos))?;
                std::mem::drop(env); // thunk may be a 1RC pointer

                if thunk.state() != ThunkState::Evaluated {
                    if should_update(&thunk.borrow().body.term) {
                        match thunk.mk_update_frame() {
                            Ok(thunk_upd) => stack.push_thunk(thunk_upd),
                            Err(BlackholedError) => {
                                return Err(EvalError::InfiniteRecursion(call_stack, pos))
                            }
                        }
                    }
                    // If the thunk isn't to be updated, directly set the evaluated flag.
                    else {
                        thunk.set_evaluated();
                    }
                }

                call_stack.push(StackElem::Var(thunk.ident_kind(), x, pos));
                thunk.into_closure()
            }
            Term::App(t1, t2) => {
                stack.push_arg(
                    Closure {
                        body: t2,
                        env: env.clone(),
                    },
                    pos,
                );
                Closure { body: t1, env }
            }
            Term::Let(x, s, t) => {
                let closure = Closure {
                    body: s,
                    env: env.clone(),
                };
                env.insert(x, Thunk::new(closure, IdentKind::Let()));
                Closure { body: t, env }
            }
            Term::Switch(exp, cases, default) => {
                let has_default = default.is_some();

                if let Some(t) = default {
                    stack.push_arg(
                        Closure {
                            body: t,
                            env: env.clone(),
                        },
                        pos,
                    );
                }

                stack.push_arg(
                    Closure {
                        body: RichTerm::new(Term::Record(cases, Default::default()), pos),
                        env: env.clone(),
                    },
                    pos,
                );

                Closure {
                    body: RichTerm::new(Term::Op1(UnaryOp::Switch(has_default), exp), pos),
                    env,
                }
            }
            Term::Op1(op, t) => {
                let prev_strict = enriched_strict;
                enriched_strict = true;
                stack.push_op_cont(
                    OperationCont::Op1(op, t.pos, prev_strict),
                    call_stack.len(),
                    pos,
                );
                Closure { body: t, env }
            }
            Term::Op2(op, fst, snd) => {
                let prev_strict = enriched_strict;


text:
// Copyright 2012-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.

//! Deprecated: replaced by `usize`.
//!
//! The rollout of the new type will gradually take place over the
//! alpha cycle along with the development of clearer conventions
//! around integer types.

#![deprecated = "replaced by usize"]

uint_module! { uint, int, ::int::BITS }