<commit_before><commit_msg>Add an example app that uses the animation API<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate gleam;
extern crate glutin;
extern crate webrender;
extern crate webrender_traits;

#[macro_use]
extern crate lazy_static;

#[path="common/boilerplate.rs"]
mod boilerplate;

use boilerplate::HandyDandyRectBuilder;
use std::sync::Mutex;
use webrender_traits::*;

// This example creates a 100x100 white rect and allows the user to move it
// around by using the arrow keys. It does this by using the animation API.

fn body(builder: &mut DisplayListBuilder,
        _pipeline_id: &PipelineId,
        _layout_size: &LayoutSize)
{
    // Create a 100x100 stacking context with an animatable transform property.
    // Note the magic "42" we use as the animation key. That is used to update
    // the transform in the keyboard event handler code.
    let bounds = (0,0).to(100, 100);
    builder.push_stacking_context(webrender_traits::ScrollPolicy::Scrollable,
                                  bounds,
                                  Some(PropertyBinding::Binding(PropertyBindingKey::new(42))),
                                  TransformStyle::Flat,
                                  None,
                                  webrender_traits::MixBlendMode::Normal,
                                  Vec::new());

    // Fill it with a white rect
    let clip = builder.push_clip_region(&bounds, vec![], None);
    builder.push_rect(bounds,
                      clip,
                      ColorF::new(1.0, 1.0, 1.0, 1.0));

    builder.pop_stacking_context();
}

lazy_static! {
    static ref TRANSFORM: Mutex<LayoutTransform> = Mutex::new(LayoutTransform::identity());
}

fn event_handler(event: &glutin::Event,
                 api: &RenderApi)
{
    match *event {
        glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(key)) => {
            let offset = match key {
                 glutin::VirtualKeyCode::Down => (0.0, 10.0),
                 glutin::VirtualKeyCode::Up => (0.0, -10.0),
                 glutin::VirtualKeyCode::Right => (10.0, 0.0),
                 glutin::VirtualKeyCode::Left => (-10.0, 0.0),
                 _ => return,
            };
            // Update the transform based on the keyboard input and push it to
            // webrender using the generate_frame API. This will recomposite with
            // the updated transform.
            let new_transform = TRANSFORM.lock().unwrap().post_translated(offset.0, offset.1, 0.0);
            api.generate_frame(Some(DynamicProperties {
                transforms: vec![
                  PropertyValue {
                    key: PropertyBindingKey::new(42),
                    value: new_transform,
                  },
                ],
                floats: vec![],
            }));
            *TRANSFORM.lock().unwrap() = new_transform;
        }
        _ => ()
    }
}

fn main() {
    boilerplate::main_wrapper(body, event_handler);
}
<|endoftext|>


<commit_before><commit_msg>Test(todo): add note about making them into integration tests :(<commit_after><|endoftext|>


<commit_before><commit_msg>Backtick missing in documentation. (#580)<commit_after><|endoftext|>


<commit_before><commit_msg>create pwm<commit_after>use core::any::{Any, TypeId};
use core::marker::Unsize;

use cast::{u16, u32};
use hal;
use stm32f411::{GPIOA, RCC, TIM1};

use timer::{Channel, TIM};

/// PWM driver
pub struct Pwm<'a, T>(pub &'a T)
where
    T: 'a;

impl<'a> Pwm<'a, TIM1> {
    /// Initializes the PWM module
    pub fn init<P>(&self, period: P)
    where
        P: Into<::apb2::Ticks>,
    {
        self._init(period.into())
    }

    fn _init(&self, period: ::apb2::Ticks) {
        let tim1 = self.0;

        // PWM mode 1
        tim1.ccmr1_output.modify(|_, w| unsafe {{
            w.oc1pe().set_bit()
                .oc1m().bits(0b110)
                .oc2pe().set_bit()
                .oc2m().bits(0b110)
        }});

        tim1.ccmr2_output.modify(|_, w| unsafe{{
            w.oc3pe().set_bit()
                .oc3m().bits(0b110)
                .oc4pe().set_bit()
                .oc4m().bits(0b110)
        }});

        tim1.ccer.modify(|_, w| {
            w.cc1p().clear_bit()
                .cc2p().clear_bit()
                .cc3p().clear_bit()
                .cc4p().clear_bit()
        });

        tim1.bdtr.modify(|_, w| w.moe().set_bit());

        self._set_period(period);

        tim1.cr1.write(|w| unsafe {
            w.cms().bits(0b00)
                .dir().set_bit()
                .opm().clear_bit()
                .cen().set_bit()
        });
    }

    fn _set_period(&self, period: ::apb2::Ticks) {
        let period = period.0;

        let psc = u16((period - 1) / (1 << 16)).unwrap();
        self.0.psc.write(|w| unsafe{ w.psc().bits(psc) });

        let arr = u16(period / u32(psc + 1)).unwrap();
        self.0.arr.write(|w| unsafe{ w.arr().bits(arr) });
    }
}

impl<'a> hal::Pwm for Pwm<'a, TIM1> {
    type Channel = Channel;
    type Time = ::apb2::Ticks;
    type Duty = u16;

    fn disable(&self, channel: Channel) {
        match channel {
            Channel::_1 => self.0.ccer.modify(|_, w| w.cc1e().clear_bit()),
            Channel::_2 => self.0.ccer.modify(|_, w| w.cc2e().clear_bit()),
            Channel::_3 => self.0.ccer.modify(|_, w| w.cc3e().clear_bit()),
            Channel::_4 => self.0.ccer.modify(|_, w| w.cc4e().clear_bit()),
        }
    }

    fn enable(&self, channel: Channel) {
        match channel {
            Channel::_1 => self.0.ccer.modify(|_, w| w.cc1e().set_bit()),
            Channel::_2 => self.0.ccer.modify(|_, w| w.cc2e().set_bit()),
            Channel::_3 => self.0.ccer.modify(|_, w| w.cc3e().set_bit()),
            Channel::_4 => self.0.ccer.modify(|_, w| w.cc4e().set_bit()),
        }
    }

    fn get_duty(&self, channel: Channel) -> u16 {
        match channel {
            Channel::_1 => self.0.ccr1.read().ccr1().bits(),
            Channel::_2 => self.0.ccr2.read().ccr2().bits(),
            Channel::_3 => self.0.ccr3.read().ccr3().bits(),
            Channel::_4 => self.0.ccr4.read().ccr4().bits(),
        }
    }

    fn get_max_duty(&self) -> u16 {
        self.0.arr.read().arr().bits()
    }

    fn get_period(&self) -> ::apb2::Ticks {
        ::apb2::Ticks(u32(self.0.psc.read().bits() * self.0.arr.read().bits()))
    }

    fn set_duty(&self, channel: Channel, duty: u16) {
        unsafe {
            match channel {
                Channel::_1 => self.0.ccr1.write(|w| w.ccr1().bits(duty)),
                Channel::_2 => self.0.ccr2.write(|w| w.ccr2().bits(duty)),
                Channel::_3 => self.0.ccr3.write(|w| w.ccr3().bits(duty)),
                Channel::_4 => self.0.ccr4.write(|w| w.ccr4().bits(duty)),
            }
        }
    }

    fn set_period<P>(&self, period: P)
    where
        P: Into<::apb2::Ticks>,
    {
        self._set_period(period.into())
    }
}<|endoftext|>


<commit_before>// Copyright 2015 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 the simd_reduce_{op} intrinsics produce the correct results.

#![feature(repr_simd, platform_intrinsics)]
#[allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone)]
struct i32x4(pub i32, pub i32, pub i32, pub i32);

#[repr(simd)]
#[derive(Copy, Clone)]
struct u32x4(pub u32, pub u32, pub u32, pub u32);

#[repr(simd)]
#[derive(Copy, Clone)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

#[repr(simd)]
#[derive(Copy, Clone)]
struct b8x4(pub i8, pub i8, pub i8, pub i8);

#[repr(simd)]
#[derive(Copy, Clone)]
struct b8x16(
    pub i8, pub i8, pub i8, pub i8,
    pub i8, pub i8, pub i8, pub i8,
    pub i8, pub i8, pub i8, pub i8,
    pub i8, pub i8, pub i8, pub i8
);

extern "platform-intrinsic" {
    fn simd_reduce_add_unordered<T, U>(x: T) -> U;
    fn simd_reduce_mul_unordered<T, U>(x: T) -> U;
    fn simd_reduce_add_ordered<T, U>(x: T, acc: U) -> U;
    fn simd_reduce_mul_ordered<T, U>(x: T, acc: U) -> U;
    fn simd_reduce_min<T, U>(x: T) -> U;
    fn simd_reduce_max<T, U>(x: T) -> U;
    fn simd_reduce_min_nanless<T, U>(x: T) -> U;
    fn simd_reduce_max_nanless<T, U>(x: T) -> U;
    fn simd_reduce_and<T, U>(x: T) -> U;
    fn simd_reduce_or<T, U>(x: T) -> U;
    fn simd_reduce_xor<T, U>(x: T) -> U;
    fn simd_reduce_all<T>(x: T) -> bool;
    fn simd_reduce_any<T>(x: T) -> bool;
}

fn main() {
    unsafe {
        let x = i32x4(1, -2, 3, 4);
        let r: i32 = simd_reduce_add_unordered(x);
        assert_eq!(r, 6_i32);
        let r: i32 = simd_reduce_mul_unordered(x);
        assert_eq!(r, -24_i32);
        let r: i32 = simd_reduce_add_ordered(x, -1);
        assert_eq!(r, 5_i32);
        let r: i32 = simd_reduce_mul_ordered(x, -1);
        assert_eq!(r, 24_i32);

        let r: i32 = simd_reduce_min(x);
        assert_eq!(r, -2_i32);
        let r: i32 = simd_reduce_max(x);
        assert_eq!(r, 4_i32);

        let x = i32x4(-1, -1, -1, -1);
        let r: i32 = simd_reduce_and(x);
        assert_eq!(r, -1_i32);
        let r: i32 = simd_reduce_or(x);
        assert_eq!(r, -1_i32);
        let r: i32 = simd_reduce_xor(x);
        assert_eq!(r, 0_i32);

        let x = i32x4(-1, -1, 0, -1);
        let r: i32 = simd_reduce_and(x);
        assert_eq!(r, 0_i32);
        let r: i32 = simd_reduce_or(x);
        assert_eq!(r, -1_i32);
        let r: i32 = simd_reduce_xor(x);
        assert_eq!(r, -1_i32);
    }

    unsafe {
        let x = u32x4(1, 2, 3, 4);
        let r: u32 = simd_reduce_add_unordered(x);
        assert_eq!(r, 10_u32);
        let r: u32 = simd_reduce_mul_unordered(x);
        assert_eq!(r, 24_u32);
        let r: u32 = simd_reduce_add_ordered(x, 1);
        assert_eq!(r, 11_u32);
        let r: u32 = simd_reduce_mul_ordered(x, 2);
        assert_eq!(r, 48_u32);

        let r: u32 = simd_reduce_min(x);
        assert_eq!(r, 1_u32);
        let r: u32 = simd_reduce_max(x);
        assert_eq!(r, 4_u32);

        let t = u32::max_value();
        let x = u32x4(t, t, t, t);
        let r: u32 = simd_reduce_and(x);
        assert_eq!(r, t);
        let r: u32 = simd_reduce_or(x);
        assert_eq!(r, t);
        let r: u32 = simd_reduce_xor(x);
        assert_eq!(r, 0_u32);

        let x = u32x4(t, t, 0, t);
        let r: u32 = simd_reduce_and(x);
        assert_eq!(r, 0_u32);
        let r: u32 = simd_reduce_or(x);
        assert_eq!(r, t);
        let r: u32 = simd_reduce_xor(x);
        assert_eq!(r, t);
    }

    unsafe {
        let x = f32x4(1., -2., 3., 4.);
        let r: f32 = simd_reduce_add_unordered(x);
        assert_eq!(r, 6_f32);
        let r: f32 = simd_reduce_mul_unordered(x);
        assert_eq!(r, -24_f32);
        // FIXME: only works correctly for accumulator, 0:
        // https://bugs.llvm.org/show_bug.cgi?id=36734
        let r: f32 = simd_reduce_add_ordered(x, 0.);
        assert_eq!(r, 6_f32);
        // FIXME: only works correctly for accumulator, 1:
        // https://bugs.llvm.org/show_bug.cgi?id=36734
        let r: f32 = simd_reduce_mul_ordered(x, 1.);
        assert_eq!(r, -24_f32);

        let r: f32 = simd_reduce_min(x);
        assert_eq!(r, -2_f32);
        let r: f32 = simd_reduce_max(x);
        assert_eq!(r, 4_f32);
        let r: f32 = simd_reduce_min_nanless(x);
        assert_eq!(r, -2_f32);
        let r: f32 = simd_reduce_max_nanless(x);
        assert_eq!(r, 4_f32);
    }

    unsafe {
        let x = b8x4(!0, !0, !0, !0);
        let r: bool = simd_reduce_all(x);
        assert_eq!(r, true);
        let r: bool = simd_reduce_any(x);
        assert_eq!(r, true);

        let x = b8x4(!0, !0, 0, !0);
        let r: bool = simd_reduce_all(x);
        assert_eq!(r, false);
        let r: bool = simd_reduce_any(x);
        assert_eq!(r, true);

        let x = b8x4(0, 0, 0, 0);
        let r: bool = simd_reduce_all(x);
        assert_eq!(r, false);
        let r: bool = simd_reduce_any(x);
        assert_eq!(r, false);
    }
}
<commit_msg>add min-llvm version to reduction tests<commit_after>// Copyright 2015 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.

// min-llvm-version 5.0

// Test that the simd_reduce_{op} intrinsics produce the correct results.

#![feature(repr_simd, platform_intrinsics)]
#[allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone)]
struct i32x4(pub i32, pub i32, pub i32, pub i32);

#[repr(simd)]
#[derive(Copy, Clone)]
struct u32x4(pub u32, pub u32, pub u32, pub u32);

#[repr(simd)]
#[derive(Copy, Clone)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

#[repr(simd)]
#[derive(Copy, Clone)]
struct b8x4(pub i8, pub i8, pub i8, pub i8);

#[repr(simd)]
#[derive(Copy, Clone)]
struct b8x16(
    pub i8, pub i8, pub i8, pub i8,
    pub i8, pub i8, pub i8, pub i8,
    pub i8, pub i8, pub i8, pub i8,
    pub i8, pub i8, pub i8, pub i8
);

extern "platform-intrinsic" {
    fn simd_reduce_add_unordered<T, U>(x: T) -> U;
    fn simd_reduce_mul_unordered<T, U>(x: T) -> U;
    fn simd_reduce_add_ordered<T, U>(x: T, acc: U) -> U;
    fn simd_reduce_mul_ordered<T, U>(x: T, acc: U) -> U;
    fn simd_reduce_min<T, U>(x: T) -> U;
    fn simd_reduce_max<T, U>(x: T) -> U;
    fn simd_reduce_min_nanless<T, U>(x: T) -> U;
    fn simd_reduce_max_nanless<T, U>(x: T) -> U;
    fn simd_reduce_and<T, U>(x: T) -> U;
    fn simd_reduce_or<T, U>(x: T) -> U;
    fn simd_reduce_xor<T, U>(x: T) -> U;
    fn simd_reduce_all<T>(x: T) -> bool;
    fn simd_reduce_any<T>(x: T) -> bool;
}

fn main() {
    unsafe {
        let x = i32x4(1, -2, 3, 4);
        let r: i32 = simd_reduce_add_unordered(x);
        assert_eq!(r, 6_i32);
        let r: i32 = simd_reduce_mul_unordered(x);
        assert_eq!(r, -24_i32);
        let r: i32 = simd_reduce_add_ordered(x, -1);
        assert_eq!(r, 5_i32);
        let r: i32 = simd_reduce_mul_ordered(x, -1);
        assert_eq!(r, 24_i32);

        let r: i32 = simd_reduce_min(x);
        assert_eq!(r, -2_i32);
        let r: i32 = simd_reduce_max(x);
        assert_eq!(r, 4_i32);

        let x = i32x4(-1, -1, -1, -1);
        let r: i32 = simd_reduce_and(x);
        assert_eq!(r, -1_i32);
        let r: i32 = simd_reduce_or(x);
        assert_eq!(r, -1_i32);
        let r: i32 = simd_reduce_xor(x);
        assert_eq!(r, 0_i32);

        let x = i32x4(-1, -1, 0, -1);
        let r: i32 = simd_reduce_and(x);
        assert_eq!(r, 0_i32);
        let r: i32 = simd_reduce_or(x);
        assert_eq!(r, -1_i32);
        let r: i32 = simd_reduce_xor(x);
        assert_eq!(r, -1_i32);
    }

    unsafe {
        let x = u32x4(1, 2, 3, 4);
        let r: u32 = simd_reduce_add_unordered(x);
        assert_eq!(r, 10_u32);
        let r: u32 = simd_reduce_mul_unordered(x);
        assert_eq!(r, 24_u32);
        let r: u32 = simd_reduce_add_ordered(x, 1);
        assert_eq!(r, 11_u32);
        let r: u32 = simd_reduce_mul_ordered(x, 2);
        assert_eq!(r, 48_u32);

        let r: u32 = simd_reduce_min(x);
        assert_eq!(r, 1_u32);
        let r: u32 = simd_reduce_max(x);
        assert_eq!(r, 4_u32);

        let t = u32::max_value();
        let x = u32x4(t, t, t, t);
        let r: u32 = simd_reduce_and(x);
        assert_eq!(r, t);
        let r: u32 = simd_reduce_or(x);
        assert_eq!(r, t);
        let r: u32 = simd_reduce_xor(x);
        assert_eq!(r, 0_u32);

        let x = u32x4(t, t, 0, t);
        let r: u32 = simd_reduce_and(x);
        assert_eq!(r, 0_u32);
        let r: u32 = simd_reduce_or(x);
        assert_eq!(r, t);
        let r: u32 = simd_reduce_xor(x);
        assert_eq!(r, t);
    }

    unsafe {
        let x = f32x4(1., -2., 3., 4.);
        let r: f32 = simd_reduce_add_unordered(x);
        assert_eq!(r, 6_f32);
        let r: f32 = simd_reduce_mul_unordered(x);
        assert_eq!(r, -24_f32);
        // FIXME: only works correctly for accumulator, 0:
        // https://bugs.llvm.org/show_bug.cgi?id=36734
        let r: f32 = simd_reduce_add_ordered(x, 0.);
        assert_eq!(r, 6_f32);
        // FIXME: only works correctly for accumulator, 1:
        // https://bugs.llvm.org/show_bug.cgi?id=36734
        let r: f32 = simd_reduce_mul_ordered(x, 1.);
        assert_eq!(r, -24_f32);

        let r: f32 = simd_reduce_min(x);
        assert_eq!(r, -2_f32);
        let r: f32 = simd_reduce_max(x);
        assert_eq!(r, 4_f32);
        let r: f32 = simd_reduce_min_nanless(x);
        assert_eq!(r, -2_f32);
        let r: f32 = simd_reduce_max_nanless(x);
        assert_eq!(r, 4_f32);
    }

    unsafe {
        let x = b8x4(!0, !0, !0, !0);
        let r: bool = simd_reduce_all(x);
        assert_eq!(r, true);
        let r: bool = simd_reduce_any(x);
        assert_eq!(r, true);

        let x = b8x4(!0, !0, 0, !0);
        let r: bool = simd_reduce_all(x);
        assert_eq!(r, false);
        let r: bool = simd_reduce_any(x);
        assert_eq!(r, true);

        let x = b8x4(0, 0, 0, 0);
        let r: bool = simd_reduce_all(x);
        assert_eq!(r, false);
        let r: bool = simd_reduce_any(x);
        assert_eq!(r, false);
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #27132 - apasel422:issue-23491, r=arielb1<commit_after>// Copyright 2015 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.

#![feature(box_syntax)]

struct Node<T: ?Sized>(T);

fn main() {
    let x: Box<Node<[isize]>> = box Node([]);
}
<|endoftext|>


<commit_before>use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];
        self.offset += 1;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Add todo<commit_after>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];
        self.offset += 1;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before>use redox::*;

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn reload(&mut self) {
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                let mut string = String::new();
                file.read_to_string(&mut string);
                self.string = string;
            }
            None => self.string = String::new(),
        }
    }

    fn save(&mut self) {
        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            None => {
                //TODO: Ask for file to save to
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")")).unwrap();

        self.url = url.to_string();
        self.file = File::open(&self.url);

        self.reload();
        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            K_ESC => break,
                            K_BKSP => if self.offset > 0 {
                                self.string = self.string[0 .. self.offset - 1].to_string() +
                                              &self.string[self.offset .. self.string.len()];
                                self.offset -= 1;
                            },
                            K_DEL => if self.offset < self.string.len() {
                                self.string = self.string[0 .. self.offset].to_string() +
                                              &self.string[self.offset + 1 .. self.string.len() - 1];
                            },
                            K_F5 => self.reload(),
                            K_F6 => self.save(),
                            K_HOME => self.offset = 0,
                            K_UP => {
                                let mut new_offset = 0;
                                for i in 2..self.offset {
                                    match self.string.as_bytes()[self.offset - i] {
                                        0 => break,
                                        10 => {
                                            new_offset = self.offset - i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                self.offset = new_offset;
                            }
                            K_LEFT => if self.offset > 0 {
                                self.offset -= 1;
                            },
                            K_RIGHT => if self.offset < self.string.len() {
                                self.offset += 1;
                            },
                            K_END => self.offset = self.string.len(),
                            K_DOWN => {
                                let mut new_offset = self.string.len();
                                for i in self.offset..self.string.len() {
                                    match self.string.as_bytes()[i] {
                                        0 => break,
                                        10 => {
                                            new_offset = i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                self.offset = new_offset;
                            }
                            _ => match key_event.character {
                                '\0' => (),
                                _ => {
                                    self.string = self.string[0 .. self.offset].to_string() +
                                                  &key_event.character.to_string() +
                                                  &self.string[self.offset .. self.string.len()];
                                    self.offset += 1;
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Some(arg) => Editor::new().main(&arg),
        None => Editor::new().main("none://"),
    }
}
<commit_msg>Started implementing Save window for editor as a freebie<commit_after>use redox::*;

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn reload(&mut self) {
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                let mut string = String::new();
                file.read_to_string(&mut string);
                self.string = string;
            }
            None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &Window) {
        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            None => {
                let mut save_window = {
                    const width: usize = 400;
                    const height: usize = 200;
                    Window::new((window.x() + (window.width()/2 - width/2) as isize),
                                (window.y() + (window.height()/2 - height/2) as isize),
                                width,
                                height,
                                "Save As").unwrap()
                };
                if let Some(event) = save_window.poll() {
                    //TODO: Create a Save/Cancel button for file saving
                    // and prompt the user for asking to save
                }
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                     &("Editor (".to_string() + url + ")")).unwrap();

        self.url = url.to_string();
        self.file = File::open(&self.url);

        self.reload();
        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            K_ESC => break,
                            K_BKSP => if self.offset > 0 {
                                self.string = self.string[0 .. self.offset - 1].to_string() +
                                              &self.string[self.offset .. self.string.len()];
                                self.offset -= 1;
                            },
                            K_DEL => if self.offset < self.string.len() {
                                self.string = self.string[0 .. self.offset].to_string() +
                                              &self.string[self.offset + 1 .. self.string.len() - 1];
                            },
                            K_F5 => self.reload(),
                            K_F6 => self.save(&window),
                            K_HOME => self.offset = 0,
                            K_UP => {
                                let mut new_offset = 0;
                                for i in 2..self.offset {
                                    match self.string.as_bytes()[self.offset - i] {
                                        0 => break,
                                        10 => {
                                            new_offset = self.offset - i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                self.offset = new_offset;
                            }
                            K_LEFT => if self.offset > 0 {
                                self.offset -= 1;
                            },
                            K_RIGHT => if self.offset < self.string.len() {
                                self.offset += 1;
                            },
                            K_END => self.offset = self.string.len(),
                            K_DOWN => {
                                let mut new_offset = self.string.len();
                                for i in self.offset..self.string.len() {
                                    match self.string.as_bytes()[i] {
                                        0 => break,
                                        10 => {
                                            new_offset = i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                self.offset = new_offset;
                            }
                            _ => match key_event.character {
                                '\0' => (),
                                _ => {
                                    self.string = self.string[0 .. self.offset].to_string() +
                                                  &key_event.character.to_string() +
                                                  &self.string[self.offset .. self.string.len()];
                                    self.offset += 1;
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Some(arg) => Editor::new().main(&arg),
        None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before>//! Types in this module are mostly internal and automatically generated. You
//! shouldn't need to interact with these types during normal usage, other than
//! the methods on [`Table`](trait.Table.html)
#[doc(hidden)]
pub mod filter;
#[doc(hidden)]
pub mod joins;

use backend::Backend;
use expression::{Expression, SelectableExpression, NonAggregate};
use query_builder::*;
#[doc(hidden)]
pub use self::joins::{InnerJoinSource, LeftOuterJoinSource};
use types::{FromSqlRow, HasSqlType};

pub use self::joins::JoinTo;

/// Trait indicating that a record can be queried from the database. This trait
/// can be derived automatically. See the [codegen
/// documentation](https://github.com/diesel-rs/diesel/tree/master/diesel_codegen#derivequeryable)
/// for more.
pub trait Queryable<ST, DB> where
    DB: Backend + HasSqlType<ST>,
{
    type Row: FromSqlRow<ST, DB>;

    fn build(row: Self::Row) -> Self;
}

#[doc(hidden)]
pub trait QuerySource {
    type FromClause;
    fn from_clause(&self) -> Self::FromClause;
}

/// A column on a database table. Types which implement this trait should have
/// been generated by the [`table!` macro](../macro.table!.html).
pub trait Column: Expression {
    type Table: Table;

    fn name() -> &'static str;
}

/// A SQL database table. Types which implement this trait should have been
/// generated by the [`table!` macro](../macro.table!.html).
pub trait Table: QuerySource + AsQuery + Sized {
    type PrimaryKey: Column<Table=Self> + Expression + NonAggregate;
    type AllColumns: SelectableExpression<Self> + NonAggregate;

    fn name() -> &'static str;
    fn primary_key(&self) -> Self::PrimaryKey;
    fn all_columns() -> Self::AllColumns;

    fn inner_join<T>(self, other: T) -> InnerJoinSource<Self, T> where
        T: Table,
        Self: JoinTo<T, joins::Inner>,
    {
        InnerJoinSource::new(self, other)
    }

    fn left_outer_join<T>(self, other: T) -> LeftOuterJoinSource<Self, T> where
        T: Table,
        Self: JoinTo<T, joins::LeftOuter>,
    {
        LeftOuterJoinSource::new(self, other)
    }
}
<commit_msg>Remove the `Column` constraint from `PrimaryKey`<commit_after>//! Types in this module are mostly internal and automatically generated. You
//! shouldn't need to interact with these types during normal usage, other than
//! the methods on [`Table`](trait.Table.html)
#[doc(hidden)]
pub mod filter;
#[doc(hidden)]
pub mod joins;

use backend::Backend;
use expression::{Expression, SelectableExpression, NonAggregate};
use query_builder::*;
#[doc(hidden)]
pub use self::joins::{InnerJoinSource, LeftOuterJoinSource};
use types::{FromSqlRow, HasSqlType};

pub use self::joins::JoinTo;

/// Trait indicating that a record can be queried from the database. This trait
/// can be derived automatically. See the [codegen
/// documentation](https://github.com/diesel-rs/diesel/tree/master/diesel_codegen#derivequeryable)
/// for more.
pub trait Queryable<ST, DB> where
    DB: Backend + HasSqlType<ST>,
{
    type Row: FromSqlRow<ST, DB>;

    fn build(row: Self::Row) -> Self;
}

#[doc(hidden)]
pub trait QuerySource {
    type FromClause;
    fn from_clause(&self) -> Self::FromClause;
}

/// A column on a database table. Types which implement this trait should have
/// been generated by the [`table!` macro](../macro.table!.html).
pub trait Column: Expression {
    type Table: Table;

    fn name() -> &'static str;
}

/// A SQL database table. Types which implement this trait should have been
/// generated by the [`table!` macro](../macro.table!.html).
pub trait Table: QuerySource + AsQuery + Sized {
    type PrimaryKey: SelectableExpression<Self> + NonAggregate;
    type AllColumns: SelectableExpression<Self> + NonAggregate;

    fn name() -> &'static str;
    fn primary_key(&self) -> Self::PrimaryKey;
    fn all_columns() -> Self::AllColumns;

    fn inner_join<T>(self, other: T) -> InnerJoinSource<Self, T> where
        T: Table,
        Self: JoinTo<T, joins::Inner>,
    {
        InnerJoinSource::new(self, other)
    }

    fn left_outer_join<T>(self, other: T) -> LeftOuterJoinSource<Self, T> where
        T: Table,
        Self: JoinTo<T, joins::LeftOuter>,
    {
        LeftOuterJoinSource::new(self, other)
    }
}
<|endoftext|>


<commit_before><commit_msg>String to tiploc is better expressed as FromStr, really.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #3053. Fixes #3053.<commit_after>// exec-env:RUST_POISON_ON_FREE=1

// Test that we root `x` even though it is found in immutable memory,
// because it is moved.

#[feature(managed_boxes)];

fn free<T>(x: @T) {}

struct Foo {
    f: @Bar
}

struct Bar {
    g: int
}

fn lend(x: @Foo) -> int {
    let y = &x.f.g;
    free(x); // specifically here, if x is not rooted, it will be freed
    *y
}

pub fn main() {
    assert_eq!(lend(@Foo {f: @Bar {g: 22}}), 22);
}
<|endoftext|>


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


<commit_before><commit_msg>docs(ClearTextPassword): fix a typo<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #63473 - adrian-budau:master, r=Centril<commit_after>// build-pass
// Regression test for #56870: Internal compiler error (traits & associated consts)

use std::fmt::Debug;

pub trait Foo<T> {
  const FOO: *const u8;
}

impl <T: Debug> Foo<T> for dyn Debug {
  const FOO: *const u8 = <T as Debug>::fmt as *const u8;
}

pub trait Bar {
  const BAR: *const u8;
}

pub trait Baz {
  type Data: Debug;
}

pub struct BarStruct<S: Baz>(S);

impl<S: Baz> Bar for BarStruct<S> {
  const BAR: *const u8 = <dyn Debug as Foo<<S as Baz>::Data>>::FOO;
}

struct AnotherStruct;
#[derive(Debug)]
struct SomeStruct;

impl Baz for AnotherStruct {
  type Data = SomeStruct;
}

fn main() {
  let _x = <BarStruct<AnotherStruct> as Bar>::BAR;
}
<|endoftext|>


<commit_before>// 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.

use build::{Location, ScopeAuxiliaryVec, ScopeId};
use rustc::hir;
use rustc::mir::repr::*;
use rustc::mir::transform::MirSource;
use rustc::ty::{self, TyCtxt};
use rustc_data_structures::fnv::FnvHashMap;
use rustc_data_structures::indexed_vec::{Idx};
use std::fmt::Display;
use std::fs;
use std::io::{self, Write};
use syntax::ast::NodeId;

const INDENT: &'static str = "    ";
/// Alignment for lining up comments following MIR statements
const ALIGN: usize = 40;

/// If the session is properly configured, dumps a human-readable
/// representation of the mir into:
///
/// ```text
/// rustc.node<node_id>.<pass_name>.<disambiguator>
/// ```
///
/// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
/// where `<filter>` takes the following forms:
///
/// - `all` -- dump MIR for all fns, all passes, all everything
/// - `substring1&substring2,...` -- `&`-separated list of substrings
///   that can appear in the pass-name or the `item_path_str` for the given
///   node-id. If any one of the substrings match, the data is dumped out.
pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          pass_name: &str,
                          disambiguator: &Display,
                          src: MirSource,
                          mir: &Mir<'tcx>,
                          auxiliary: Option<&ScopeAuxiliaryVec>) {
    let filters = match tcx.sess.opts.debugging_opts.dump_mir {
        None => return,
        Some(ref filters) => filters,
    };
    let node_id = src.item_id();
    let node_path = tcx.item_path_str(tcx.map.local_def_id(node_id));
    let is_matched =
        filters.split("&")
               .any(|filter| {
                   filter == "all" ||
                       pass_name.contains(filter) ||
                       node_path.contains(filter)
               });
    if !is_matched {
        return;
    }

    let promotion_id = match src {
        MirSource::Promoted(_, id) => format!("-{:?}", id),
        _ => String::new()
    };

    let file_name = format!("rustc.node{}{}.{}.{}.mir",
                            node_id, promotion_id, pass_name, disambiguator);
    let _ = fs::File::create(&file_name).and_then(|mut file| {
        try!(writeln!(file, "// MIR for `{}`", node_path));
        try!(writeln!(file, "// node_id = {}", node_id));
        try!(writeln!(file, "// pass_name = {}", pass_name));
        try!(writeln!(file, "// disambiguator = {}", disambiguator));
        try!(writeln!(file, ""));
        try!(write_mir_fn(tcx, src, mir, &mut file, auxiliary));
        Ok(())
    });
}

/// Write out a human-readable textual representation for the given MIR.
pub fn write_mir_pretty<'a, 'b, 'tcx, I>(tcx: TyCtxt<'b, 'tcx, 'tcx>,
                                         iter: I,
                                         w: &mut Write)
                                         -> io::Result<()>
    where I: Iterator<Item=(&'a NodeId, &'a Mir<'tcx>)>, 'tcx: 'a
{
    let mut first = true;
    for (&id, mir) in iter {
        if first {
            first = false;
        } else {
            // Put empty lines between all items
            writeln!(w, "")?;
        }

        let src = MirSource::from_node(tcx, id);
        write_mir_fn(tcx, src, mir, w, None)?;

        for (i, mir) in mir.promoted.iter_enumerated() {
            writeln!(w, "")?;
            write_mir_fn(tcx, MirSource::Promoted(id, i), mir, w, None)?;
        }
    }
    Ok(())
}

enum Annotation {
    EnterScope(ScopeId),
    ExitScope(ScopeId),
}

fn scope_entry_exit_annotations(auxiliary: Option<&ScopeAuxiliaryVec>)
                                -> FnvHashMap<Location, Vec<Annotation>>
{
    // compute scope/entry exit annotations
    let mut annotations = FnvHashMap();
    if let Some(auxiliary) = auxiliary {
        for (scope_id, auxiliary) in auxiliary.iter_enumerated() {
            annotations.entry(auxiliary.dom)
                       .or_insert(vec![])
                       .push(Annotation::EnterScope(scope_id));

            for &loc in &auxiliary.postdoms {
                annotations.entry(loc)
                           .or_insert(vec![])
                           .push(Annotation::ExitScope(scope_id));
            }
        }
    }
    return annotations;
}

pub fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              src: MirSource,
                              mir: &Mir<'tcx>,
                              w: &mut Write,
                              auxiliary: Option<&ScopeAuxiliaryVec>)
                              -> io::Result<()> {
    let annotations = scope_entry_exit_annotations(auxiliary);
    write_mir_intro(tcx, src, mir, w)?;
    for block in mir.basic_blocks().indices() {
        write_basic_block(tcx, block, mir, w, &annotations)?;
        if block.index() + 1 != mir.basic_blocks().len() {
            writeln!(w, "")?;
        }
    }

    writeln!(w, "}}")?;
    Ok(())
}

/// Write out a human-readable textual representation for the given basic block.
fn write_basic_block(tcx: TyCtxt,
                     block: BasicBlock,
                     mir: &Mir,
                     w: &mut Write,
                     annotations: &FnvHashMap<Location, Vec<Annotation>>)
                     -> io::Result<()> {
    let data = &mir[block];

    // Basic block label at the top.
    writeln!(w, "{}{:?}: {{", INDENT, block)?;

    // List of statements in the middle.
    let mut current_location = Location { block: block, statement_index: 0 };
    for statement in &data.statements {
        if let Some(ref annotations) = annotations.get(&current_location) {
            for annotation in annotations.iter() {
                match *annotation {
                    Annotation::EnterScope(id) =>
                        writeln!(w, "{0}{0}// Enter Scope({1})",
                                 INDENT, id.index())?,
                    Annotation::ExitScope(id) =>
                        writeln!(w, "{0}{0}// Exit Scope({1})",
                                 INDENT, id.index())?,
                }
            }
        }

        let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
        writeln!(w, "{0:1$} // {2}",
                 indented_mir,
                 ALIGN,
                 comment(tcx, statement.source_info))?;

        current_location.statement_index += 1;
    }

    // Terminator at the bottom.
    let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
    writeln!(w, "{0:1$} // {2}",
             indented_terminator,
             ALIGN,
             comment(tcx, data.terminator().source_info))?;

    writeln!(w, "{}}}\n", INDENT)
}

fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
    format!("scope {} at {}", scope.index(), tcx.sess.codemap().span_to_string(span))
}

fn write_scope_tree(tcx: TyCtxt,
                    mir: &Mir,
                    scope_tree: &FnvHashMap<VisibilityScope, Vec<VisibilityScope>>,
                    w: &mut Write,
                    parent: VisibilityScope,
                    depth: usize)
                    -> io::Result<()> {
    let indent = depth * INDENT.len();

    let children = match scope_tree.get(&parent) {
        Some(childs) => childs,
        None => return Ok(()),
    };

    for &child in children {
        let data = &mir.visibility_scopes[child];
        assert_eq!(data.parent_scope, Some(parent));
        writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;

        // User variable types (including the user's name in a comment).
        for (id, var) in mir.var_decls.iter_enumerated() {
            // Skip if not declared in this scope.
            if var.source_info.scope != child {
                continue;
            }

            let mut_str = if var.mutability == Mutability::Mut {
                "mut "
            } else {
                ""
            };

            let indent = indent + INDENT.len();
            let indented_var = format!("{0:1$}let {2}{3:?}: {4};",
                                       INDENT,
                                       indent,
                                       mut_str,
                                       id,
                                       var.ty);
            writeln!(w, "{0:1$} // \"{2}\" in {3}",
                     indented_var,
                     ALIGN,
                     var.name,
                     comment(tcx, var.source_info))?;
        }

        write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;

        writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
    }

    Ok(())
}

/// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
/// local variables (both user-defined bindings and compiler temporaries).
fn write_mir_intro<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                             src: MirSource,
                             mir: &Mir,
                             w: &mut Write)
                             -> io::Result<()> {
    write_mir_sig(tcx, src, mir, w)?;
    writeln!(w, " {{")?;

    // construct a scope tree and write it out
    let mut scope_tree: FnvHashMap<VisibilityScope, Vec<VisibilityScope>> = FnvHashMap();
    for (index, scope_data) in mir.visibility_scopes.iter().enumerate() {
        if let Some(parent) = scope_data.parent_scope {
            scope_tree.entry(parent)
                      .or_insert(vec![])
                      .push(VisibilityScope::new(index));
        } else {
            // Only the argument scope has no parent, because it's the root.
            assert_eq!(index, ARGUMENT_VISIBILITY_SCOPE.index());
        }
    }

    write_scope_tree(tcx, mir, &scope_tree, w, ARGUMENT_VISIBILITY_SCOPE, 1)?;

    write_mir_decls(mir, w)
}

fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut Write)
                 -> io::Result<()>
{
    match src {
        MirSource::Fn(_) => write!(w, "fn")?,
        MirSource::Const(_) => write!(w, "const")?,
        MirSource::Static(_, hir::MutImmutable) => write!(w, "static")?,
        MirSource::Static(_, hir::MutMutable) => write!(w, "static mut")?,
        MirSource::Promoted(_, i) => write!(w, "{:?} in", i)?
    }

    write!(w, " {}", tcx.node_path_str(src.item_id()))?;

    if let MirSource::Fn(_) = src {
        write!(w, "(")?;

        // fn argument types.
        for (i, arg) in mir.arg_decls.iter_enumerated() {
            if i.index() != 0 {
                write!(w, ", ")?;
            }
            write!(w, "{:?}: {}", Lvalue::Arg(i), arg.ty)?;
        }

        write!(w, ") -> ")?;

        // fn return type.
        match mir.return_ty {
            ty::FnOutput::FnConverging(ty) => write!(w, "{}", ty),
            ty::FnOutput::FnDiverging => write!(w, "!"),
        }
    } else {
        assert!(mir.arg_decls.is_empty());
        write!(w, ": {} =", mir.return_ty.unwrap())
    }
}

fn write_mir_decls(mir: &Mir, w: &mut Write) -> io::Result<()> {
    // Compiler-introduced temporary types.
    for (id, temp) in mir.temp_decls.iter_enumerated() {
        writeln!(w, "{}let mut {:?}: {};", INDENT, id, temp.ty)?;
    }

    // Wrote any declaration? Add an empty line before the first block is printed.
    if !mir.var_decls.is_empty() || !mir.temp_decls.is_empty() {
        writeln!(w, "")?;
    }

    Ok(())
}
<commit_msg>Remove extra newlines in MIR dump<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.

use build::{Location, ScopeAuxiliaryVec, ScopeId};
use rustc::hir;
use rustc::mir::repr::*;
use rustc::mir::transform::MirSource;
use rustc::ty::{self, TyCtxt};
use rustc_data_structures::fnv::FnvHashMap;
use rustc_data_structures::indexed_vec::{Idx};
use std::fmt::Display;
use std::fs;
use std::io::{self, Write};
use syntax::ast::NodeId;

const INDENT: &'static str = "    ";
/// Alignment for lining up comments following MIR statements
const ALIGN: usize = 40;

/// If the session is properly configured, dumps a human-readable
/// representation of the mir into:
///
/// ```text
/// rustc.node<node_id>.<pass_name>.<disambiguator>
/// ```
///
/// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
/// where `<filter>` takes the following forms:
///
/// - `all` -- dump MIR for all fns, all passes, all everything
/// - `substring1&substring2,...` -- `&`-separated list of substrings
///   that can appear in the pass-name or the `item_path_str` for the given
///   node-id. If any one of the substrings match, the data is dumped out.
pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          pass_name: &str,
                          disambiguator: &Display,
                          src: MirSource,
                          mir: &Mir<'tcx>,
                          auxiliary: Option<&ScopeAuxiliaryVec>) {
    let filters = match tcx.sess.opts.debugging_opts.dump_mir {
        None => return,
        Some(ref filters) => filters,
    };
    let node_id = src.item_id();
    let node_path = tcx.item_path_str(tcx.map.local_def_id(node_id));
    let is_matched =
        filters.split("&")
               .any(|filter| {
                   filter == "all" ||
                       pass_name.contains(filter) ||
                       node_path.contains(filter)
               });
    if !is_matched {
        return;
    }

    let promotion_id = match src {
        MirSource::Promoted(_, id) => format!("-{:?}", id),
        _ => String::new()
    };

    let file_name = format!("rustc.node{}{}.{}.{}.mir",
                            node_id, promotion_id, pass_name, disambiguator);
    let _ = fs::File::create(&file_name).and_then(|mut file| {
        try!(writeln!(file, "// MIR for `{}`", node_path));
        try!(writeln!(file, "// node_id = {}", node_id));
        try!(writeln!(file, "// pass_name = {}", pass_name));
        try!(writeln!(file, "// disambiguator = {}", disambiguator));
        try!(writeln!(file, ""));
        try!(write_mir_fn(tcx, src, mir, &mut file, auxiliary));
        Ok(())
    });
}

/// Write out a human-readable textual representation for the given MIR.
pub fn write_mir_pretty<'a, 'b, 'tcx, I>(tcx: TyCtxt<'b, 'tcx, 'tcx>,
                                         iter: I,
                                         w: &mut Write)
                                         -> io::Result<()>
    where I: Iterator<Item=(&'a NodeId, &'a Mir<'tcx>)>, 'tcx: 'a
{
    let mut first = true;
    for (&id, mir) in iter {
        if first {
            first = false;
        } else {
            // Put empty lines between all items
            writeln!(w, "")?;
        }

        let src = MirSource::from_node(tcx, id);
        write_mir_fn(tcx, src, mir, w, None)?;

        for (i, mir) in mir.promoted.iter_enumerated() {
            writeln!(w, "")?;
            write_mir_fn(tcx, MirSource::Promoted(id, i), mir, w, None)?;
        }
    }
    Ok(())
}

enum Annotation {
    EnterScope(ScopeId),
    ExitScope(ScopeId),
}

fn scope_entry_exit_annotations(auxiliary: Option<&ScopeAuxiliaryVec>)
                                -> FnvHashMap<Location, Vec<Annotation>>
{
    // compute scope/entry exit annotations
    let mut annotations = FnvHashMap();
    if let Some(auxiliary) = auxiliary {
        for (scope_id, auxiliary) in auxiliary.iter_enumerated() {
            annotations.entry(auxiliary.dom)
                       .or_insert(vec![])
                       .push(Annotation::EnterScope(scope_id));

            for &loc in &auxiliary.postdoms {
                annotations.entry(loc)
                           .or_insert(vec![])
                           .push(Annotation::ExitScope(scope_id));
            }
        }
    }
    return annotations;
}

pub fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              src: MirSource,
                              mir: &Mir<'tcx>,
                              w: &mut Write,
                              auxiliary: Option<&ScopeAuxiliaryVec>)
                              -> io::Result<()> {
    let annotations = scope_entry_exit_annotations(auxiliary);
    write_mir_intro(tcx, src, mir, w)?;
    for block in mir.basic_blocks().indices() {
        write_basic_block(tcx, block, mir, w, &annotations)?;
        if block.index() + 1 != mir.basic_blocks().len() {
            writeln!(w, "")?;
        }
    }

    writeln!(w, "}}")?;
    Ok(())
}

/// Write out a human-readable textual representation for the given basic block.
fn write_basic_block(tcx: TyCtxt,
                     block: BasicBlock,
                     mir: &Mir,
                     w: &mut Write,
                     annotations: &FnvHashMap<Location, Vec<Annotation>>)
                     -> io::Result<()> {
    let data = &mir[block];

    // Basic block label at the top.
    writeln!(w, "{}{:?}: {{", INDENT, block)?;

    // List of statements in the middle.
    let mut current_location = Location { block: block, statement_index: 0 };
    for statement in &data.statements {
        if let Some(ref annotations) = annotations.get(&current_location) {
            for annotation in annotations.iter() {
                match *annotation {
                    Annotation::EnterScope(id) =>
                        writeln!(w, "{0}{0}// Enter Scope({1})",
                                 INDENT, id.index())?,
                    Annotation::ExitScope(id) =>
                        writeln!(w, "{0}{0}// Exit Scope({1})",
                                 INDENT, id.index())?,
                }
            }
        }

        let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
        writeln!(w, "{0:1$} // {2}",
                 indented_mir,
                 ALIGN,
                 comment(tcx, statement.source_info))?;

        current_location.statement_index += 1;
    }

    // Terminator at the bottom.
    let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
    writeln!(w, "{0:1$} // {2}",
             indented_terminator,
             ALIGN,
             comment(tcx, data.terminator().source_info))?;

    writeln!(w, "{}}}", INDENT)
}

fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
    format!("scope {} at {}", scope.index(), tcx.sess.codemap().span_to_string(span))
}

fn write_scope_tree(tcx: TyCtxt,
                    mir: &Mir,
                    scope_tree: &FnvHashMap<VisibilityScope, Vec<VisibilityScope>>,
                    w: &mut Write,
                    parent: VisibilityScope,
                    depth: usize)
                    -> io::Result<()> {
    let indent = depth * INDENT.len();

    let children = match scope_tree.get(&parent) {
        Some(childs) => childs,
        None => return Ok(()),
    };

    for &child in children {
        let data = &mir.visibility_scopes[child];
        assert_eq!(data.parent_scope, Some(parent));
        writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;

        // User variable types (including the user's name in a comment).
        for (id, var) in mir.var_decls.iter_enumerated() {
            // Skip if not declared in this scope.
            if var.source_info.scope != child {
                continue;
            }

            let mut_str = if var.mutability == Mutability::Mut {
                "mut "
            } else {
                ""
            };

            let indent = indent + INDENT.len();
            let indented_var = format!("{0:1$}let {2}{3:?}: {4};",
                                       INDENT,
                                       indent,
                                       mut_str,
                                       id,
                                       var.ty);
            writeln!(w, "{0:1$} // \"{2}\" in {3}",
                     indented_var,
                     ALIGN,
                     var.name,
                     comment(tcx, var.source_info))?;
        }

        write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;

        writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
    }

    Ok(())
}

/// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
/// local variables (both user-defined bindings and compiler temporaries).
fn write_mir_intro<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                             src: MirSource,
                             mir: &Mir,
                             w: &mut Write)
                             -> io::Result<()> {
    write_mir_sig(tcx, src, mir, w)?;
    writeln!(w, " {{")?;

    // construct a scope tree and write it out
    let mut scope_tree: FnvHashMap<VisibilityScope, Vec<VisibilityScope>> = FnvHashMap();
    for (index, scope_data) in mir.visibility_scopes.iter().enumerate() {
        if let Some(parent) = scope_data.parent_scope {
            scope_tree.entry(parent)
                      .or_insert(vec![])
                      .push(VisibilityScope::new(index));
        } else {
            // Only the argument scope has no parent, because it's the root.
            assert_eq!(index, ARGUMENT_VISIBILITY_SCOPE.index());
        }
    }

    write_scope_tree(tcx, mir, &scope_tree, w, ARGUMENT_VISIBILITY_SCOPE, 1)?;

    write_mir_decls(mir, w)
}

fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut Write)
                 -> io::Result<()>
{
    match src {
        MirSource::Fn(_) => write!(w, "fn")?,
        MirSource::Const(_) => write!(w, "const")?,
        MirSource::Static(_, hir::MutImmutable) => write!(w, "static")?,
        MirSource::Static(_, hir::MutMutable) => write!(w, "static mut")?,
        MirSource::Promoted(_, i) => write!(w, "{:?} in", i)?
    }

    write!(w, " {}", tcx.node_path_str(src.item_id()))?;

    if let MirSource::Fn(_) = src {
        write!(w, "(")?;

        // fn argument types.
        for (i, arg) in mir.arg_decls.iter_enumerated() {
            if i.index() != 0 {
                write!(w, ", ")?;
            }
            write!(w, "{:?}: {}", Lvalue::Arg(i), arg.ty)?;
        }

        write!(w, ") -> ")?;

        // fn return type.
        match mir.return_ty {
            ty::FnOutput::FnConverging(ty) => write!(w, "{}", ty),
            ty::FnOutput::FnDiverging => write!(w, "!"),
        }
    } else {
        assert!(mir.arg_decls.is_empty());
        write!(w, ": {} =", mir.return_ty.unwrap())
    }
}

fn write_mir_decls(mir: &Mir, w: &mut Write) -> io::Result<()> {
    // Compiler-introduced temporary types.
    for (id, temp) in mir.temp_decls.iter_enumerated() {
        writeln!(w, "{}let mut {:?}: {};", INDENT, id, temp.ty)?;
    }

    // Wrote any declaration? Add an empty line before the first block is printed.
    if !mir.var_decls.is_empty() || !mir.temp_decls.is_empty() {
        writeln!(w, "")?;
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1513<commit_after>// https://leetcode.com/problems/number-of-substrings-with-only-1s/
pub fn num_sub(s: String) -> i32 {
    todo!()
}

fn main() {
    println!("{}", num_sub(String::from("0110111"))); // 9
    println!("{}", num_sub(String::from("101"))); // 2
    println!("{}", num_sub(String::from("111111"))); // 21
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2373<commit_after>// https://leetcode.com/problems/largest-local-values-in-a-matrix/
pub fn largest_local(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    todo!()
}

fn main() {
    println!(
        "{:?}",
        largest_local(vec![
            vec![9, 9, 8, 1],
            vec![5, 6, 2, 6],
            vec![8, 2, 6, 4],
            vec![6, 2, 2, 2]
        ])
    ); // [[9,9],[8,6]]
    println!(
        "{:?}",
        largest_local(vec![
            vec![1, 1, 1, 1, 1],
            vec![1, 1, 1, 1, 1],
            vec![1, 1, 2, 1, 1],
            vec![1, 1, 1, 1, 1],
            vec![1, 1, 1, 1, 1]
        ])
    ); // [[2,2,2],[2,2,2],[2,2,2]]
}
<|endoftext|>


<commit_before><commit_msg>added pages for api specs<commit_after><|endoftext|>


<commit_before><commit_msg>Adds shell.rs and UnixShell trait<commit_after>//! Paths and Unix shells
//!
//! MacOS, Linux, FreeBSD, and many other OS model their design on Unix,
//! so handling them is relatively consistent. But only relatively.
//! POSIX postdates Unix by 20 years, and each "Unix-like" shell develops
//! unique quirks over time.

// TODO: Nushell, PowerShell
// Cross-platform non-POSIX shells were not assessed for integration yet.

use super::*;
use std::env;
use std::path::PathBuf;

pub type Shell = Box<dyn UnixShell>;

macro_rules! support_shells {
    ( $($shell:ident,)* ) => {
        fn enumerate_shells() -> Vec<Shell> {
            vec![$( Box::new($shell), )*]
        }
    }
}

support_shells! {
    Posix,
    Bash,
    Zsh,
}

pub fn get_available_shells() -> impl Iterator<Item = Shell> {
    enumerate_shells().into_iter().filter(|sh| sh.does_exist())
}

pub trait UnixShell {
    fn does_exist(&self) -> bool;

    fn rcfile(&self) -> Option<PathBuf>;

    fn export_string(&self) -> Result<String> {
        // The path is *prepended* in case there are system-installed
        // rustc's that need to be overridden.
        Ok(format!(
            r#"export PATH="{}/bin:$PATH""#,
            canonical_cargo_home()?
        ))
    }
}

struct Posix;
impl UnixShell for Posix {
    fn does_exist(&self) -> bool {
        true
    }

    fn rcfile(&self) -> Option<PathBuf> {
        utils::home_dir().map(|dir| dir.join(".profile"))
    }
}

struct Bash;
impl UnixShell for Bash {
    fn does_exist(&self) -> bool {
        self.rcfile().map_or(false, |rc| rc.is_file()) || matches!(utils::find_cmd(&["bash"]), Some(_))
    }

    fn rcfile(&self) -> Option<PathBuf> {
        // .bashrc is normative, in spite of a few weird Mac versions.
        utils::home_dir().map(|dir| dir.join(".bashrc"))
    }
}

struct Zsh;
impl UnixShell for Zsh {
    fn does_exist(&self) -> bool {
        self.rcfile().map_or(false, |rc| rc.is_file()) || matches!(utils::find_cmd(&["zsh"]), Some(_))
    }

    fn rcfile(&self) -> Option<PathBuf> {
        let zdotdir = match env::var("ZDOTDIR") {
            Ok(dir) => Some(PathBuf::from(dir)),
            _ => utils::home_dir(),
        };

        // .zshenv is preferred for path mods but not all zshers use it,
        // zsh always loads .zshrc on interactive, unlike bash's weirdness.
        zdotdir.map(|dir| match dir.join(".zshenv") {
            rc if rc.is_file() => rc,
            _ => dir.join(".zshrc"),
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Don't attempt to wait for session ending when it has already ended<commit_after><|endoftext|>


<commit_before><commit_msg>ADD: DIY hints content and hints promot behavior<commit_after>use std::collections::HashSet;

use rustyline::Editor;
use rustyline::{hint::Hinter, Context};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};

#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
    // It's simple example of rustyline, for more effecient, please use ** radix trie ** (thanks @gwenn's idea)
    hints: HashSet<String>,
}

impl Hinter for DIYHinter {
    fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<String> {
        if pos < line.len() {
            return None;
        }

        self.hints
            .iter()
            .filter_map(|hint| {
                // expect hint after word complete, like redis cli, add condition: line.ends_with(" ")
                if pos > 0 && hint.starts_with(&line[..pos]) {
                    Some(hint[pos..].to_owned())
                } else {
                    None
                }
            })
            .nth(0)
    }
}

fn diy_hints() -> HashSet<String> {
    let mut set = HashSet::new();
    set.insert(String::from("help"));
    set.insert(String::from("get key"));
    set.insert(String::from("set key value"));
    set.insert(String::from("hget key field"));
    set.insert(String::from("hset key field value"));
    set
}

fn main() -> rustyline::Result<()> {
    println!("This is a DIY hint hack of rustyline");
    let h = DIYHinter { hints: diy_hints() };

    let mut rl: Editor<DIYHinter> = Editor::new();
    rl.set_helper(Some(h));

    loop {
        let input = rl.readline("> ")?;
        println!("input: {}", input);
    }
}
<|endoftext|>


<commit_before>// 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.

use std::io::{TempDir, Command, fs};
use std::os;

fn main() {
    // If we're the child, make sure we were invoked correctly
    let args = os::args();
    if args.len() > 1 && args[1].as_slice() == "child" {
        return assert_eq!(args[0].as_slice(), "mytest");
    }

    test();
}

fn test() {
    // If we're the parent, copy our own binary to a tempr directory, and then
    // make it executable.
    let dir = TempDir::new("mytest").unwrap();
    let me = os::self_exe_name().unwrap();
    let dest = dir.path().join(format!("mytest{}", os::consts::EXE_SUFFIX));
    fs::copy(&me, &dest).unwrap();

    // Append the temp directory to our own PATH.
    let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new()));
    path.push(dir.path().clone());
    let path = os::join_paths(path.as_slice()).unwrap();

    Command::new("mytest").env("PATH", path.as_slice())
                          .arg("child")
                          .spawn().unwrap();
}
<commit_msg>Rollup merge of #21498 - quantheory:master, r=alexcrichton<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.

use std::io::{Command, fs, USER_RWX};
use std::os;
use std::path::BytesContainer;
use std::rand::random;

fn main() {
    // If we're the child, make sure we were invoked correctly
    let args = os::args();
    if args.len() > 1 && args[1].as_slice() == "child" {
        return assert_eq!(args[0],
                          format!("mytest{}", os::consts::EXE_SUFFIX));
    }

    test();
}

fn test() {
    // If we're the parent, copy our own binary to a new directory.
    let my_path = os::self_exe_name().unwrap();
    let my_dir  = my_path.dir_path();

    let random_u32: u32 = random();
    let child_dir = Path::new(my_dir.join(format!("issue-15149-child-{}",
                                                  random_u32)));
    fs::mkdir(&child_dir, USER_RWX).unwrap();

    let child_path = child_dir.join(format!("mytest{}",
                                            os::consts::EXE_SUFFIX));
    fs::copy(&my_path, &child_path).unwrap();

    // Append the new directory to our own PATH.
    let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new()));
    path.push(child_dir.clone());
    let path = os::join_paths(path.as_slice()).unwrap();

    let child_output = Command::new("mytest").env("PATH", path.as_slice())
                                             .arg("child")
                                             .output().unwrap();

    assert!(child_output.status.success(),
            format!("child assertion failed\n child stdout:\n {}\n child stderr:\n {}",
                    child_output.output.container_as_str().unwrap(),
                    child_output.error.container_as_str().unwrap()));

    fs::rmdir_recursive(&child_dir).unwrap();

}
<|endoftext|>


<commit_before><commit_msg>Add run-pass test for issue 33498<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.

pub fn main() {
    let x = (0, 2);

    match x {
        (0, ref y) => {}
        (y, 0) => {}
        _ => (),
    }
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #22258<commit_after>// Copyright 2015 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.

use std::ops::Add;

fn f<T: Add>(a: T, b: T) -> <T as Add>::Output {
    a + b
}

fn main() {
    println!("a + b is {}", f::<f32>(100f32, 200f32));
}
<|endoftext|>