<commit_before>// xfail-stage0
// xfail-stage1
// xfail-stage2
// -*- rust -*-

// error-pattern:predicate check

fn f(int a, int b) : lt(a,b) {
}

fn lt(int a, int b) -> bool {
  ret a < b;
}

fn main() {
  let int a = 10;
  let int b = 23;
  check lt(b,a);
  f(b,a);
}
<commit_msg>Un-xfail test/run-fail/pred.rs<commit_after>// -*- rust -*-
// xfail-stage0
// error-pattern:Predicate lt(b, a) failed

fn f(int a, int b) : lt(a,b) {
}

pred lt(int a, int b) -> bool {
  ret a < b;
}

fn main() {
  let int a = 10;
  let int b = 23;
  check lt(b,a);
  f(b,a);
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue #10766<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.

// This test verifies that casting from the same lifetime on a value
// to the same lifetime on a trait succeeds. See issue #10766.

#![allow(dead_code)]
fn main() {
    trait T {}

    fn f<'a, V: T>(v: &'a V) -> &'a T {
        v as &'a T
    }
}
<|endoftext|>


<commit_before><commit_msg>modified get_notifications to allow both oauth and username/password auth<commit_after><|endoftext|>


<commit_before><commit_msg>improve the example<commit_after><|endoftext|>


<commit_before><commit_msg>First version for allocator behind mutex.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove got_symlink_permission, we already have one of those.<commit_after><|endoftext|>


<commit_before>// Copyright 2015 The Gfx-rs Developers.
//
// 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.

#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate gfx_device_gl;
extern crate glutin;

use gfx::traits::FactoryExt;
use gfx::Device;

pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;

gfx_vertex_struct!(Vertex {
    pos: [f32; 2] = "a_Pos",
    color: [f32; 3] = "a_Color",
});

gfx_pipeline!(pipe {
    vbuf: gfx::VertexBuffer<Vertex> = (),
    out: gfx::RenderTarget<ColorFormat> = "Target0",
});

const TRIANGLE: [Vertex; 3] = [
    Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] },
    Vertex { pos: [  0.5, -0.5 ], color: [0.0, 1.0, 0.0] },
    Vertex { pos: [  0.0,  0.5 ], color: [0.0, 0.0, 1.0] }
];

const CLEAR_COLOR: [f32; 4] = [0.1, 0.2, 0.3, 1.0];

pub fn main() {
    let builder = glutin::WindowBuilder::new()
        .with_title("Triangle example".to_string())
        .with_dimensions(1024, 768)
        .with_vsync();
    let (window, mut device, mut factory, main_color, _main_depth) =
        gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
    let command_buffer = factory.create_command_buffer();
    let mut encoder: gfx::Encoder<_, _> = command_buffer.into();
    let pso = factory.create_pipeline_simple(
        include_bytes!("shader/triangle_150.glslv"),
        include_bytes!("shader/triangle_150.glslf"),
        gfx::state::CullFace::Nothing,
        pipe::new()
    ).unwrap();
    let (vertex_buffer, slice) = factory.create_vertex_buffer(&TRIANGLE);
    let data = pipe::Data {
        vbuf: vertex_buffer,
        out: main_color
    };

    'main: loop {
        // loop over events
        for event in window.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                glutin::Event::Closed => break 'main,
                _ => {},
            }
        }
        // draw a frame
        encoder.clear(&data.out, CLEAR_COLOR);
        encoder.draw(&slice, &pso, &data);
        window.swap_buffers().unwrap();
        device.cleanup();
        encoder.flush(&mut device);
    }
}
<commit_msg>Inline command buffer in triangle example<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// 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.

#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate gfx_device_gl;
extern crate glutin;

use gfx::traits::FactoryExt;
use gfx::Device;

pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;

gfx_vertex_struct!(Vertex {
    pos: [f32; 2] = "a_Pos",
    color: [f32; 3] = "a_Color",
});

gfx_pipeline!(pipe {
    vbuf: gfx::VertexBuffer<Vertex> = (),
    out: gfx::RenderTarget<ColorFormat> = "Target0",
});

const TRIANGLE: [Vertex; 3] = [
    Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] },
    Vertex { pos: [  0.5, -0.5 ], color: [0.0, 1.0, 0.0] },
    Vertex { pos: [  0.0,  0.5 ], color: [0.0, 0.0, 1.0] }
];

const CLEAR_COLOR: [f32; 4] = [0.1, 0.2, 0.3, 1.0];

pub fn main() {
    let builder = glutin::WindowBuilder::new()
        .with_title("Triangle example".to_string())
        .with_dimensions(1024, 768)
        .with_vsync();
    let (window, mut device, mut factory, main_color, _main_depth) =
        gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
    let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into();
    let pso = factory.create_pipeline_simple(
        include_bytes!("shader/triangle_150.glslv"),
        include_bytes!("shader/triangle_150.glslf"),
        gfx::state::CullFace::Nothing,
        pipe::new()
    ).unwrap();
    let (vertex_buffer, slice) = factory.create_vertex_buffer(&TRIANGLE);
    let data = pipe::Data {
        vbuf: vertex_buffer,
        out: main_color
    };

    'main: loop {
        // loop over events
        for event in window.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                glutin::Event::Closed => break 'main,
                _ => {},
            }
        }
        // draw a frame
        encoder.clear(&data.out, CLEAR_COLOR);
        encoder.draw(&slice, &pso, &data);
        window.swap_buffers().unwrap();
        device.cleanup();
        encoder.flush(&mut device);
    }
}
<|endoftext|>


<commit_before>use syscall::common::*;

#[path="../../kernel/syscall/common.rs"]
pub mod common;

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={eax}"(a)
        : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86_64")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={rax}"(a)
        : "{rax}"(a), "{rbx}"(b), "{rcx}"(c), "{rdx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

pub unsafe fn sys_debug(byte: u8) {
    syscall(SYS_DEBUG, byte as usize, 0, 0);
}

pub unsafe fn sys_brk(addr: usize) -> usize {
    syscall(SYS_BRK, addr, 0, 0)
}

pub unsafe fn sys_chdir(path: *const u8) -> usize {
    syscall(SYS_CHDIR, path as usize, 0, 0)
}

pub unsafe fn sys_clone(flags: usize) -> usize {
    syscall(SYS_CLONE, flags, 0, 0)
}

pub unsafe fn sys_close(fd: usize) -> usize {
    syscall(SYS_CLOSE, fd, 0, 0)
}

pub unsafe fn sys_clock_gettime(clock: usize, tp: *mut TimeSpec) -> usize{
    syscall(SYS_CLOCK_GETTIME, clock, tp as usize, 0)
}

pub unsafe fn sys_dup(fd: usize) -> usize {
    syscall(SYS_DUP, fd, 0, 0)
}

pub unsafe fn sys_execve(path: *const u8, args: *const *const u8) -> usize {
    syscall(SYS_EXECVE, path as usize, args as usize, 0)
}

pub unsafe fn sys_exit(status: isize) {
    syscall(SYS_EXIT, status as usize, 0, 0);
}

pub unsafe fn sys_fpath(fd: usize, buf: *mut u8, len: usize) -> usize {
    syscall(SYS_FPATH, fd, buf as usize, len)
}

//TODO: FSTAT

pub unsafe fn sys_fsync(fd: usize) -> usize {
    syscall(SYS_FSYNC, fd, 0, 0)
}

pub unsafe fn sys_ftruncate(fd: usize, len: usize) -> usize {
    syscall(SYS_FTRUNCATE, fd, len, 0)
}

pub unsafe fn sys_link(old: *const u8, new: *const u8) -> usize {
    syscall(SYS_LINK, old as usize, new as usize, 0)
}

pub unsafe fn sys_lseek(fd: usize, offset: isize, whence: usize) -> usize {
    syscall(SYS_LSEEK, fd, offset as usize, whence)
}

pub unsafe fn sys_mkdir(path: *const u8, mode: usize) -> usize{
    syscall(SYS_MKDIR, path, mode)
}

pub unsafe fn sys_nanosleep(req: *const TimeSpec, rem: *mut TimeSpec) -> usize{
    syscall(SYS_NANOSLEEP, req as usize, rem as usize, 0)
}

pub unsafe fn sys_open(path: *const u8, flags: usize, mode: usize) -> usize {
    syscall(SYS_OPEN, path as usize, flags, mode)
}

pub unsafe fn sys_read(fd: usize, buf: *mut u8, count: usize) -> usize {
    syscall(SYS_READ, fd, buf as usize, count)
}

pub unsafe fn sys_unlink(path: *const u8) -> usize {
    syscall(SYS_UNLINK, path as usize, 0, 0)
}

pub unsafe fn sys_write(fd: usize, buf: *const u8, count: usize) -> usize {
    syscall(SYS_WRITE, fd, buf as usize, count)
}

pub unsafe fn sys_yield() {
    syscall(SYS_YIELD, 0, 0, 0);
}

pub unsafe fn sys_alloc(size: usize) -> usize {
    syscall(SYS_ALLOC, size, 0, 0)
}

pub unsafe fn sys_realloc(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC, ptr, size, 0)
}

pub unsafe fn sys_realloc_inplace(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC_INPLACE, ptr, size, 0)
}

pub unsafe fn sys_unalloc(ptr: usize) {
    syscall(SYS_UNALLOC, ptr, 0, 0);
}
<commit_msg>Debugging<commit_after>use syscall::common::*;

#[path="../../kernel/syscall/common.rs"]
pub mod common;

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={eax}"(a)
        : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86_64")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={rax}"(a)
        : "{rax}"(a), "{rbx}"(b), "{rcx}"(c), "{rdx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

pub unsafe fn sys_debug(byte: u8) {
    syscall(SYS_DEBUG, byte as usize, 0, 0);
}

pub unsafe fn sys_brk(addr: usize) -> usize {
    syscall(SYS_BRK, addr, 0, 0)
}

pub unsafe fn sys_chdir(path: *const u8) -> usize {
    syscall(SYS_CHDIR, path as usize, 0, 0)
}

pub unsafe fn sys_clone(flags: usize) -> usize {
    syscall(SYS_CLONE, flags, 0, 0)
}

pub unsafe fn sys_close(fd: usize) -> usize {
    syscall(SYS_CLOSE, fd, 0, 0)
}

pub unsafe fn sys_clock_gettime(clock: usize, tp: *mut TimeSpec) -> usize{
    syscall(SYS_CLOCK_GETTIME, clock, tp as usize, 0)
}

pub unsafe fn sys_dup(fd: usize) -> usize {
    syscall(SYS_DUP, fd, 0, 0)
}

pub unsafe fn sys_execve(path: *const u8, args: *const *const u8) -> usize {
    syscall(SYS_EXECVE, path as usize, args as usize, 0)
}

pub unsafe fn sys_exit(status: isize) {
    syscall(SYS_EXIT, status as usize, 0, 0);
}

pub unsafe fn sys_fpath(fd: usize, buf: *mut u8, len: usize) -> usize {
    syscall(SYS_FPATH, fd, buf as usize, len)
}

//TODO: FSTAT

pub unsafe fn sys_fsync(fd: usize) -> usize {
    syscall(SYS_FSYNC, fd, 0, 0)
}

pub unsafe fn sys_ftruncate(fd: usize, len: usize) -> usize {
    syscall(SYS_FTRUNCATE, fd, len, 0)
}

pub unsafe fn sys_link(old: *const u8, new: *const u8) -> usize {
    syscall(SYS_LINK, old as usize, new as usize, 0)
}

pub unsafe fn sys_lseek(fd: usize, offset: isize, whence: usize) -> usize {
    syscall(SYS_LSEEK, fd, offset as usize, whence)
}

pub unsafe fn sys_mkdir(path: *const u8, mode: usize) -> usize{
    syscall(SYS_MKDIR, path as usize, 0, mode)
}

pub unsafe fn sys_nanosleep(req: *const TimeSpec, rem: *mut TimeSpec) -> usize{
    syscall(SYS_NANOSLEEP, req as usize, rem as usize, 0)
}

pub unsafe fn sys_open(path: *const u8, flags: usize, mode: usize) -> usize {
    syscall(SYS_OPEN, path as usize, flags, mode)
}

pub unsafe fn sys_read(fd: usize, buf: *mut u8, count: usize) -> usize {
    syscall(SYS_READ, fd, buf as usize, count)
}

pub unsafe fn sys_unlink(path: *const u8) -> usize {
    syscall(SYS_UNLINK, path as usize, 0, 0)
}

pub unsafe fn sys_write(fd: usize, buf: *const u8, count: usize) -> usize {
    syscall(SYS_WRITE, fd, buf as usize, count)
}

pub unsafe fn sys_yield() {
    syscall(SYS_YIELD, 0, 0, 0);
}

pub unsafe fn sys_alloc(size: usize) -> usize {
    syscall(SYS_ALLOC, size, 0, 0)
}

pub unsafe fn sys_realloc(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC, ptr, size, 0)
}

pub unsafe fn sys_realloc_inplace(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC_INPLACE, ptr, size, 0)
}

pub unsafe fn sys_unalloc(ptr: usize) {
    syscall(SYS_UNALLOC, ptr, 0, 0);
}
<|endoftext|>


<commit_before><commit_msg>list7<commit_after>use lists::{contains, new_list};

mod lists {
  use std::fmt;
  use lists::List::{Cons, Nil};
  use std::sync::Arc;

  #[derive(PartialEq, Clone)]
  pub enum List<T> {
    Cons(T, Arc<List<T>>),
    Nil
  }

  impl<T> fmt::Display for List<T> where T : fmt::Display {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
      match *self {
        Cons(ref head, ref tail) =>
          {
            write!(f, "{head} :: ", head = head);
             write!(f, "{tail} ", tail = tail)
          }
        Nil => write!(f, "Nil")
      }
    }
  }

  #[allow(dead_code)]
  pub fn contains<T>(list: &List<T>, e: T) -> bool where T: PartialEq {
    match *list {
      Cons(ref head, ref tail) => if *head == e { true } else { contains(tail, e) },
      Nil => false
    }
  }

  #[allow(dead_code)]
  pub fn flat_map<T, U>(list: &List<T>, f: &Fn(T) -> List<U>) -> List<U> where T: Copy, T: Sized, T: Copy, T: PartialEq, U: Copy, U: Sized, U: PartialEq {
    match *list {
      Cons(ref head, ref tail) => concat(&f(*head), flat_map(tail, f)),
      Nil => Nil
    }
  }

  #[allow(dead_code)]
  pub fn filter<T>(list: &List<T>, f: &Fn(T) -> bool) -> List<T> where T : Copy {
    fold_right(list, Nil, &|x, y| if f(x) { Cons(x, Arc::new(filter(&y, f))) } else { filter(&y, f) })
  }

  #[allow(dead_code)]
  pub fn concat<T>(list: &List<T>, b: List<T>) -> List<T> where T: Copy, T: Sized {
    fold_right(list, b, &|x, y| Cons(x, Arc::new(y)))
  }

  #[allow(dead_code)]
  pub fn fold_right<T, U>(list: &List<T>, result: U, f: &Fn(T, U) -> U) -> U where T: Copy, T: Sized {
    match *list {
      Cons(ref head, ref tail) =>
        f(*head, fold_right(tail, result, f)),
      Nil => result
    }
  }

  #[allow(dead_code)]
  pub fn fold_left<T, U>(list: &List<T>, result: U, f: &Fn(U, T) -> U) -> U where T: Copy, T: Sized {
    match *list {
      Cons(ref head, ref tail) => fold_left(tail, f(result, *head), f),
      Nil => result
    }
  }

  #[allow(dead_code)]
  pub fn map<T, U>(list: &List<T>, f: &Fn(T) -> U) -> List<U> where T: Copy , U: Copy {
    fold_right(list, Nil, &|x, y| Cons(f(x), Arc::new(y)))
  }

  #[allow(dead_code)]
  pub fn new_list<T>(args: Vec<T>) -> List<T> where T: Copy {
    let mut vec = args;
    let mut x: List<T> = Nil;
    while vec.len() > 0 {
      match vec.pop() {
        Some(e) => x = Cons(e, Arc::new(x)),
        None => {}
      }
    }
    x
  }
}

fn main() {
  let list = new_list(vec![1, 2, 3, 4, 5]);
  println!("{list} contains 3 == {result}", list=list, result=contains(&list, 3));
  println!("{list} contains 6 == {result}", list=list, result=contains(&list, 6));
}
<|endoftext|>


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

//! A pass that promotes borrows of constant rvalues.
//!
//! The rvalues considered constant are trees of temps,
//! each with exactly one initialization, and holding
//! a constant value with no interior mutability.
//! They are placed into a new MIR constant body in
//! `promoted` and the borrow rvalue is replaced with
//! a `Literal::Promoted` using the index into `promoted`
//! of that constant MIR.
//!
//! This pass assumes that every use is dominated by an
//! initialization and can otherwise silence errors, if
//! move analysis runs after promotion on broken MIR.

use rustc::mir::repr::*;
use rustc::mir::visit::{LvalueContext, MutVisitor, Visitor};
use rustc::mir::traversal::ReversePostorder;
use rustc::ty::TyCtxt;
use syntax_pos::Span;

use rustc_data_structures::indexed_vec::{IndexVec, Idx};

use std::iter;
use std::mem;
use std::usize;

/// State of a temporary during collection and promotion.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TempState {
    /// No references to this temp.
    Undefined,
    /// One direct assignment and any number of direct uses.
    /// A borrow of this temp is promotable if the assigned
    /// value is qualified as constant.
    Defined {
        location: Location,
        uses: usize
    },
    /// Any other combination of assignments/uses.
    Unpromotable,
    /// This temp was part of an rvalue which got extracted
    /// during promotion and needs cleanup.
    PromotedOut
}

impl TempState {
    pub fn is_promotable(&self) -> bool {
        if let TempState::Defined { uses, .. } = *self {
            uses > 0
        } else {
            false
        }
    }
}

/// A "root candidate" for promotion, which will become the
/// returned value in a promoted MIR, unless it's a subset
/// of a larger candidate.
pub enum Candidate {
    /// Borrow of a constant temporary.
    Ref(Location),

    /// Array of indices found in the third argument of
    /// a call to one of the simd_shuffleN intrinsics.
    ShuffleIndices(BasicBlock)
}

struct TempCollector<'tcx> {
    temps: IndexVec<Local, TempState>,
    span: Span,
    mir: &'tcx Mir<'tcx>,
}

impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
    fn visit_lvalue(&mut self, lvalue: &Lvalue<'tcx>, context: LvalueContext<'tcx>, location: Location) {
        self.super_lvalue(lvalue, context, location);
        if let Lvalue::Local(index) = *lvalue {
            // We're only interested in temporaries
            if self.mir.local_kind(index) != LocalKind::Temp {
                return;
            }

            // Ignore drops, if the temp gets promoted,
            // then it's constant and thus drop is noop.
            // Storage live ranges are also irrelevant.
            match context {
                LvalueContext::Drop |
                LvalueContext::StorageLive |
                LvalueContext::StorageDead => return,
                _ => {}
            }

            let temp = &mut self.temps[index];
            if *temp == TempState::Undefined {
                match context {
                    LvalueContext::Store |
                    LvalueContext::Call => {
                        *temp = TempState::Defined {
                            location: location,
                            uses: 0
                        };
                        return;
                    }
                    _ => { /* mark as unpromotable below */ }
                }
            } else if let TempState::Defined { ref mut uses, .. } = *temp {
                match context {
                    LvalueContext::Borrow {..} |
                    LvalueContext::Consume |
                    LvalueContext::Inspect => {
                        *uses += 1;
                        return;
                    }
                    _ => { /* mark as unpromotable below */ }
                }
            }
            *temp = TempState::Unpromotable;
        }
    }

    fn visit_source_info(&mut self, source_info: &SourceInfo) {
        self.span = source_info.span;
    }
}

pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec<Local, TempState> {
    let mut collector = TempCollector {
        temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls),
        span: mir.span,
        mir: mir,
    };
    for (bb, data) in rpo {
        collector.visit_basic_block_data(bb, data);
    }
    collector.temps
}

struct Promoter<'a, 'tcx: 'a> {
    source: &'a mut Mir<'tcx>,
    promoted: Mir<'tcx>,
    temps: &'a mut IndexVec<Local, TempState>,

    /// If true, all nested temps are also kept in the
    /// source MIR, not moved to the promoted MIR.
    keep_original: bool
}

impl<'a, 'tcx> Promoter<'a, 'tcx> {
    fn new_block(&mut self) -> BasicBlock {
        let span = self.promoted.span;
        self.promoted.basic_blocks_mut().push(BasicBlockData {
            statements: vec![],
            terminator: Some(Terminator {
                source_info: SourceInfo {
                    span: span,
                    scope: ARGUMENT_VISIBILITY_SCOPE
                },
                kind: TerminatorKind::Return
            }),
            is_cleanup: false
        })
    }

    fn assign(&mut self, dest: Lvalue<'tcx>, rvalue: Rvalue<'tcx>, span: Span) {
        let last = self.promoted.basic_blocks().last().unwrap();
        let data = &mut self.promoted[last];
        data.statements.push(Statement {
            source_info: SourceInfo {
                span: span,
                scope: ARGUMENT_VISIBILITY_SCOPE
            },
            kind: StatementKind::Assign(dest, rvalue)
        });
    }

    /// Copy the initialization of this temp to the
    /// promoted MIR, recursing through temps.
    fn promote_temp(&mut self, temp: Local) -> Local {
        let old_keep_original = self.keep_original;
        let (bb, stmt_idx) = match self.temps[temp] {
            TempState::Defined {
                location: Location { block, statement_index },
                uses
            } if uses > 0 => {
                if uses > 1 {
                    self.keep_original = true;
                }
                (block, statement_index)
            }
            state =>  {
                span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
                          temp, state);
            }
        };
        if !self.keep_original {
            self.temps[temp] = TempState::PromotedOut;
        }

        let no_stmts = self.source[bb].statements.len();

        // First, take the Rvalue or Call out of the source MIR,
        // or duplicate it, depending on keep_original.
        let (mut rvalue, mut call) = (None, None);
        let source_info = if stmt_idx < no_stmts {
            let statement = &mut self.source[bb].statements[stmt_idx];
            let rhs = match statement.kind {
                StatementKind::Assign(_, ref mut rhs) => rhs,
                _ => {
                    span_bug!(statement.source_info.span, "{:?} is not an assignment",
                              statement);
                }
            };
            if self.keep_original {
                rvalue = Some(rhs.clone());
            } else {
                let unit = Rvalue::Aggregate(AggregateKind::Tuple, vec![]);
                rvalue = Some(mem::replace(rhs, unit));
            }
            statement.source_info
        } else if self.keep_original {
            let terminator = self.source[bb].terminator().clone();
            call = Some(terminator.kind);
            terminator.source_info
        } else {
            let terminator = self.source[bb].terminator_mut();
            let target = match terminator.kind {
                TerminatorKind::Call {
                    destination: ref mut dest @ Some(_),
                    ref mut cleanup, ..
                } => {
                    // No cleanup necessary.
                    cleanup.take();

                    // We'll put a new destination in later.
                    dest.take().unwrap().1
                }
                ref kind => {
                    span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
                }
            };
            call = Some(mem::replace(&mut terminator.kind, TerminatorKind::Goto {
                target: target
            }));
            terminator.source_info
        };

        // Then, recurse for components in the Rvalue or Call.
        if stmt_idx < no_stmts {
            self.visit_rvalue(rvalue.as_mut().unwrap(), Location {
                block: bb,
                statement_index: stmt_idx
            });
        } else {
            self.visit_terminator_kind(bb, call.as_mut().unwrap(), Location {
                block: bb,
                statement_index: no_stmts
            });
        }

        let new_temp = self.promoted.local_decls.push(
            LocalDecl::new_temp(self.source.local_decls[temp].ty));

        // Inject the Rvalue or Call into the promoted MIR.
        if stmt_idx < no_stmts {
            self.assign(Lvalue::Local(new_temp), rvalue.unwrap(), source_info.span);
        } else {
            let last = self.promoted.basic_blocks().last().unwrap();
            let new_target = self.new_block();
            let mut call = call.unwrap();
            match call {
                TerminatorKind::Call { ref mut destination, ..}  => {
                    *destination = Some((Lvalue::Local(new_temp), new_target));
                }
                _ => bug!()
            }
            let terminator = self.promoted[last].terminator_mut();
            terminator.source_info.span = source_info.span;
            terminator.kind = call;
        }

        // Restore the old duplication state.
        self.keep_original = old_keep_original;

        new_temp
    }

    fn promote_candidate(mut self, candidate: Candidate) {
        let span = self.promoted.span;
        let new_operand = Operand::Constant(Constant {
            span: span,
            ty: self.promoted.return_ty,
            literal: Literal::Promoted {
                index: Promoted::new(self.source.promoted.len())
            }
        });
        let mut rvalue = match candidate {
            Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
                let ref mut statement = self.source[bb].statements[stmt_idx];
                match statement.kind {
                    StatementKind::Assign(_, ref mut rvalue) => {
                        mem::replace(rvalue, Rvalue::Use(new_operand))
                    }
                    _ => bug!()
                }
            }
            Candidate::ShuffleIndices(bb) => {
                match self.source[bb].terminator_mut().kind {
                    TerminatorKind::Call { ref mut args, .. } => {
                        Rvalue::Use(mem::replace(&mut args[2], new_operand))
                    }
                    _ => bug!()
                }
            }
        };
        self.visit_rvalue(&mut rvalue, Location {
            block: BasicBlock::new(0),
            statement_index: usize::MAX
        });

        self.assign(Lvalue::Local(RETURN_POINTER), rvalue, span);
        self.source.promoted.push(self.promoted);
    }
}

/// Replaces all temporaries with their promoted counterparts.
impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
    fn visit_lvalue(&mut self,
                    lvalue: &mut Lvalue<'tcx>,
                    context: LvalueContext<'tcx>,
                    location: Location) {
        if let Lvalue::Local(ref mut temp) = *lvalue {
            if self.source.local_kind(*temp) == LocalKind::Temp {
                *temp = self.promote_temp(*temp);
            }
        }
        self.super_lvalue(lvalue, context, location);
    }
}

pub fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>,
                                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                    mut temps: IndexVec<Local, TempState>,
                                    candidates: Vec<Candidate>) {
    // Visit candidates in reverse, in case they're nested.
    for candidate in candidates.into_iter().rev() {
        let (span, ty) = match candidate {
            Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
                let statement = &mir[bb].statements[stmt_idx];
                let dest = match statement.kind {
                    StatementKind::Assign(ref dest, _) => dest,
                    _ => {
                        span_bug!(statement.source_info.span,
                                  "expected assignment to promote");
                    }
                };
                if let Lvalue::Local(index) = *dest {
                    if temps[index] == TempState::PromotedOut {
                        // Already promoted.
                        continue;
                    }
                }
                (statement.source_info.span, dest.ty(mir, tcx).to_ty(tcx))
            }
            Candidate::ShuffleIndices(bb) => {
                let terminator = mir[bb].terminator();
                let ty = match terminator.kind {
                    TerminatorKind::Call { ref args, .. } => {
                        args[2].ty(mir, tcx)
                    }
                    _ => {
                        span_bug!(terminator.source_info.span,
                                  "expected simd_shuffleN call to promote");
                    }
                };
                (terminator.source_info.span, ty)
            }
        };

        // Declare return pointer local
        let initial_locals = iter::once(LocalDecl::new_return_pointer(ty)).collect();

        let mut promoter = Promoter {
            promoted: Mir::new(
                IndexVec::new(),
                Some(VisibilityScopeData {
                    span: span,
                    parent_scope: None
                }).into_iter().collect(),
                IndexVec::new(),
                ty,
                initial_locals,
                0,
                vec![],
                span
            ),
            source: mir,
            temps: &mut temps,
            keep_original: false
        };
        assert_eq!(promoter.new_block(), START_BLOCK);
        promoter.promote_candidate(candidate);
    }

    // Eliminate assignments to, and drops of promoted temps.
    let promoted = |index: Local| temps[index] == TempState::PromotedOut;
    for block in mir.basic_blocks_mut() {
        block.statements.retain(|statement| {
            match statement.kind {
                StatementKind::Assign(Lvalue::Local(index), _) |
                StatementKind::StorageLive(Lvalue::Local(index)) |
                StatementKind::StorageDead(Lvalue::Local(index)) => {
                    !promoted(index)
                }
                _ => true
            }
        });
        let terminator = block.terminator_mut();
        match terminator.kind {
            TerminatorKind::Drop { location: Lvalue::Local(index), target, .. } => {
                if promoted(index) {
                    terminator.kind = TerminatorKind::Goto {
                        target: target
                    };
                }
            }
            _ => {}
        }
    }
}
<commit_msg>promote_consts: make assign take a Local<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.

//! A pass that promotes borrows of constant rvalues.
//!
//! The rvalues considered constant are trees of temps,
//! each with exactly one initialization, and holding
//! a constant value with no interior mutability.
//! They are placed into a new MIR constant body in
//! `promoted` and the borrow rvalue is replaced with
//! a `Literal::Promoted` using the index into `promoted`
//! of that constant MIR.
//!
//! This pass assumes that every use is dominated by an
//! initialization and can otherwise silence errors, if
//! move analysis runs after promotion on broken MIR.

use rustc::mir::repr::*;
use rustc::mir::visit::{LvalueContext, MutVisitor, Visitor};
use rustc::mir::traversal::ReversePostorder;
use rustc::ty::TyCtxt;
use syntax_pos::Span;

use rustc_data_structures::indexed_vec::{IndexVec, Idx};

use std::iter;
use std::mem;
use std::usize;

/// State of a temporary during collection and promotion.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TempState {
    /// No references to this temp.
    Undefined,
    /// One direct assignment and any number of direct uses.
    /// A borrow of this temp is promotable if the assigned
    /// value is qualified as constant.
    Defined {
        location: Location,
        uses: usize
    },
    /// Any other combination of assignments/uses.
    Unpromotable,
    /// This temp was part of an rvalue which got extracted
    /// during promotion and needs cleanup.
    PromotedOut
}

impl TempState {
    pub fn is_promotable(&self) -> bool {
        if let TempState::Defined { uses, .. } = *self {
            uses > 0
        } else {
            false
        }
    }
}

/// A "root candidate" for promotion, which will become the
/// returned value in a promoted MIR, unless it's a subset
/// of a larger candidate.
pub enum Candidate {
    /// Borrow of a constant temporary.
    Ref(Location),

    /// Array of indices found in the third argument of
    /// a call to one of the simd_shuffleN intrinsics.
    ShuffleIndices(BasicBlock)
}

struct TempCollector<'tcx> {
    temps: IndexVec<Local, TempState>,
    span: Span,
    mir: &'tcx Mir<'tcx>,
}

impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
    fn visit_lvalue(&mut self, lvalue: &Lvalue<'tcx>, context: LvalueContext<'tcx>, location: Location) {
        self.super_lvalue(lvalue, context, location);
        if let Lvalue::Local(index) = *lvalue {
            // We're only interested in temporaries
            if self.mir.local_kind(index) != LocalKind::Temp {
                return;
            }

            // Ignore drops, if the temp gets promoted,
            // then it's constant and thus drop is noop.
            // Storage live ranges are also irrelevant.
            match context {
                LvalueContext::Drop |
                LvalueContext::StorageLive |
                LvalueContext::StorageDead => return,
                _ => {}
            }

            let temp = &mut self.temps[index];
            if *temp == TempState::Undefined {
                match context {
                    LvalueContext::Store |
                    LvalueContext::Call => {
                        *temp = TempState::Defined {
                            location: location,
                            uses: 0
                        };
                        return;
                    }
                    _ => { /* mark as unpromotable below */ }
                }
            } else if let TempState::Defined { ref mut uses, .. } = *temp {
                match context {
                    LvalueContext::Borrow {..} |
                    LvalueContext::Consume |
                    LvalueContext::Inspect => {
                        *uses += 1;
                        return;
                    }
                    _ => { /* mark as unpromotable below */ }
                }
            }
            *temp = TempState::Unpromotable;
        }
    }

    fn visit_source_info(&mut self, source_info: &SourceInfo) {
        self.span = source_info.span;
    }
}

pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec<Local, TempState> {
    let mut collector = TempCollector {
        temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls),
        span: mir.span,
        mir: mir,
    };
    for (bb, data) in rpo {
        collector.visit_basic_block_data(bb, data);
    }
    collector.temps
}

struct Promoter<'a, 'tcx: 'a> {
    source: &'a mut Mir<'tcx>,
    promoted: Mir<'tcx>,
    temps: &'a mut IndexVec<Local, TempState>,

    /// If true, all nested temps are also kept in the
    /// source MIR, not moved to the promoted MIR.
    keep_original: bool
}

impl<'a, 'tcx> Promoter<'a, 'tcx> {
    fn new_block(&mut self) -> BasicBlock {
        let span = self.promoted.span;
        self.promoted.basic_blocks_mut().push(BasicBlockData {
            statements: vec![],
            terminator: Some(Terminator {
                source_info: SourceInfo {
                    span: span,
                    scope: ARGUMENT_VISIBILITY_SCOPE
                },
                kind: TerminatorKind::Return
            }),
            is_cleanup: false
        })
    }

    fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
        let last = self.promoted.basic_blocks().last().unwrap();
        let data = &mut self.promoted[last];
        data.statements.push(Statement {
            source_info: SourceInfo {
                span: span,
                scope: ARGUMENT_VISIBILITY_SCOPE
            },
            kind: StatementKind::Assign(Lvalue::Local(dest), rvalue)
        });
    }

    /// Copy the initialization of this temp to the
    /// promoted MIR, recursing through temps.
    fn promote_temp(&mut self, temp: Local) -> Local {
        let old_keep_original = self.keep_original;
        let (bb, stmt_idx) = match self.temps[temp] {
            TempState::Defined {
                location: Location { block, statement_index },
                uses
            } if uses > 0 => {
                if uses > 1 {
                    self.keep_original = true;
                }
                (block, statement_index)
            }
            state =>  {
                span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
                          temp, state);
            }
        };
        if !self.keep_original {
            self.temps[temp] = TempState::PromotedOut;
        }

        let no_stmts = self.source[bb].statements.len();

        // First, take the Rvalue or Call out of the source MIR,
        // or duplicate it, depending on keep_original.
        let (mut rvalue, mut call) = (None, None);
        let source_info = if stmt_idx < no_stmts {
            let statement = &mut self.source[bb].statements[stmt_idx];
            let rhs = match statement.kind {
                StatementKind::Assign(_, ref mut rhs) => rhs,
                _ => {
                    span_bug!(statement.source_info.span, "{:?} is not an assignment",
                              statement);
                }
            };
            if self.keep_original {
                rvalue = Some(rhs.clone());
            } else {
                let unit = Rvalue::Aggregate(AggregateKind::Tuple, vec![]);
                rvalue = Some(mem::replace(rhs, unit));
            }
            statement.source_info
        } else if self.keep_original {
            let terminator = self.source[bb].terminator().clone();
            call = Some(terminator.kind);
            terminator.source_info
        } else {
            let terminator = self.source[bb].terminator_mut();
            let target = match terminator.kind {
                TerminatorKind::Call {
                    destination: ref mut dest @ Some(_),
                    ref mut cleanup, ..
                } => {
                    // No cleanup necessary.
                    cleanup.take();

                    // We'll put a new destination in later.
                    dest.take().unwrap().1
                }
                ref kind => {
                    span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
                }
            };
            call = Some(mem::replace(&mut terminator.kind, TerminatorKind::Goto {
                target: target
            }));
            terminator.source_info
        };

        // Then, recurse for components in the Rvalue or Call.
        if stmt_idx < no_stmts {
            self.visit_rvalue(rvalue.as_mut().unwrap(), Location {
                block: bb,
                statement_index: stmt_idx
            });
        } else {
            self.visit_terminator_kind(bb, call.as_mut().unwrap(), Location {
                block: bb,
                statement_index: no_stmts
            });
        }

        let new_temp = self.promoted.local_decls.push(
            LocalDecl::new_temp(self.source.local_decls[temp].ty));

        // Inject the Rvalue or Call into the promoted MIR.
        if stmt_idx < no_stmts {
            self.assign(new_temp, rvalue.unwrap(), source_info.span);
        } else {
            let last = self.promoted.basic_blocks().last().unwrap();
            let new_target = self.new_block();
            let mut call = call.unwrap();
            match call {
                TerminatorKind::Call { ref mut destination, ..}  => {
                    *destination = Some((Lvalue::Local(new_temp), new_target));
                }
                _ => bug!()
            }
            let terminator = self.promoted[last].terminator_mut();
            terminator.source_info.span = source_info.span;
            terminator.kind = call;
        }

        // Restore the old duplication state.
        self.keep_original = old_keep_original;

        new_temp
    }

    fn promote_candidate(mut self, candidate: Candidate) {
        let span = self.promoted.span;
        let new_operand = Operand::Constant(Constant {
            span: span,
            ty: self.promoted.return_ty,
            literal: Literal::Promoted {
                index: Promoted::new(self.source.promoted.len())
            }
        });
        let mut rvalue = match candidate {
            Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
                let ref mut statement = self.source[bb].statements[stmt_idx];
                match statement.kind {
                    StatementKind::Assign(_, ref mut rvalue) => {
                        mem::replace(rvalue, Rvalue::Use(new_operand))
                    }
                    _ => bug!()
                }
            }
            Candidate::ShuffleIndices(bb) => {
                match self.source[bb].terminator_mut().kind {
                    TerminatorKind::Call { ref mut args, .. } => {
                        Rvalue::Use(mem::replace(&mut args[2], new_operand))
                    }
                    _ => bug!()
                }
            }
        };
        self.visit_rvalue(&mut rvalue, Location {
            block: BasicBlock::new(0),
            statement_index: usize::MAX
        });

        self.assign(RETURN_POINTER, rvalue, span);
        self.source.promoted.push(self.promoted);
    }
}

/// Replaces all temporaries with their promoted counterparts.
impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
    fn visit_lvalue(&mut self,
                    lvalue: &mut Lvalue<'tcx>,
                    context: LvalueContext<'tcx>,
                    location: Location) {
        if let Lvalue::Local(ref mut temp) = *lvalue {
            if self.source.local_kind(*temp) == LocalKind::Temp {
                *temp = self.promote_temp(*temp);
            }
        }
        self.super_lvalue(lvalue, context, location);
    }
}

pub fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>,
                                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                    mut temps: IndexVec<Local, TempState>,
                                    candidates: Vec<Candidate>) {
    // Visit candidates in reverse, in case they're nested.
    for candidate in candidates.into_iter().rev() {
        let (span, ty) = match candidate {
            Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
                let statement = &mir[bb].statements[stmt_idx];
                let dest = match statement.kind {
                    StatementKind::Assign(ref dest, _) => dest,
                    _ => {
                        span_bug!(statement.source_info.span,
                                  "expected assignment to promote");
                    }
                };
                if let Lvalue::Local(index) = *dest {
                    if temps[index] == TempState::PromotedOut {
                        // Already promoted.
                        continue;
                    }
                }
                (statement.source_info.span, dest.ty(mir, tcx).to_ty(tcx))
            }
            Candidate::ShuffleIndices(bb) => {
                let terminator = mir[bb].terminator();
                let ty = match terminator.kind {
                    TerminatorKind::Call { ref args, .. } => {
                        args[2].ty(mir, tcx)
                    }
                    _ => {
                        span_bug!(terminator.source_info.span,
                                  "expected simd_shuffleN call to promote");
                    }
                };
                (terminator.source_info.span, ty)
            }
        };

        // Declare return pointer local
        let initial_locals = iter::once(LocalDecl::new_return_pointer(ty)).collect();

        let mut promoter = Promoter {
            promoted: Mir::new(
                IndexVec::new(),
                Some(VisibilityScopeData {
                    span: span,
                    parent_scope: None
                }).into_iter().collect(),
                IndexVec::new(),
                ty,
                initial_locals,
                0,
                vec![],
                span
            ),
            source: mir,
            temps: &mut temps,
            keep_original: false
        };
        assert_eq!(promoter.new_block(), START_BLOCK);
        promoter.promote_candidate(candidate);
    }

    // Eliminate assignments to, and drops of promoted temps.
    let promoted = |index: Local| temps[index] == TempState::PromotedOut;
    for block in mir.basic_blocks_mut() {
        block.statements.retain(|statement| {
            match statement.kind {
                StatementKind::Assign(Lvalue::Local(index), _) |
                StatementKind::StorageLive(Lvalue::Local(index)) |
                StatementKind::StorageDead(Lvalue::Local(index)) => {
                    !promoted(index)
                }
                _ => true
            }
        });
        let terminator = block.terminator_mut();
        match terminator.kind {
            TerminatorKind::Drop { location: Lvalue::Local(index), target, .. } => {
                if promoted(index) {
                    terminator.kind = TerminatorKind::Goto {
                        target: target
                    };
                }
            }
            _ => {}
        }
    }
}
<|endoftext|>


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

// revisions: lxl nll
//[lxl]compile-flags: -Z borrowck=mir -Z two-phase-borrows
//[nll]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll

// This is a corner case that the current implementation is (probably)
// treating more conservatively than is necessary. But it also does
// not seem like a terribly important use case to cover.
//
// So this test is just making a note of the current behavior, with
// the caveat that in the future, the rules may be loosened, at which
// point this test might be thrown out.

fn main() {
    let mut vec = vec![0, 1];
    let delay: &mut Vec<_>;
    {
        let shared = &vec;

        // we reserve here, which could (on its own) be compatible
        // with the shared borrow. But in the current implementation,
        // its an error.
        delay = &mut vec;
        //[lxl]~^ ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable
        //[nll]~^^   ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable

        shared[0];
    }

    // the &mut-borrow only becomes active way down here.
    //
    // (At least in theory; part of the reason this test fails is that
    // the constructed MIR throws in extra &mut reborrows which
    // flummoxes our attmpt to delay the activation point here.)
    delay.push(2);
}

<|endoftext|>


<commit_before><commit_msg>refactor: simplify `is_str`<commit_after><|endoftext|>


<commit_before><commit_msg> start new<commit_after>fn main() {
    let test0 = Vec::new();
    let test1 = vec![2, 1, 2, 1, 0, 1, 2];
    let test2 = vec![1];
    let test3 = vec![7, 1, 5, 3, 6, 4];
    let test4 = vec![2, 4, 1];
}
<|endoftext|>


<commit_before>use alloc::boxed::Box;

use collections::string::String;

use core::ops::DerefMut;

use common::event::{Event, KeyEvent, MouseEvent, QuitEvent};
use common::queue::Queue;
use common::scheduler;

use super::color::Color;
use super::display::Display;
use super::point::Point;
use super::size::Size;

/// A window
pub struct Window {
    /// The position of the window
    pub point: Point,
    /// The size of the window
    pub size: Size,
    /// The title of the window
    pub title: String,
    /// The content of the window
    pub content: Box<Display>,
    /// The color of the window title
    pub title_color: Color,
    /// The color of the border
    pub border_color: Color,
    /// Is the window focused?
    pub focused: bool,
    /// Is the window minimized?
    pub minimized: bool,
    dragging: bool,
    last_mouse_event: MouseEvent,
    events: Queue<Event>,
    ptr: *mut Window,
}

impl Window {
    /// Create a new window
    pub fn new(point: Point, size: Size, title: String) -> Box<Self> {
        let mut ret = box Window {
            point: point,
            size: size,
            title: title,
            content: Display::new(size.width, size.height),
            title_color: Color::new(255, 255, 255),
            border_color: Color::alpha(64, 64, 64, 128),
            focused: false,
            minimized: false,
            dragging: false,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                right_button: false,
                middle_button: false,
            },
            events: Queue::new(),
            ptr: 0 as *mut Window,
        };

        unsafe {
            ret.ptr = ret.deref_mut();

            if ret.ptr as usize > 0 {
                (*::session_ptr).add_window(ret.ptr);
            }
        }

        ret
    }

    /// Poll the window (new)
    pub fn poll(&mut self) -> Option<Event> {
        let event_option;
        unsafe {
            let reenable = scheduler::start_no_ints();
            event_option = self.events.pop();
            scheduler::end_no_ints(reenable);
        }

        return event_option;
    }

    /// Redraw the window
    pub fn redraw(&mut self) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.content.flip();
            (*::session_ptr).redraw = true;
            scheduler::end_no_ints(reenable);
        }
    }

    /// Draw the window using a `Display`
    pub fn draw(&mut self, display: &Display) {
        if self.focused {
            self.border_color = Color::alpha(128, 128, 128, 192);
        } else {
            self.border_color = Color::alpha(64, 64, 64, 128);
        }

        if self.minimized {
            self.title_color = Color::new(0, 0, 0);
        } else {
            self.title_color = Color::new(255, 255, 255);

            display.rect(Point::new(self.point.x - 2, self.point.y - 18),
                         Size::new(self.size.width + 4, 18),
                         self.border_color);

            let mut cursor = Point::new(self.point.x, self.point.y - 17);
            for c in self.title.chars() {
                if cursor.x + 8 <= self.point.x + self.size.width as isize {
                    display.char(cursor, c, self.title_color);
                }
                cursor.x += 8;
            }

            display.rect(Point::new(self.point.x - 2, self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);
            display.rect(Point::new(self.point.x - 2,
                                    self.point.y + self.size.height as isize),
                         Size::new(self.size.width + 4, 2),
                         self.border_color);
            display.rect(Point::new(self.point.x + self.size.width as isize,
                                    self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);

            unsafe {
                let reenable = scheduler::start_no_ints();
                display.image(self.point,
                              self.content.onscreen as *const u32,
                              Size::new(self.content.width, self.content.height));
                scheduler::end_no_ints(reenable);
            }
        }
    }

    /// Called on key press
    pub fn on_key(&mut self, key_event: KeyEvent) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.events.push(key_event.to_event());
            scheduler::end_no_ints(reenable);
        }
    }

    fn on_window_decoration(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= -2 &&
            x < self.size.width as isize + 4 &&
            y >= -18 &&
            y < self.size.height as isize + 2
    }

    /// Called on mouse movement
    pub fn on_mouse(&mut self, orig_mouse_event: MouseEvent, allow_catch: bool) -> bool {
        let mut mouse_event = orig_mouse_event;

        mouse_event.x -= self.point.x;
        mouse_event.y -= self.point.y;

        let mut caught = false;

        if allow_catch {
            if mouse_event.left_button {
                if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                }

                if !self.last_mouse_event.left_button && mouse_event.x >= -2 &&
                   mouse_event.x < self.size.width as isize + 4 &&
                   mouse_event.y >= -18 && mouse_event.y < 0 {
                    self.dragging = true;
                    caught = true;
                }
            } else {
                self.dragging = false;
            }

            if mouse_event.right_button {
                if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                }

                if !self.last_mouse_event.right_button && mouse_event.x >= -2 &&
                   mouse_event.x < self.size.width as isize + 4 &&
                   mouse_event.y >= -18 && mouse_event.y < 0 {
                    self.minimized = !self.minimized;
                    caught = true;
                }
            }

            if mouse_event.middle_button {
                if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    unsafe {
                        let reenable = scheduler::start_no_ints();
                        self.events.push(QuitEvent.to_event());
                        scheduler::end_no_ints(reenable);
                    }
                }
            }

            if self.dragging {
                self.point.x += orig_mouse_event.x - self.last_mouse_event.x;
                self.point.y += orig_mouse_event.y - self.last_mouse_event.y;
                caught = true;
            }
        } else {
            self.dragging = false;
        }

        self.last_mouse_event = orig_mouse_event;

        if caught && !self.dragging {
            unsafe {
                let reenable = scheduler::start_no_ints();
                self.events.push(mouse_event.to_event());
                scheduler::end_no_ints(reenable);
            }
        }

        caught
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            if self.ptr as usize > 0 {
                (*::session_ptr).remove_window(self.ptr);
            }
        }
    }
}
<commit_msg>Fix mouse events<commit_after>use alloc::boxed::Box;

use collections::string::String;

use core::ops::DerefMut;

use common::event::{Event, KeyEvent, MouseEvent, QuitEvent};
use common::queue::Queue;
use common::scheduler;

use super::color::Color;
use super::display::Display;
use super::point::Point;
use super::size::Size;

/// A window
pub struct Window {
    /// The position of the window
    pub point: Point,
    /// The size of the window
    pub size: Size,
    /// The title of the window
    pub title: String,
    /// The content of the window
    pub content: Box<Display>,
    /// The color of the window title
    pub title_color: Color,
    /// The color of the border
    pub border_color: Color,
    /// Is the window focused?
    pub focused: bool,
    /// Is the window minimized?
    pub minimized: bool,
    dragging: bool,
    last_mouse_event: MouseEvent,
    events: Queue<Event>,
    ptr: *mut Window,
}

impl Window {
    /// Create a new window
    pub fn new(point: Point, size: Size, title: String) -> Box<Self> {
        let mut ret = box Window {
            point: point,
            size: size,
            title: title,
            content: Display::new(size.width, size.height),
            title_color: Color::new(255, 255, 255),
            border_color: Color::alpha(64, 64, 64, 128),
            focused: false,
            minimized: false,
            dragging: false,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                right_button: false,
                middle_button: false,
            },
            events: Queue::new(),
            ptr: 0 as *mut Window,
        };

        unsafe {
            ret.ptr = ret.deref_mut();

            if ret.ptr as usize > 0 {
                (*::session_ptr).add_window(ret.ptr);
            }
        }

        ret
    }

    /// Poll the window (new)
    pub fn poll(&mut self) -> Option<Event> {
        let event_option;
        unsafe {
            let reenable = scheduler::start_no_ints();
            event_option = self.events.pop();
            scheduler::end_no_ints(reenable);
        }

        return event_option;
    }

    /// Redraw the window
    pub fn redraw(&mut self) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.content.flip();
            (*::session_ptr).redraw = true;
            scheduler::end_no_ints(reenable);
        }
    }

    /// Draw the window using a `Display`
    pub fn draw(&mut self, display: &Display) {
        if self.focused {
            self.border_color = Color::alpha(128, 128, 128, 192);
        } else {
            self.border_color = Color::alpha(64, 64, 64, 128);
        }

        if self.minimized {
            self.title_color = Color::new(0, 0, 0);
        } else {
            self.title_color = Color::new(255, 255, 255);

            display.rect(Point::new(self.point.x - 2, self.point.y - 18),
                         Size::new(self.size.width + 4, 18),
                         self.border_color);

            let mut cursor = Point::new(self.point.x, self.point.y - 17);
            for c in self.title.chars() {
                if cursor.x + 8 <= self.point.x + self.size.width as isize {
                    display.char(cursor, c, self.title_color);
                }
                cursor.x += 8;
            }

            display.rect(Point::new(self.point.x - 2, self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);
            display.rect(Point::new(self.point.x - 2,
                                    self.point.y + self.size.height as isize),
                         Size::new(self.size.width + 4, 2),
                         self.border_color);
            display.rect(Point::new(self.point.x + self.size.width as isize,
                                    self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);

            unsafe {
                let reenable = scheduler::start_no_ints();
                display.image(self.point,
                              self.content.onscreen as *const u32,
                              Size::new(self.content.width, self.content.height));
                scheduler::end_no_ints(reenable);
            }
        }
    }

    /// Called on key press
    pub fn on_key(&mut self, key_event: KeyEvent) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.events.push(key_event.to_event());
            scheduler::end_no_ints(reenable);
        }
    }

    fn on_window_decoration(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= -2 &&
            x < self.size.width as isize + 4 &&
            y >= -18 &&
            y < 0
    }

    fn on_window_body(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= 0 &&
            x < self.size.width as isize &&
            y >= 0 &&
            y < self.size.height as isize
    }

    /// Called on mouse movement
    pub fn on_mouse(&mut self, orig_mouse_event: MouseEvent, allow_catch: bool) -> bool {
        let mut mouse_event = orig_mouse_event;

        mouse_event.x -= self.point.x;
        mouse_event.y -= self.point.y;

        let mut caught = false;

        if allow_catch {
            if mouse_event.left_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    if !self.last_mouse_event.left_button {
                        self.dragging = true;
                    }
                }
            } else {
                self.dragging = false;
            }

            if mouse_event.right_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    if !self.last_mouse_event.right_button {
                        self.minimized = !self.minimized;
                    }
                }
            }

            if mouse_event.middle_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    unsafe {
                        let reenable = scheduler::start_no_ints();
                        self.events.push(QuitEvent.to_event());
                        scheduler::end_no_ints(reenable);
                    }
                }
            }

            if self.dragging {
                self.point.x += orig_mouse_event.x - self.last_mouse_event.x;
                self.point.y += orig_mouse_event.y - self.last_mouse_event.y;
                caught = true;
            }
        } else {
            self.dragging = false;
        }

        self.last_mouse_event = orig_mouse_event;

        if (caught && !self.dragging) || self.on_window_body(mouse_event.x, mouse_event.y) {
            unsafe {
                let reenable = scheduler::start_no_ints();
                self.events.push(mouse_event.to_event());
                scheduler::end_no_ints(reenable);
            }
        }

        caught
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            if self.ptr as usize > 0 {
                (*::session_ptr).remove_window(self.ptr);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Removed unused "use" directive<commit_after><|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/25-code/multiple_phrases/src/english/mod.rs<commit_after><|endoftext|>


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

// compile-flags:-Zmir-opt-level=2
pub trait Foo {
    fn bar(&self) -> usize { 2 }
}

impl Foo for () {
    fn bar(&self) -> usize { 3 }
}

fn main() {
    let result = ().bar();
    assert_eq!(result, 3);
}
<|endoftext|>


<commit_before><commit_msg>have cargoless hello_world too<commit_after>fn main() {
    println!("Hello, world!");
}

<|endoftext|>


<commit_before><commit_msg>Fix conversion of image data slice<commit_after><|endoftext|>


<commit_before><commit_msg>simple image viewer<commit_after><|endoftext|>


<commit_before><commit_msg>Add message why panic<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2367<commit_after>// https://leetcode.com/problems/number-of-arithmetic-triplets/
pub fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 {
    todo!()
}

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


<commit_before><commit_msg>Skeleton for problem 2456<commit_after>// https://leetcode.com/problems/words-within-two-edits-of-dictionary/
pub fn two_edit_words(queries: Vec<String>, dictionary: Vec<String>) -> Vec<String> {
    todo!()
}

fn main() {
    println!(
        "{:?}",
        two_edit_words(
            vec![
                "word".to_string(),
                "note".to_string(),
                "ants".to_string(),
                "wood".to_string()
            ],
            vec!["wood".to_string(), "joke".to_string(), "moat".to_string()]
        )
    ); // ["word","note","wood"]
    println!(
        "{:?}",
        two_edit_words(vec!["yes".to_string()], vec!["not".to_string()])
    ); // []
}
<|endoftext|>


<commit_before><commit_msg>Review feedback: Added test with control flow merge of two borrows "before activation"<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// revisions: lxl nll
//[lxl]compile-flags: -Z borrowck=mir -Z two-phase-borrows
//[nll]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll

fn main() {
    let mut a = 0;
    let mut b = 0;
    let p = if maybe() {
        &mut a
    } else {
        &mut b
    };
    use_(p);
}

fn maybe() -> bool { false }
fn use_<T>(_: T) { }
<|endoftext|>


<commit_before><commit_msg>chore: eprintln<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2335<commit_after>// https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/
pub fn fill_cups(amount: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", fill_cups(vec![1, 4, 2])); // 4
    println!("{}", fill_cups(vec![5, 4, 4])); // 7
    println!("{}", fill_cups(vec![5, 0, 0])); // 5
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2363<commit_after>// https://leetcode.com/problems/merge-similar-items/
pub fn merge_similar_items(items1: Vec<Vec<i32>>, items2: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    todo!()
}

fn main() {
    println!(
        "{}",
        merge_similar_items(
            vec![vec![1, 1], vec![4, 5], vec![3, 8]],
            vec![vec![3, 1], vec![1, 5]]
        )
    ); // [[1,6],[3,9],[4,5]]
    println!(
        "{}",
        merge_similar_items(
            vec![vec![1, 1], vec![3, 2], vec![2, 3]],
            vec![vec![2, 1], vec![3, 2], vec![1, 3]]
        )
    ); // [[1,4],[2,4],[3,4]]
    println!(
        "{}",
        merge_similar_items(
            vec![vec![1, 3], vec![2, 2]],
            vec![vec![7, 1], vec![2, 2], vec![1, 4]]
        )
    ); // [[1,7],[2,4],[7,1]]
}
<|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.

#![allow(non_snake_case)]

register_long_diagnostics! {

E0081: r##"
Enum discriminants are used to differentiate enum variants stored in memory.
This error indicates that the same value was used for two or more variants,
making them impossible to tell apart.

```
// Good.
enum Enum {
    P,
    X = 3,
    Y = 5
}

// Bad.
enum Enum {
    P = 3,
    X = 3,
    Y = 5
}
```

Note that variants without a manually specified discriminant are numbered from
top to bottom starting from 0, so clashes can occur with seemingly unrelated
variants.

```
enum Bad {
    X,
    Y = 0
}
```

Here `X` will have already been assigned the discriminant 0 by the time `Y` is
encountered, so a conflict occurs.
"##,

E0082: r##"
The default type for enum discriminants is `isize`, but it can be adjusted by
adding the `repr` attribute to the enum declaration. This error indicates that
an integer literal given as a discriminant is not a member of the discriminant
type. For example:

```
#[repr(u8)]
enum Thing {
    A = 1024,
    B = 5
}
```

Here, 1024 lies outside the valid range for `u8`, so the discriminant for `A` is
invalid. You may want to change representation types to fix this, or else change
invalid discriminant values so that they fit within the existing type.

Note also that without a representation manually defined, the compiler will
optimize by using the smallest integer type possible.
"##,

E0083: r##"
At present, it's not possible to define a custom representation for an enum with
a single variant. As a workaround you can add a `Dummy` variant.

See: https://github.com/rust-lang/rust/issues/10292
"##,

E0084: r##"
It is impossible to define an integer type to be used to represent zero-variant
enum values because there are no zero-variant enum values. There is no way to
construct an instance of the following type using only safe code:

```
enum Empty {}
```
"##

}

register_diagnostics! {
    E0023,
    E0024,
    E0025,
    E0026,
    E0027,
    E0029,
    E0030,
    E0031,
    E0033,
    E0034,
    E0035,
    E0036,
    E0038,
    E0040, // explicit use of destructor method
    E0044,
    E0045,
    E0046,
    E0049,
    E0050,
    E0053,
    E0054,
    E0055,
    E0057,
    E0059,
    E0060,
    E0061,
    E0062,
    E0063,
    E0066,
    E0067,
    E0068,
    E0069,
    E0070,
    E0071,
    E0072,
    E0073,
    E0074,
    E0075,
    E0076,
    E0077,
    E0085,
    E0086,
    E0087,
    E0088,
    E0089,
    E0090,
    E0091,
    E0092,
    E0093,
    E0094,
    E0101,
    E0102,
    E0103,
    E0104,
    E0106,
    E0107,
    E0116,
    E0117,
    E0118,
    E0119,
    E0120,
    E0121,
    E0122,
    E0123,
    E0124,
    E0127,
    E0128,
    E0129,
    E0130,
    E0131,
    E0132,
    E0141,
    E0159,
    E0163,
    E0164,
    E0166,
    E0167,
    E0168,
    E0172,
    E0173, // manual implementations of unboxed closure traits are experimental
    E0174, // explicit use of unboxed closure methods are experimental
    E0178,
    E0182,
    E0183,
    E0184,
    E0185,
    E0186,
    E0187, // can't infer the kind of the closure
    E0188, // types differ in mutability
    E0189, // can only cast a boxed pointer to a boxed object
    E0190, // can only cast a &-pointer to an &-object
    E0191, // value of the associated type must be specified
    E0192, // negative imples are allowed just for `Send` and `Sync`
    E0193, // cannot bound type where clause bounds may only be attached to types
           // involving type parameters
    E0194,
    E0195, // lifetime parameters or bounds on method do not match the trait declaration
    E0196, // cannot determine a type for this closure
    E0197, // inherent impls cannot be declared as unsafe
    E0198, // negative implementations are not unsafe
    E0199, // implementing trait is not unsafe
    E0200, // trait requires an `unsafe impl` declaration
    E0201, // duplicate method in trait impl
    E0202, // associated items are not allowed in inherent impls
    E0203, // type parameter has more than one relaxed default bound,
           // and only one is supported
    E0204, // trait `Copy` may not be implemented for this type; field
           // does not implement `Copy`
    E0205, // trait `Copy` may not be implemented for this type; variant
           // does not implement `copy`
    E0206, // trait `Copy` may not be implemented for this type; type is
           // not a structure or enumeration
    E0207, // type parameter is not constrained by the impl trait, self type, or predicate
    E0208,
    E0209, // builtin traits can only be implemented on structs or enums
    E0210, // type parameter is not constrained by any local type
    E0211,
    E0212, // cannot extract an associated type from a higher-ranked trait bound
    E0213, // associated types are not accepted in this context
    E0214, // parenthesized parameters may only be used with a trait
    E0215, // angle-bracket notation is not stable with `Fn`
    E0216, // parenthetical notation is only stable with `Fn`
    E0217, // ambiguous associated type, defined in multiple supertraits
    E0218, // no associated type defined
    E0219, // associated type defined in higher-ranked supertrait
    E0220, // associated type not found for type parameter
    E0221, // ambiguous associated type in bounds
    E0222, // variadic function must have C calling convention
    E0223, // ambiguous associated type
    E0224, // at least one non-builtin train is required for an object type
    E0225, // only the builtin traits can be used as closure or object bounds
    E0226, // only a single explicit lifetime bound is permitted
    E0227, // ambiguous lifetime bound, explicit lifetime bound required
    E0228, // explicit lifetime bound required
    E0229, // associated type bindings are not allowed here
    E0230, // there is no type parameter on trait
    E0231, // only named substitution parameters are allowed
    E0232, // this attribute must have a value
    E0233,
    E0234, // `for` loop expression has type which does not implement the `Iterator` trait
    E0235, // structure constructor specifies a structure of type but
    E0236, // no lang item for range syntax
    E0237, // no lang item for range syntax
    E0238, // parenthesized parameters may only be used with a trait
    E0239, // `next` method of `Iterator` trait has unexpected type
    E0240,
    E0241,
    E0242, // internal error looking up a definition
    E0243, // wrong number of type arguments
    E0244, // wrong number of type arguments
    E0245, // not a trait
    E0246, // illegal recursive type
    E0247, // found module name used as a type
    E0248, // found value name used as a type
    E0249, // expected constant expr for array length
    E0250, // expected constant expr for array length
    E0318, // can't create default impls for traits outside their crates
    E0319, // trait impls for defaulted traits allowed just for structs/enums
    E0320, // recursive overflow during dropck
    E0321, // extended coherence rules for defaulted traits violated
    E0322, // cannot implement Sized explicitly
    E0323, // implemented an associated const when another trait item expected
    E0324, // implemented a method when another trait item expected
    E0325, // implemented an associated type when another trait item expected
    E0326, // associated const implemented with different type from trait
    E0327, // referred to method instead of constant in match pattern
    E0366, // dropck forbid specialization to concrete type or region
    E0367, // dropck forbid specialization to predicate not in struct/enum
    E0368, // binary operation `<op>=` cannot be applied to types
    E0369, // binary operation `<op>` cannot be applied to types
    E0371, // impl Trait for Trait is illegal
    E0372  // impl Trait for Trait where Trait is not object safe
}
<commit_msg>Rollup merge of #25190 - nham:E0046_E0054, 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.

#![allow(non_snake_case)]

register_long_diagnostics! {

E0046: r##"
When trying to make some type implement a trait `Foo`, you must, at minimum,
provide implementations for all of `Foo`'s required methods (meaning the
methods that do not have default implementations), as well as any required
trait items like associated types or constants.
"##,

E0054: r##"
It is not allowed to cast to a bool. If you are trying to cast a numeric type
to a bool, you can compare it with zero instead:

```
let x = 5;

// Ok
let x_is_nonzero = x != 0;

// Not allowed, won't compile
let x_is_nonzero = x as bool;
```
"##,

E0081: r##"
Enum discriminants are used to differentiate enum variants stored in memory.
This error indicates that the same value was used for two or more variants,
making them impossible to tell apart.

```
// Good.
enum Enum {
    P,
    X = 3,
    Y = 5
}

// Bad.
enum Enum {
    P = 3,
    X = 3,
    Y = 5
}
```

Note that variants without a manually specified discriminant are numbered from
top to bottom starting from 0, so clashes can occur with seemingly unrelated
variants.

```
enum Bad {
    X,
    Y = 0
}
```

Here `X` will have already been assigned the discriminant 0 by the time `Y` is
encountered, so a conflict occurs.
"##,

E0082: r##"
The default type for enum discriminants is `isize`, but it can be adjusted by
adding the `repr` attribute to the enum declaration. This error indicates that
an integer literal given as a discriminant is not a member of the discriminant
type. For example:

```
#[repr(u8)]
enum Thing {
    A = 1024,
    B = 5
}
```

Here, 1024 lies outside the valid range for `u8`, so the discriminant for `A` is
invalid. You may want to change representation types to fix this, or else change
invalid discriminant values so that they fit within the existing type.

Note also that without a representation manually defined, the compiler will
optimize by using the smallest integer type possible.
"##,

E0083: r##"
At present, it's not possible to define a custom representation for an enum with
a single variant. As a workaround you can add a `Dummy` variant.

See: https://github.com/rust-lang/rust/issues/10292
"##,

E0084: r##"
It is impossible to define an integer type to be used to represent zero-variant
enum values because there are no zero-variant enum values. There is no way to
construct an instance of the following type using only safe code:

```
enum Empty {}
```
"##

}

register_diagnostics! {
    E0023,
    E0024,
    E0025,
    E0026,
    E0027,
    E0029,
    E0030,
    E0031,
    E0033,
    E0034,
    E0035,
    E0036,
    E0038,
    E0040, // explicit use of destructor method
    E0044,
    E0045,
    E0049,
    E0050,
    E0053,
    E0055,
    E0057,
    E0059,
    E0060,
    E0061,
    E0062,
    E0063,
    E0066,
    E0067,
    E0068,
    E0069,
    E0070,
    E0071,
    E0072,
    E0073,
    E0074,
    E0075,
    E0076,
    E0077,
    E0085,
    E0086,
    E0087,
    E0088,
    E0089,
    E0090,
    E0091,
    E0092,
    E0093,
    E0094,
    E0101,
    E0102,
    E0103,
    E0104,
    E0106,
    E0107,
    E0116,
    E0117,
    E0118,
    E0119,
    E0120,
    E0121,
    E0122,
    E0123,
    E0124,
    E0127,
    E0128,
    E0129,
    E0130,
    E0131,
    E0132,
    E0141,
    E0159,
    E0163,
    E0164,
    E0166,
    E0167,
    E0168,
    E0172,
    E0173, // manual implementations of unboxed closure traits are experimental
    E0174, // explicit use of unboxed closure methods are experimental
    E0178,
    E0182,
    E0183,
    E0184,
    E0185,
    E0186,
    E0187, // can't infer the kind of the closure
    E0188, // types differ in mutability
    E0189, // can only cast a boxed pointer to a boxed object
    E0190, // can only cast a &-pointer to an &-object
    E0191, // value of the associated type must be specified
    E0192, // negative imples are allowed just for `Send` and `Sync`
    E0193, // cannot bound type where clause bounds may only be attached to types
           // involving type parameters
    E0194,
    E0195, // lifetime parameters or bounds on method do not match the trait declaration
    E0196, // cannot determine a type for this closure
    E0197, // inherent impls cannot be declared as unsafe
    E0198, // negative implementations are not unsafe
    E0199, // implementing trait is not unsafe
    E0200, // trait requires an `unsafe impl` declaration
    E0201, // duplicate method in trait impl
    E0202, // associated items are not allowed in inherent impls
    E0203, // type parameter has more than one relaxed default bound,
           // and only one is supported
    E0204, // trait `Copy` may not be implemented for this type; field
           // does not implement `Copy`
    E0205, // trait `Copy` may not be implemented for this type; variant
           // does not implement `copy`
    E0206, // trait `Copy` may not be implemented for this type; type is
           // not a structure or enumeration
    E0207, // type parameter is not constrained by the impl trait, self type, or predicate
    E0208,
    E0209, // builtin traits can only be implemented on structs or enums
    E0210, // type parameter is not constrained by any local type
    E0211,
    E0212, // cannot extract an associated type from a higher-ranked trait bound
    E0213, // associated types are not accepted in this context
    E0214, // parenthesized parameters may only be used with a trait
    E0215, // angle-bracket notation is not stable with `Fn`
    E0216, // parenthetical notation is only stable with `Fn`
    E0217, // ambiguous associated type, defined in multiple supertraits
    E0218, // no associated type defined
    E0219, // associated type defined in higher-ranked supertrait
    E0220, // associated type not found for type parameter
    E0221, // ambiguous associated type in bounds
    E0222, // variadic function must have C calling convention
    E0223, // ambiguous associated type
    E0224, // at least one non-builtin train is required for an object type
    E0225, // only the builtin traits can be used as closure or object bounds
    E0226, // only a single explicit lifetime bound is permitted
    E0227, // ambiguous lifetime bound, explicit lifetime bound required
    E0228, // explicit lifetime bound required
    E0229, // associated type bindings are not allowed here
    E0230, // there is no type parameter on trait
    E0231, // only named substitution parameters are allowed
    E0232, // this attribute must have a value
    E0233,
    E0234, // `for` loop expression has type which does not implement the `Iterator` trait
    E0235, // structure constructor specifies a structure of type but
    E0236, // no lang item for range syntax
    E0237, // no lang item for range syntax
    E0238, // parenthesized parameters may only be used with a trait
    E0239, // `next` method of `Iterator` trait has unexpected type
    E0240,
    E0241,
    E0242, // internal error looking up a definition
    E0243, // wrong number of type arguments
    E0244, // wrong number of type arguments
    E0245, // not a trait
    E0246, // illegal recursive type
    E0247, // found module name used as a type
    E0248, // found value name used as a type
    E0249, // expected constant expr for array length
    E0250, // expected constant expr for array length
    E0318, // can't create default impls for traits outside their crates
    E0319, // trait impls for defaulted traits allowed just for structs/enums
    E0320, // recursive overflow during dropck
    E0321, // extended coherence rules for defaulted traits violated
    E0322, // cannot implement Sized explicitly
    E0323, // implemented an associated const when another trait item expected
    E0324, // implemented a method when another trait item expected
    E0325, // implemented an associated type when another trait item expected
    E0326, // associated const implemented with different type from trait
    E0327, // referred to method instead of constant in match pattern
    E0366, // dropck forbid specialization to concrete type or region
    E0367, // dropck forbid specialization to predicate not in struct/enum
    E0368, // binary operation `<op>=` cannot be applied to types
    E0369, // binary operation `<op>` cannot be applied to types
    E0371, // impl Trait for Trait is illegal
    E0372  // impl Trait for Trait where Trait is not object safe
}
<|endoftext|>


<commit_before><commit_msg>Add a test for binding bare functions<commit_after>fn# f(i: int) {
    assert i == 10;
}

fn main() {
    // Binding a bare function turns it into a shared closure
    let g: fn() = bind f(10);
    g();
}<|endoftext|>


<commit_before><commit_msg>Add regression test for #20862<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.

fn foo(x: i32) {
    |y| x + y
//~^ ERROR: mismatched types:
//~| expected `()`,
//~|     found closure
//~| (expected (),
//~|     found closure) [E0308]
}

fn main() {
    let x = foo(5)(2);
//~^ ERROR: expected function, found `()`
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #44415<commit_after>// Copyright 2018 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(const_fn)]
#![feature(core_intrinsics)]

use std::intrinsics;

struct Foo {
    bytes: [u8; unsafe { intrinsics::size_of::<Foo>() }],
    //~^ ERROR unsupported cyclic reference between types/traits detected
    x: usize,
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Added test for immutable unique closure upvar mutation.<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.

// revisions: ast mir
//[mir]compile-flags: -Z emit-end-regions -Z borrowck=mir

fn main() {
    let x = 0;

    (move || {
        x = 1;
        //[mir]~^ ERROR cannot assign to immutable item `x` [E0594]
        //[ast]~^^ ERROR cannot assign to captured outer variable in an `FnMut` closure [E0594]
    })()
}
<|endoftext|>