<commit_before>#![allow(dead_code)]

use self::Key::*;
use std::io::{File, Open, Read, Write};
use libc::{c_ushort, c_int, c_ulong};
use std::os::unix::AsRawFd;
use std::io::process::{Command, InheritFd};
use std::iter::repeat;
use std::cmp::min;
use ansi;

use std::thread::Thread;
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;

pub struct Screen {
  tty: Terminal,
  original_stty_state: Vec<u8>,
  pub height: u16,
  pub width: u16,
  pub visible_choices: u16,
  pub start_line: u16,
}

impl Screen {
  pub fn open_screen() -> Screen {
    let mut tty = Terminal::open_terminal();
    let current_stty_state = tty.stty(&["-g"]);
    tty.initialize();
    let (cols, rows) = tty.winsize().unwrap();
    let visible_choices = min(20, rows - 1);
    let start_line = rows - visible_choices - 1;
    Screen {
      tty: tty,
      original_stty_state: current_stty_state,
      height: rows,
      width: cols,
      visible_choices: visible_choices,
      start_line: start_line,
    }
  }

  fn restore_tty(&mut self) {
    self.tty.stty(&[String::from_utf8(self.original_stty_state.clone()).unwrap().as_slice()]);
  }

  pub fn move_cursor(&mut self, line: u16, column: u16) {
    self.tty.write(ansi::setpos(line, column).as_slice());
  }

  pub fn move_cursor_to_bottom(&mut self) {
    let end_line = self.start_line + self.visible_choices;
    self.move_cursor(end_line, 0);
    self.write("\n");
  }

  pub fn blank_screen(&mut self) {
    let start_line = self.start_line;
    self.move_cursor(start_line, 0);
    let blank_line = repeat(' ').take(self.width as usize).collect::<String>();
    for _ in range(0, self.height) {
      self.tty.write(blank_line.as_bytes());
    }
    self.move_cursor(start_line, 0);
  }

  pub fn show_cursor(&mut self) {
    self.tty.write(ansi::show_cursor().as_slice());
  }

  pub fn hide_cursor(&mut self) {
    self.tty.write(ansi::hide_cursor().as_slice());
  }

  pub fn write(&mut self, s: &str) {
    self.tty.write(s.as_bytes());
  }

  pub fn write_inverted(&mut self, s: &str) {
    self.tty.write(ansi::inverse().as_slice());
    self.tty.write(s.as_bytes());
    self.tty.write(ansi::reset().as_slice());
  }

  // Return all buffered keystrokes, or the next key if buffer is empty.
  pub fn get_buffered_keys(&mut self) -> Vec<Key> {
    let mut ret = Vec::new();
    while let Ok(byte) = self.tty.input.try_recv() {
      ret.push(Terminal::translate_byte(byte));
    }
    if ret.is_empty() {
      let byte = self.tty.input.recv().unwrap();
      ret.push(Terminal::translate_byte(byte));
    }
    ret
  }
}

impl Drop for Screen {
  fn drop(&mut self) {
    self.restore_tty();
  }
}

pub enum Key {
  Char(char),
  Control(char),
  Enter,
  Backspace,
}

struct Terminal {
  input: Receiver<u8>,
  output: File,
}

impl Terminal {
  fn open_terminal() -> Terminal {
    let term_path = Path::new("/dev/tty");
    let mut input_file = File::open_mode(&term_path, Open, Read).unwrap();
    let output_file = File::open_mode(&term_path, Open, Write).unwrap();
    let (tx, rx): (Sender<u8>, Receiver<u8>) = mpsc::channel();
    Thread::spawn(move || {
      loop {
        tx.send(input_file.read_byte().unwrap()).unwrap();
      }
    });
    Terminal {
      input: rx,
      output: output_file
    }
  }

  fn initialize(&mut self) {
    self.stty(&["raw", "-echo", "cbreak"]);
  }

  fn stty(&mut self, args: &[&str]) -> Vec<u8> {
    let term_input = File::open_mode(&Path::new("/dev/tty"), Open, Read).unwrap();
    let fd = term_input.as_raw_fd();
    let mut process = match Command::new("stty").args(args).stdin(InheritFd(fd)).spawn() {
      Ok(p) => p,
      Err(e) => panic!("Command failed: {}", e),
    };

    process.stdout.as_mut().unwrap().read_to_end().unwrap()
  }

  fn getchar(&mut self) -> Key {
    let byte = self.input.recv().unwrap();
    Terminal::translate_byte(byte)
  }

  fn translate_byte(byte: u8) -> Key {
    if byte == '\r' as u8 {
      Enter
    } else if byte == 127 {
      Backspace
    } else if byte & 96 == 0 {
      Control((byte + 96u8) as char)
    } else {
      Char(byte as char)
    }
  }

  fn write(&mut self, s: &[u8]) {
    self.output.write(s.as_slice()).unwrap();
  }

  fn writeln(&mut self, s: &str) {
    self.output.write_line(s).unwrap();
  }

  fn winsize(&self) -> Option<(u16, u16)> {
    extern { fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int; }
    const TIOCGWINSZ: c_ulong = 0x40087468;

    #[repr(C)]
    struct TermSize {
      rows: c_ushort,
      cols: c_ushort,
      x: c_ushort,
      y: c_ushort,
    }

    let size = TermSize { rows: 0, cols: 0, x: 0, y: 0 };
    if unsafe { ioctl(self.output.as_raw_fd(), TIOCGWINSZ, &size) } == 0 {
      Some((size.cols as u16, size.rows as u16))
    } else {
      None
    }
  }
}
<commit_msg>Remove redundant type annotations<commit_after>#![allow(dead_code)]

use self::Key::*;
use std::io::{File, Open, Read, Write};
use libc::{c_ushort, c_int, c_ulong};
use std::os::unix::AsRawFd;
use std::io::process::{Command, InheritFd};
use std::iter::repeat;
use std::cmp::min;
use ansi;

use std::thread::Thread;
use std::sync::mpsc::Receiver;
use std::sync::mpsc;

pub struct Screen {
  tty: Terminal,
  original_stty_state: Vec<u8>,
  pub height: u16,
  pub width: u16,
  pub visible_choices: u16,
  pub start_line: u16,
}

impl Screen {
  pub fn open_screen() -> Screen {
    let mut tty = Terminal::open_terminal();
    let current_stty_state = tty.stty(&["-g"]);
    tty.initialize();
    let (cols, rows) = tty.winsize().unwrap();
    let visible_choices = min(20, rows - 1);
    let start_line = rows - visible_choices - 1;
    Screen {
      tty: tty,
      original_stty_state: current_stty_state,
      height: rows,
      width: cols,
      visible_choices: visible_choices,
      start_line: start_line,
    }
  }

  fn restore_tty(&mut self) {
    self.tty.stty(&[String::from_utf8(self.original_stty_state.clone()).unwrap().as_slice()]);
  }

  pub fn move_cursor(&mut self, line: u16, column: u16) {
    self.tty.write(ansi::setpos(line, column).as_slice());
  }

  pub fn move_cursor_to_bottom(&mut self) {
    let end_line = self.start_line + self.visible_choices;
    self.move_cursor(end_line, 0);
    self.write("\n");
  }

  pub fn blank_screen(&mut self) {
    let start_line = self.start_line;
    self.move_cursor(start_line, 0);
    let blank_line = repeat(' ').take(self.width as usize).collect::<String>();
    for _ in range(0, self.height) {
      self.tty.write(blank_line.as_bytes());
    }
    self.move_cursor(start_line, 0);
  }

  pub fn show_cursor(&mut self) {
    self.tty.write(ansi::show_cursor().as_slice());
  }

  pub fn hide_cursor(&mut self) {
    self.tty.write(ansi::hide_cursor().as_slice());
  }

  pub fn write(&mut self, s: &str) {
    self.tty.write(s.as_bytes());
  }

  pub fn write_inverted(&mut self, s: &str) {
    self.tty.write(ansi::inverse().as_slice());
    self.tty.write(s.as_bytes());
    self.tty.write(ansi::reset().as_slice());
  }

  // Return all buffered keystrokes, or the next key if buffer is empty.
  pub fn get_buffered_keys(&mut self) -> Vec<Key> {
    let mut ret = Vec::new();
    while let Ok(byte) = self.tty.input.try_recv() {
      ret.push(Terminal::translate_byte(byte));
    }
    if ret.is_empty() {
      let byte = self.tty.input.recv().unwrap();
      ret.push(Terminal::translate_byte(byte));
    }
    ret
  }
}

impl Drop for Screen {
  fn drop(&mut self) {
    self.restore_tty();
  }
}

pub enum Key {
  Char(char),
  Control(char),
  Enter,
  Backspace,
}

struct Terminal {
  input: Receiver<u8>,
  output: File,
}

impl Terminal {
  fn open_terminal() -> Terminal {
    let term_path = Path::new("/dev/tty");
    let mut input_file = File::open_mode(&term_path, Open, Read).unwrap();
    let output_file = File::open_mode(&term_path, Open, Write).unwrap();
    let (tx, rx) = mpsc::channel();
    Thread::spawn(move || {
      loop {
        tx.send(input_file.read_byte().unwrap()).unwrap();
      }
    });
    Terminal {
      input: rx,
      output: output_file
    }
  }

  fn initialize(&mut self) {
    self.stty(&["raw", "-echo", "cbreak"]);
  }

  fn stty(&mut self, args: &[&str]) -> Vec<u8> {
    let term_input = File::open_mode(&Path::new("/dev/tty"), Open, Read).unwrap();
    let fd = term_input.as_raw_fd();
    let mut process = match Command::new("stty").args(args).stdin(InheritFd(fd)).spawn() {
      Ok(p) => p,
      Err(e) => panic!("Command failed: {}", e),
    };

    process.stdout.as_mut().unwrap().read_to_end().unwrap()
  }

  fn getchar(&mut self) -> Key {
    let byte = self.input.recv().unwrap();
    Terminal::translate_byte(byte)
  }

  fn translate_byte(byte: u8) -> Key {
    if byte == '\r' as u8 {
      Enter
    } else if byte == 127 {
      Backspace
    } else if byte & 96 == 0 {
      Control((byte + 96u8) as char)
    } else {
      Char(byte as char)
    }
  }

  fn write(&mut self, s: &[u8]) {
    self.output.write(s.as_slice()).unwrap();
  }

  fn writeln(&mut self, s: &str) {
    self.output.write_line(s).unwrap();
  }

  fn winsize(&self) -> Option<(u16, u16)> {
    extern { fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int; }
    const TIOCGWINSZ: c_ulong = 0x40087468;

    #[repr(C)]
    struct TermSize {
      rows: c_ushort,
      cols: c_ushort,
      x: c_ushort,
      y: c_ushort,
    }

    let size = TermSize { rows: 0, cols: 0, x: 0, y: 0 };
    if unsafe { ioctl(self.output.as_raw_fd(), TIOCGWINSZ, &size) } == 0 {
      Some((size.cols as u16, size.rows as u16))
    } else {
      None
    }
  }
}
<|endoftext|>


<commit_before>//! Aggregates the weights of equal records into at most one record.
//!
//! As differential dataflow streams are unordered and taken to be the accumulation of all records,
//! no semantic change happens via `consolidate`. However, there is a practical difference between
//! a collection that aggregates down to zero records, and one that actually has no records. The
//! underlying system can more clearly see that no work must be done in the later case, and we can
//! drop out of, e.g. iterative computations.

use timely::dataflow::Scope;

use ::{Collection, Data, Diff, Hashable};
use operators::arrange::ArrangeBySelf;

/// An extension method for consolidating weighted streams.
pub trait Consolidate<D: Data+Hashable> {
    /// Aggregates the weights of equal records into at most one record.
    ///
    /// This method uses the type `D`'s `hashed()` method to partition the data. The data are
    /// accumulated in place, each held back until their timestamp has completed.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate timely;
    /// extern crate differential_dataflow;
    ///
    /// use differential_dataflow::input::Input;
    /// use differential_dataflow::operators::Consolidate;
    ///
    /// fn main() {
    ///     ::timely::example(|scope| {
    ///
    ///         let x = scope.new_collection_from(1 .. 10u32).1;
    ///
    ///         x.negate()
    ///          .concat(&x)
    ///          .consolidate() // <-- ensures cancellation occurs
    ///          .assert_empty();
    ///     });
    /// }
    /// ```
    fn consolidate(&self) -> Self;
}

impl<G: Scope, D, R> Consolidate<D> for Collection<G, D, R>
where
    D: Data+Hashable,
    R: Diff,
    G::Timestamp: ::lattice::Lattice+Ord,
 {
    fn consolidate(&self) -> Self {
       self.arrange_by_self().as_collection(|d,_| d.clone())
    }
}
<commit_msg>consolidate_stream<commit_after>//! Aggregates the weights of equal records into at most one record.
//!
//! As differential dataflow streams are unordered and taken to be the accumulation of all records,
//! no semantic change happens via `consolidate`. However, there is a practical difference between
//! a collection that aggregates down to zero records, and one that actually has no records. The
//! underlying system can more clearly see that no work must be done in the later case, and we can
//! drop out of, e.g. iterative computations.

use timely::dataflow::Scope;

use ::{Collection, Data, Diff, Hashable};
use operators::arrange::ArrangeBySelf;

/// An extension method for consolidating weighted streams.
pub trait Consolidate<D: Data+Hashable> {
    /// Aggregates the weights of equal records into at most one record.
    ///
    /// This method uses the type `D`'s `hashed()` method to partition the data. The data are
    /// accumulated in place, each held back until their timestamp has completed.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate timely;
    /// extern crate differential_dataflow;
    ///
    /// use differential_dataflow::input::Input;
    /// use differential_dataflow::operators::Consolidate;
    ///
    /// fn main() {
    ///     ::timely::example(|scope| {
    ///
    ///         let x = scope.new_collection_from(1 .. 10u32).1;
    ///
    ///         x.negate()
    ///          .concat(&x)
    ///          .consolidate() // <-- ensures cancellation occurs
    ///          .assert_empty();
    ///     });
    /// }
    /// ```
    fn consolidate(&self) -> Self;
}

impl<G: Scope, D, R> Consolidate<D> for Collection<G, D, R>
where
    D: Data+Hashable,
    R: Diff,
    G::Timestamp: ::lattice::Lattice+Ord,
 {
    fn consolidate(&self) -> Self {
        self.arrange_by_self().as_collection(|d,_| d.clone())
    }
}

/// An extension method for consolidating weighted streams.
pub trait ConsolidateStream<D: Data+Hashable> {
    /// Aggregates the weights of equal records.
    ///
    /// Unlike `consolidate`, this method does not exchange data and does not
    /// ensure that at most one copy of each `(data, time)` pair exists in the
    /// results. Instead, it acts on each batch of data and collapses equivalent
    /// `(data, time)` pairs found therein, suppressing any that accumulate to
    /// zero.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate timely;
    /// extern crate differential_dataflow;
    ///
    /// use differential_dataflow::input::Input;
    /// use differential_dataflow::operators::ConsolidateStream;
    ///
    /// fn main() {
    ///     ::timely::example(|scope| {
    ///
    ///         let x = scope.new_collection_from(1 .. 10u32).1;
    ///
    ///         // nothing to assert, as no particular guarantees.
    ///         x.negate()
    ///          .concat(&x)
    ///          .consolidate_stream();
    ///     });
    /// }
    /// ```
    fn consolidate_stream(&self) -> Self;
}

impl<G: Scope, D, R> ConsolidateStream<D> for Collection<G, D, R>
where
    D: Data+Hashable,
    R: Diff,
    G::Timestamp: ::lattice::Lattice+Ord,
 {
    fn consolidate_stream(&self) -> Self {

        use timely::dataflow::channels::pact::Pipeline;
        use timely::dataflow::operators::Operator;
        use collection::AsCollection;

        self.inner
            .unary(Pipeline, "ConsolidateStream", |_cap, _info| {

                let mut vector = Vec::new();
                move |input, output| {
                    input.for_each(|time, data| {
                        data.swap(&mut vector);
                        vector.sort_unstable_by(|x,y| (&x.0, &x.1).cmp(&(&y.0, &y.1)));
                        for index in 1 .. vector.len() {
                            if vector[index].0 == vector[index - 1].0 && vector[index].1 == vector[index - 1].1 {
                                vector[index].2 = vector[index].2 + vector[index - 1].2;
                                vector[index - 1].2 = R::zero();
                            }
                        }
                        vector.retain(|x| !x.2.is_zero());
                        output.session(&time).give_vec(&mut vector);
                    })
                }
            })
            .as_collection()
    }
}
<|endoftext|>


<commit_before>//
//  SOS: the Stupid Operating System
//  by Hawk Weisman (hi@hawkweisman.me)
//
//  Copyright (c) 2015 Hawk Weisman
//  Released under the terms of the MIT license. See `LICENSE` in the root
//  directory of this repository for more information.
//
//! Architecture-specific memory management.
use core::ptr::Unique;
use core::mem;

use ::memory::{VAddr, Addr};
use ::memory::paging::{Page, Mapper};

use alloc::{Allocator};

pub mod table;
pub mod entry;

use self::table::*;
use self::entry::Flags;

use core::ops;

pub const PAGE_SHIFT: u8 = 12;
/// The size of a page (4mb)
//  TODO: can we possibly rewrite this so that we can handle pages
//        in excess of 4 megs?
pub const PAGE_SIZE: u64 = 1 << PAGE_SHIFT; // 4096

extern {
    // TODO: It would be really nice if there was a less ugly way of doing
    // this... (read: after the Revolution when we add memory regions to the
    // heap programmatically.)
    #[link_name = "heap_base"]
    pub static mut HEAP_BASE: u8;
    #[link_name = "heap_top"]
    pub static mut HEAP_TOP: u8;
    // Of course, we will still need to export the kernel stack addresses like
    // this, but it would be nice if they could be, i dont know, not mut u8s
    // pointers, like God intended.
    #[link_name = "stack_base"]
    pub static mut STACK_BASE: u8;
    #[link_name = "stack_base"]
    pub static mut STACK_TOP: u8;
}

/// A frame (physical page)
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Frame { pub number: u64 }

impl ops::Add<u64> for Frame {
    type Output = Frame;

    #[inline]
    fn add(self, amount: u64) -> Frame {
        Frame { number: self.number + amount }
    }
}

impl ops::Add<usize> for Frame {
    type Output = Frame;

    #[inline]
    fn add(self, amount: usize) -> Frame {
        Frame { number: self.number + amount as u64 }
    }
}

impl Frame {

    /// Returns the physical address where this frame starts.
    #[inline]
    pub const fn base_addr(&self) -> PAddr {
        PAddr(self.number << PAGE_SHIFT)
    }

    /// Returns a new frame containing `addr`
    #[inline]
    pub const fn containing(addr: PAddr) -> Frame {
        Frame { number: addr.0 / PAGE_SIZE }
    }

    /// Convert the frame into a raw pointer to the frame's base address
    #[inline]
    pub unsafe fn as_ptr<T>(&self) -> *const T {
        mem::transmute(self.base_addr())
    }

    /// Convert the frame into a raw mutable pointer to the frame's base address
    #[inline]
    pub unsafe fn as_mut_ptr<T>(&self) -> *mut T {
        *self.base_addr() as *mut u8 as *mut T
    }

    /// Returns a `FrameRange`
    pub const fn range_between(start: Frame, end: Frame) -> FrameRange {
        FrameRange { start: start, end: end }
    }

    /// Returns a `FrameRange` on the frames from this frame until the end frame
    pub const fn range_until(&self, end: Frame) -> FrameRange {
        FrameRange { start: *self, end: end }
    }

}

/// A range of frames
pub struct FrameRange { start: Frame, end: Frame }

impl FrameRange {
    /// Returns an iterator over this `FrameRange`
    pub fn iter<'a>(&'a self) -> FrameRangeIter<'a> {
        FrameRangeIter { range: self, current: self.start.clone() }
    }
}

/// An iterator over a range of frames
pub struct FrameRangeIter<'a> { range: &'a FrameRange, current: Frame }

impl<'a> Iterator for FrameRangeIter<'a> {
    type Item = Frame;

    fn next(&mut self) -> Option<Frame> {
      let end = self.range.end.number;
      assert!(self.range.start.number <= end);
      if self.current.number < end {
          let frame = self.current.clone();
          self.current.number += 1;
          Some(frame)
      } else {
          None
      }
  }

}

/// A physical (linear) memory address is a 64-bit unsigned integer
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PAddr(u64);

impl Addr<u64> for PAddr { }

impl_addr! { PAddr, u64 }

/// Struct representing the currently active PML4 instance.
///
/// The `ActivePML4` is a `Unique` reference to a PML4-level page table. It's
/// unique because, well, there can only be one active PML4 at a given time.
///
///
pub struct ActivePML4(Unique<Table<PML4Level>>);

/// The active PML4 table is the single point of entry for page mapping.
impl Mapper for ActivePML4 {
    type Flags = entry::Flags;
    type Frame = Frame;

    fn translate(&self, vaddr: VAddr) -> Option<PAddr> {
        self.translate_page(Page::containing(vaddr))
            .map(|frame| {
                let offset = *vaddr % PAGE_SIZE as usize;
                PAddr::from(frame.number + offset as u64)
            })
    }

    fn translate_page(&self, page: Page) -> Option<Frame> {
        let pdpt = self.pml4().next_table(page.pml4_index());

        pdpt.and_then(|pdpt| pdpt.next_table(page.pdpt_index()))
            .and_then(|pd| pd.next_table(page.pd_index()))
            .and_then(|pt| pt[page.pt_index()].get_frame())
            .or_else( || {
                pdpt.and_then(|pdpt| {
                    let pdpt_entry = &pdpt[page.pdpt_index()];
                    pdpt_entry.do_huge(page.pd_index() + page.pt_index() )
                        .or_else(|| {
                            pdpt.next_table(page.pdpt_index())
                                .and_then(|pd| {
                                    let pd_entry = &pd[page.pd_index()];
                                    pd_entry.do_huge(page.pt_index())
                                })
                        })
                    })
                })
    }

    /// Modifies the page tables so that `page` maps to `frame`.
    ///
    /// # Arguments
    /// + `page`: the virtual `Page` to map
    /// + `frame`: the physical `Frame` that `Page` should map to.
    /// + `flags`: the page table entry flags.
    /// + `alloc`: a memory allocator
    fn map_to<A>( &mut self, page: Page, frame: Frame
                , flags: Flags, alloc: &mut A)
    where A: Allocator{

       // get the page table index of the page to map
       let idx = page.pt_index();

        // access or create all the lower-level page tables.
        let mut page_table
            // get the PML4
            = self.pml4_mut()
                  // get or create the PDPT table at the page's PML4 index
                  .create_next(page.pml4_index(), alloc)
                  // get or create the PD table at the page's PDPT index
                  .create_next(page.pdpt_index(), alloc)
                  // get or create the page table at the  page's PD table index
                  .create_next(idx, alloc);

        // check if the page at that index is not currently in use, as we
        // cannot map a page which is currently in use.
        assert!(page_table[idx].is_unused()
               , "Could not map frame {:?}, page table entry {} is already \
                  in use!", frame, idx);
        // set the page table entry at that index
        page_table[idx].set(frame, flags | entry::PRESENT);
    }

    fn identity_map<A>(&mut self, frame: Frame, flags: Flags, alloc: &mut A)
    where A: Allocator {
        self.map_to( Page::containing(VAddr::from(frame.base_addr().0 as usize))
                   , frame
                   , flags
                   , alloc )
    }

    fn map_to_any<A>(&mut self, page: Page, flags: Flags, alloc: &mut A)
    where A: Allocator {
        // TODO: this is Definitely Wrong; our malloc just gives us
        //       pointers instead of allocating as frames that we coerce to
        //       pointers. might want to rewrite that.
        let frame = unsafe {
            alloc.allocate(PAGE_SIZE as usize, PAGE_SIZE as usize)
            // also, "PAGE_SIZE, PAGE_SIZE" is Almost Certainly the wrong size
            // and alignment for the allocation request - I think i left it that
            // way because i couldn't figure it out at the time and am an idiot.
            //      -- eliza
                    .expect("Couldn't map page, out of frames!")
        };
        unimplemented!()
        //self.map_to(page, frame, flags, alloc);
    }

}

impl ActivePML4 {

    pub unsafe fn new() -> Self {
        ActivePML4(Unique::new(PML4))
    }

    fn pml4(&self) -> &Table<PML4Level> {
        unsafe { self.0.get() }
    }

    fn pml4_mut(&mut self) -> &mut Table<PML4Level> {
        unsafe { self.0.get_mut() }
    }

}
<commit_msg>[x86_64] add FrameAllocator trait to memory<commit_after>//
//  SOS: the Stupid Operating System
//  by Hawk Weisman (hi@hawkweisman.me)
//
//  Copyright (c) 2015 Hawk Weisman
//  Released under the terms of the MIT license. See `LICENSE` in the root
//  directory of this repository for more information.
//
//! Architecture-specific memory management.
use core::ptr::Unique;
use core::mem;

use ::memory::{VAddr, Addr};
use ::memory::paging::{Page, Mapper};

use alloc::{Allocator};

pub mod table;
pub mod entry;

use self::table::*;
use self::entry::Flags;

use core::ops;

pub const PAGE_SHIFT: u8 = 12;
/// The size of a page (4mb)
//  TODO: can we possibly rewrite this so that we can handle pages
//        in excess of 4 megs?
pub const PAGE_SIZE: u64 = 1 << PAGE_SHIFT; // 4096

extern {
    // TODO: It would be really nice if there was a less ugly way of doing
    // this... (read: after the Revolution when we add memory regions to the
    // heap programmatically.)
    #[link_name = "heap_base"]
    pub static mut HEAP_BASE: u8;
    #[link_name = "heap_top"]
    pub static mut HEAP_TOP: u8;
    // Of course, we will still need to export the kernel stack addresses like
    // this, but it would be nice if they could be, i dont know, not mut u8s
    // pointers, like God intended.
    #[link_name = "stack_base"]
    pub static mut STACK_BASE: u8;
    #[link_name = "stack_base"]
    pub static mut STACK_TOP: u8;
}

/// A physical (linear) memory address is a 64-bit unsigned integer
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PAddr(u64);

impl Addr<u64> for PAddr { }

impl_addr! { PAddr, u64 }

/// A frame (physical page)
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Frame { pub number: u64 }

impl ops::Add<u64> for Frame {
    type Output = Frame;

    #[inline]
    fn add(self, amount: u64) -> Frame {
        Frame { number: self.number + amount }
    }
}

impl ops::Add<usize> for Frame {
    type Output = Frame;

    #[inline]
    fn add(self, amount: usize) -> Frame {
        Frame { number: self.number + amount as u64 }
    }
}

impl Frame {

    /// Returns the physical address where this frame starts.
    #[inline]
    pub const fn base_addr(&self) -> PAddr {
        PAddr(self.number << PAGE_SHIFT)
    }

    /// Returns a new frame containing `addr`
    #[inline]
    pub const fn containing(addr: PAddr) -> Frame {
        Frame { number: addr.0 / PAGE_SIZE }
    }

    /// Convert the frame into a raw pointer to the frame's base address
    #[inline]
    pub unsafe fn as_ptr<T>(&self) -> *const T {
        mem::transmute(self.base_addr())
    }

    /// Convert the frame into a raw mutable pointer to the frame's base address
    #[inline]
    pub unsafe fn as_mut_ptr<T>(&self) -> *mut T {
        *self.base_addr() as *mut u8 as *mut T
    }

    /// Returns a `FrameRange`
    pub const fn range_between(start: Frame, end: Frame) -> FrameRange {
        FrameRange { start: start, end: end }
    }

    /// Returns a `FrameRange` on the frames from this frame until the end frame
    pub const fn range_until(&self, end: Frame) -> FrameRange {
        FrameRange { start: *self, end: end }
    }

}

/// A range of frames
pub struct FrameRange { start: Frame, end: Frame }

impl FrameRange {
    /// Returns an iterator over this `FrameRange`
    pub fn iter<'a>(&'a self) -> FrameRangeIter<'a> {
        FrameRangeIter { range: self, current: self.start.clone() }
    }
}

/// An iterator over a range of frames
pub struct FrameRangeIter<'a> { range: &'a FrameRange, current: Frame }

impl<'a> Iterator for FrameRangeIter<'a> {
    type Item = Frame;

    fn next(&mut self) -> Option<Frame> {
      let end = self.range.end.number;
      assert!(self.range.start.number <= end);
      if self.current.number < end {
          let frame = self.current.clone();
          self.current.number += 1;
          Some(frame)
      } else {
          None
      }
  }

}

/// Trait for a memory allocator which can allocate memory in terms of frames.
pub trait FrameAllocator {

    /// Allocate a new `Frame`
    //  TODO: do we want to be able to request a frame size?
    fn alloc_frame(&mut self) -> Option<Frame>;

    /// Deallocate a given `Frame`.
    fn dealloc_frame(&mut self, frame: Frame);
}

/// Struct representing the currently active PML4 instance.
///
/// The `ActivePML4` is a `Unique` reference to a PML4-level page table. It's
/// unique because, well, there can only be one active PML4 at a given time.
///
///
pub struct ActivePML4(Unique<Table<PML4Level>>);

/// The active PML4 table is the single point of entry for page mapping.
impl Mapper for ActivePML4 {
    type Flags = entry::Flags;
    type Frame = Frame;

    fn translate(&self, vaddr: VAddr) -> Option<PAddr> {
        self.translate_page(Page::containing(vaddr))
            .map(|frame| {
                let offset = *vaddr % PAGE_SIZE as usize;
                PAddr::from(frame.number + offset as u64)
            })
    }

    fn translate_page(&self, page: Page) -> Option<Frame> {
        let pdpt = self.pml4().next_table(page.pml4_index());

        pdpt.and_then(|pdpt| pdpt.next_table(page.pdpt_index()))
            .and_then(|pd| pd.next_table(page.pd_index()))
            .and_then(|pt| pt[page.pt_index()].get_frame())
            .or_else( || {
                pdpt.and_then(|pdpt| {
                    let pdpt_entry = &pdpt[page.pdpt_index()];
                    pdpt_entry.do_huge(page.pd_index() + page.pt_index() )
                        .or_else(|| {
                            pdpt.next_table(page.pdpt_index())
                                .and_then(|pd| {
                                    let pd_entry = &pd[page.pd_index()];
                                    pd_entry.do_huge(page.pt_index())
                                })
                        })
                    })
                })
    }

    /// Modifies the page tables so that `page` maps to `frame`.
    ///
    /// # Arguments
    /// + `page`: the virtual `Page` to map
    /// + `frame`: the physical `Frame` that `Page` should map to.
    /// + `flags`: the page table entry flags.
    /// + `alloc`: a memory allocator
    fn map_to<A>( &mut self, page: Page, frame: Frame
                , flags: Flags, alloc: &mut A)
    where A: Allocator{

       // get the page table index of the page to map
       let idx = page.pt_index();

        // access or create all the lower-level page tables.
        let mut page_table
            // get the PML4
            = self.pml4_mut()
                  // get or create the PDPT table at the page's PML4 index
                  .create_next(page.pml4_index(), alloc)
                  // get or create the PD table at the page's PDPT index
                  .create_next(page.pdpt_index(), alloc)
                  // get or create the page table at the  page's PD table index
                  .create_next(idx, alloc);

        // check if the page at that index is not currently in use, as we
        // cannot map a page which is currently in use.
        assert!(page_table[idx].is_unused()
               , "Could not map frame {:?}, page table entry {} is already \
                  in use!", frame, idx);
        // set the page table entry at that index
        page_table[idx].set(frame, flags | entry::PRESENT);
    }

    fn identity_map<A>(&mut self, frame: Frame, flags: Flags, alloc: &mut A)
    where A: Allocator {
        self.map_to( Page::containing(VAddr::from(frame.base_addr().0 as usize))
                   , frame
                   , flags
                   , alloc )
    }

    fn map_to_any<A>(&mut self, page: Page, flags: Flags, alloc: &mut A)
    where A: Allocator {
        // TODO: this is Definitely Wrong; our malloc just gives us
        //       pointers instead of allocating as frames that we coerce to
        //       pointers. might want to rewrite that.
        let frame = unsafe {
            alloc.allocate(PAGE_SIZE as usize, PAGE_SIZE as usize)
            // also, "PAGE_SIZE, PAGE_SIZE" is Almost Certainly the wrong size
            // and alignment for the allocation request - I think i left it that
            // way because i couldn't figure it out at the time and am an idiot.
            //      -- eliza
                    .expect("Couldn't map page, out of frames!")
        };
        unimplemented!()
        //self.map_to(page, frame, flags, alloc);
    }

}

impl ActivePML4 {

    pub unsafe fn new() -> Self {
        ActivePML4(Unique::new(PML4))
    }

    fn pml4(&self) -> &Table<PML4Level> {
        unsafe { self.0.get() }
    }

    fn pml4_mut(&mut self) -> &mut Table<PML4Level> {
        unsafe { self.0.get_mut() }
    }

}
<|endoftext|>


<commit_before>import driver.session;
import lib.llvm.llvm;
import middle.trans;
import std.Str;
import std.FS;

import lib.llvm.llvm.ModuleRef;
import lib.llvm.llvm.ValueRef;
import lib.llvm.mk_pass_manager;
import lib.llvm.mk_target_data;
import lib.llvm.mk_type_names;
import lib.llvm.False;

tag output_type {
    output_type_none;
    output_type_bitcode;
    output_type_assembly;
    output_type_object;
}

fn llvm_err(session.session sess, str msg) {
    sess.err(msg + ": " + Str.str_from_cstr(llvm.LLVMRustGetLastError()));
    fail;
}

fn link_intrinsics(session.session sess, ModuleRef llmod) {
    auto path = FS.connect(sess.get_opts().sysroot, "intrinsics.bc");
    auto membuf =
        llvm.LLVMRustCreateMemoryBufferWithContentsOfFile(Str.buf(path));
    if ((membuf as uint) == 0u) {
        llvm_err(sess, "installation problem: couldn't open intrinstics.bc");
        fail;
    }

    auto llintrinsicsmod = llvm.LLVMRustParseBitcode(membuf);
    if ((llintrinsicsmod as uint) == 0u) {
        llvm_err(sess, "installation problem: couldn't parse intrinstics.bc");
        fail;
    }

    if (llvm.LLVMLinkModules(llmod, llintrinsicsmod) == False) {
        llvm_err(sess, "couldn't link the module with the intrinsics");
        fail;
    }
}

mod Write {
    fn is_object_or_assembly(output_type ot) -> bool {
        if (ot == output_type_assembly) {
            ret true;
        }
        if (ot == output_type_object) {
            ret true;
        }
        ret false;
    }

    // Decides what to call an intermediate file, given the name of the output
    // and the extension to use.
    fn mk_intermediate_name(str output_path, str extension) -> str {
        auto dot_pos = Str.index(output_path, '.' as u8);
        auto stem;
        if (dot_pos < 0) {
            stem = output_path;
        } else {
            stem = Str.substr(output_path, 0u, dot_pos as uint);
        }
        ret stem + "." + extension;
    }

    fn run_passes(session.session sess, ModuleRef llmod, str output) {
        link_intrinsics(sess, llmod);

        auto pm = mk_pass_manager();
        auto opts = sess.get_opts();

        // TODO: run the linter here also, once there are llvm-c bindings for
        // it.

        // Generate a pre-optimization intermediate file if -save-temps was
        // specified.
        if (opts.save_temps) {
            alt (opts.output_type) {
                case (output_type_bitcode) {
                    if (opts.optimize) {
                        auto filename = mk_intermediate_name(output,
                                                             "no-opt.bc");
                        llvm.LLVMWriteBitcodeToFile(llmod,
                                                    Str.buf(filename));
                    }
                }
                case (_) {
                    auto filename = mk_intermediate_name(output, "bc");
                    llvm.LLVMWriteBitcodeToFile(llmod, Str.buf(filename));
                }
            }
        }

        // FIXME: This is mostly a copy of the bits of opt's -O2 that are
        // available in the C api.
        // FIXME2: We might want to add optimization levels like -O1, -O2,
        // -Os, etc
        // FIXME3: Should we expose and use the pass lists used by the opt
        // tool?
        if (opts.optimize) {
            auto fpm = mk_pass_manager();

            // createStandardFunctionPasses
            llvm.LLVMAddTypeBasedAliasAnalysisPass(fpm.llpm);
            llvm.LLVMAddBasicAliasAnalysisPass(fpm.llpm);
            llvm.LLVMAddCFGSimplificationPass(fpm.llpm);
            llvm.LLVMAddScalarReplAggregatesPass(fpm.llpm);
            llvm.LLVMAddEarlyCSEPass(fpm.llpm);

            llvm.LLVMRunPassManager(fpm.llpm, llmod);

            // createStandardModulePasses
            llvm.LLVMAddTypeBasedAliasAnalysisPass(pm.llpm);
            llvm.LLVMAddBasicAliasAnalysisPass(pm.llpm);
            llvm.LLVMAddGlobalOptimizerPass(pm.llpm);
            llvm.LLVMAddIPSCCPPass(pm.llpm);
            llvm.LLVMAddDeadArgEliminationPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddPruneEHPass(pm.llpm);
            llvm.LLVMAddFunctionInliningPass(pm.llpm);
            llvm.LLVMAddFunctionAttrsPass(pm.llpm);
            llvm.LLVMAddScalarReplAggregatesPassSSA(pm.llpm);
            llvm.LLVMAddEarlyCSEPass(pm.llpm);
            llvm.LLVMAddSimplifyLibCallsPass(pm.llpm);
            llvm.LLVMAddJumpThreadingPass(pm.llpm);
            llvm.LLVMAddCorrelatedValuePropagationPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddTailCallEliminationPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddReassociatePass(pm.llpm);
            llvm.LLVMAddLoopRotatePass(pm.llpm);
            llvm.LLVMAddLICMPass(pm.llpm);
            llvm.LLVMAddLoopUnswitchPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddIndVarSimplifyPass(pm.llpm);
            llvm.LLVMAddLoopIdiomPass(pm.llpm);
            llvm.LLVMAddLoopDeletionPass(pm.llpm);
            llvm.LLVMAddLoopUnrollPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddGVNPass(pm.llpm);
            llvm.LLVMAddMemCpyOptPass(pm.llpm);
            llvm.LLVMAddSCCPPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddJumpThreadingPass(pm.llpm);
            llvm.LLVMAddCorrelatedValuePropagationPass(pm.llpm);
            llvm.LLVMAddDeadStoreEliminationPass(pm.llpm);
            llvm.LLVMAddAggressiveDCEPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddStripDeadPrototypesPass(pm.llpm);
            llvm.LLVMAddDeadTypeEliminationPass(pm.llpm);
            llvm.LLVMAddConstantMergePass(pm.llpm);
        }

        if (opts.verify) {
            llvm.LLVMAddVerifierPass(pm.llpm);
        }

        // TODO: Write .s if -c was specified and -save-temps was on.
        if (is_object_or_assembly(opts.output_type)) {
            let int LLVMAssemblyFile = 0;
            let int LLVMObjectFile = 1;
            let int LLVMNullFile = 2;
            auto FileType;
            if (opts.output_type == output_type_object) {
                FileType = LLVMObjectFile;
            } else {
                FileType = LLVMAssemblyFile;
            }

            // Write optimized bitcode if --save-temps was on.
            if (opts.save_temps) {
                alt (opts.output_type) {
                    case (output_type_bitcode) { /* nothing to do */ }
                    case (_) {
                        auto filename = mk_intermediate_name(output,
                                                             "opt.bc");
                        llvm.LLVMRunPassManager(pm.llpm, llmod);
                        llvm.LLVMWriteBitcodeToFile(llmod,
                                                    Str.buf(filename));
                        pm = mk_pass_manager();
                    }
                }
            }

            llvm.LLVMRustWriteOutputFile(pm.llpm, llmod,
                                         Str.buf(x86.get_target_triple()),
                                         Str.buf(output),
                                         FileType);
            llvm.LLVMDisposeModule(llmod);
            ret;
        }

        llvm.LLVMRunPassManager(pm.llpm, llmod);

        llvm.LLVMWriteBitcodeToFile(llmod, Str.buf(output));
        llvm.LLVMDisposeModule(llmod);
    }
}

<commit_msg>rustc: Make llvm_err() conform to Postel's law a little better<commit_after>import driver.session;
import lib.llvm.llvm;
import middle.trans;
import std.Str;
import std.FS;

import lib.llvm.llvm.ModuleRef;
import lib.llvm.llvm.ValueRef;
import lib.llvm.mk_pass_manager;
import lib.llvm.mk_target_data;
import lib.llvm.mk_type_names;
import lib.llvm.False;

tag output_type {
    output_type_none;
    output_type_bitcode;
    output_type_assembly;
    output_type_object;
}

fn llvm_err(session.session sess, str msg) {
    auto buf = llvm.LLVMRustGetLastError();
    if ((buf as uint) == 0u) {
        sess.err(msg);
    } else {
        sess.err(msg + ": " + Str.str_from_cstr(buf));
    }
    fail;
}

fn link_intrinsics(session.session sess, ModuleRef llmod) {
    auto path = FS.connect(sess.get_opts().sysroot, "intrinsics.bc");
    auto membuf =
        llvm.LLVMRustCreateMemoryBufferWithContentsOfFile(Str.buf(path));
    if ((membuf as uint) == 0u) {
        llvm_err(sess, "installation problem: couldn't open intrinstics.bc");
        fail;
    }

    auto llintrinsicsmod = llvm.LLVMRustParseBitcode(membuf);
    if ((llintrinsicsmod as uint) == 0u) {
        llvm_err(sess, "installation problem: couldn't parse intrinstics.bc");
        fail;
    }

    if (llvm.LLVMLinkModules(llmod, llintrinsicsmod) == False) {
        llvm_err(sess, "couldn't link the module with the intrinsics");
        fail;
    }
}

mod Write {
    fn is_object_or_assembly(output_type ot) -> bool {
        if (ot == output_type_assembly) {
            ret true;
        }
        if (ot == output_type_object) {
            ret true;
        }
        ret false;
    }

    // Decides what to call an intermediate file, given the name of the output
    // and the extension to use.
    fn mk_intermediate_name(str output_path, str extension) -> str {
        auto dot_pos = Str.index(output_path, '.' as u8);
        auto stem;
        if (dot_pos < 0) {
            stem = output_path;
        } else {
            stem = Str.substr(output_path, 0u, dot_pos as uint);
        }
        ret stem + "." + extension;
    }

    fn run_passes(session.session sess, ModuleRef llmod, str output) {
        link_intrinsics(sess, llmod);

        auto pm = mk_pass_manager();
        auto opts = sess.get_opts();

        // TODO: run the linter here also, once there are llvm-c bindings for
        // it.

        // Generate a pre-optimization intermediate file if -save-temps was
        // specified.
        if (opts.save_temps) {
            alt (opts.output_type) {
                case (output_type_bitcode) {
                    if (opts.optimize) {
                        auto filename = mk_intermediate_name(output,
                                                             "no-opt.bc");
                        llvm.LLVMWriteBitcodeToFile(llmod,
                                                    Str.buf(filename));
                    }
                }
                case (_) {
                    auto filename = mk_intermediate_name(output, "bc");
                    llvm.LLVMWriteBitcodeToFile(llmod, Str.buf(filename));
                }
            }
        }

        // FIXME: This is mostly a copy of the bits of opt's -O2 that are
        // available in the C api.
        // FIXME2: We might want to add optimization levels like -O1, -O2,
        // -Os, etc
        // FIXME3: Should we expose and use the pass lists used by the opt
        // tool?
        if (opts.optimize) {
            auto fpm = mk_pass_manager();

            // createStandardFunctionPasses
            llvm.LLVMAddTypeBasedAliasAnalysisPass(fpm.llpm);
            llvm.LLVMAddBasicAliasAnalysisPass(fpm.llpm);
            llvm.LLVMAddCFGSimplificationPass(fpm.llpm);
            llvm.LLVMAddScalarReplAggregatesPass(fpm.llpm);
            llvm.LLVMAddEarlyCSEPass(fpm.llpm);

            llvm.LLVMRunPassManager(fpm.llpm, llmod);

            // createStandardModulePasses
            llvm.LLVMAddTypeBasedAliasAnalysisPass(pm.llpm);
            llvm.LLVMAddBasicAliasAnalysisPass(pm.llpm);
            llvm.LLVMAddGlobalOptimizerPass(pm.llpm);
            llvm.LLVMAddIPSCCPPass(pm.llpm);
            llvm.LLVMAddDeadArgEliminationPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddPruneEHPass(pm.llpm);
            llvm.LLVMAddFunctionInliningPass(pm.llpm);
            llvm.LLVMAddFunctionAttrsPass(pm.llpm);
            llvm.LLVMAddScalarReplAggregatesPassSSA(pm.llpm);
            llvm.LLVMAddEarlyCSEPass(pm.llpm);
            llvm.LLVMAddSimplifyLibCallsPass(pm.llpm);
            llvm.LLVMAddJumpThreadingPass(pm.llpm);
            llvm.LLVMAddCorrelatedValuePropagationPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddTailCallEliminationPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddReassociatePass(pm.llpm);
            llvm.LLVMAddLoopRotatePass(pm.llpm);
            llvm.LLVMAddLICMPass(pm.llpm);
            llvm.LLVMAddLoopUnswitchPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddIndVarSimplifyPass(pm.llpm);
            llvm.LLVMAddLoopIdiomPass(pm.llpm);
            llvm.LLVMAddLoopDeletionPass(pm.llpm);
            llvm.LLVMAddLoopUnrollPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddGVNPass(pm.llpm);
            llvm.LLVMAddMemCpyOptPass(pm.llpm);
            llvm.LLVMAddSCCPPass(pm.llpm);
            llvm.LLVMAddInstructionCombiningPass(pm.llpm);
            llvm.LLVMAddJumpThreadingPass(pm.llpm);
            llvm.LLVMAddCorrelatedValuePropagationPass(pm.llpm);
            llvm.LLVMAddDeadStoreEliminationPass(pm.llpm);
            llvm.LLVMAddAggressiveDCEPass(pm.llpm);
            llvm.LLVMAddCFGSimplificationPass(pm.llpm);
            llvm.LLVMAddStripDeadPrototypesPass(pm.llpm);
            llvm.LLVMAddDeadTypeEliminationPass(pm.llpm);
            llvm.LLVMAddConstantMergePass(pm.llpm);
        }

        if (opts.verify) {
            llvm.LLVMAddVerifierPass(pm.llpm);
        }

        // TODO: Write .s if -c was specified and -save-temps was on.
        if (is_object_or_assembly(opts.output_type)) {
            let int LLVMAssemblyFile = 0;
            let int LLVMObjectFile = 1;
            let int LLVMNullFile = 2;
            auto FileType;
            if (opts.output_type == output_type_object) {
                FileType = LLVMObjectFile;
            } else {
                FileType = LLVMAssemblyFile;
            }

            // Write optimized bitcode if --save-temps was on.
            if (opts.save_temps) {
                alt (opts.output_type) {
                    case (output_type_bitcode) { /* nothing to do */ }
                    case (_) {
                        auto filename = mk_intermediate_name(output,
                                                             "opt.bc");
                        llvm.LLVMRunPassManager(pm.llpm, llmod);
                        llvm.LLVMWriteBitcodeToFile(llmod,
                                                    Str.buf(filename));
                        pm = mk_pass_manager();
                    }
                }
            }

            llvm.LLVMRustWriteOutputFile(pm.llpm, llmod,
                                         Str.buf(x86.get_target_triple()),
                                         Str.buf(output),
                                         FileType);
            llvm.LLVMDisposeModule(llmod);
            ret;
        }

        llvm.LLVMRunPassManager(pm.llpm, llmod);

        llvm.LLVMWriteBitcodeToFile(llmod, Str.buf(output));
        llvm.LLVMDisposeModule(llmod);
    }
}

<|endoftext|>


<commit_before>//! Completion for lints
use ide_db::helpers::generated_lints::Lint;
use syntax::{ast, T};

use crate::{
    context::CompletionContext,
    item::{CompletionItem, CompletionItemKind, CompletionKind},
    Completions,
};

pub(super) fn complete_lint(
    acc: &mut Completions,
    ctx: &CompletionContext,
    derive_input: ast::TokenTree,
    lints_completions: &[Lint],
) {
    if let Some(existing_lints) = super::parse_comma_sep_paths(derive_input) {
        for &Lint { label, description } in lints_completions {
            let (qual, name) = {
                // FIXME: change `Lint`'s label to not store a path in it but split the prefix off instead?
                let mut parts = label.split("::");
                let ns_or_label = match parts.next() {
                    Some(it) => it,
                    None => continue,
                };
                let label = parts.next();
                match label {
                    Some(label) => (Some(ns_or_label), label),
                    None => (None, ns_or_label),
                }
            };
            let lint_already_annotated = existing_lints
                .iter()
                .filter_map(|path| {
                    let q = path.qualifier();
                    if q.as_ref().and_then(|it| it.qualifier()).is_some() {
                        return None;
                    }
                    Some((q.and_then(|it| it.as_single_name_ref()), path.segment()?.name_ref()?))
                })
                .any(|(q, name_ref)| {
                    let qualifier_matches = match (q, qual) {
                        (None, None) => true,
                        (None, Some(_)) => false,
                        (Some(_), None) => false,
                        (Some(q), Some(ns)) => q.text() == ns,
                    };
                    qualifier_matches && name_ref.text() == name
                });
            if lint_already_annotated {
                continue;
            }
            let insert = match qual {
                Some(qual) if !ctx.previous_token_is(T![:]) => format!("{}::{}", qual, name),
                _ => name.to_owned(),
            };
            let mut item =
                CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label);
            item.kind(CompletionItemKind::Attribute)
                .insert_text(insert)
                .documentation(hir::Documentation::new(description.to_owned()));
            item.add_to(acc)
        }
    }
}
<commit_msg>Skip non clippy completions when completing a clippy path<commit_after>//! Completion for lints
use ide_db::helpers::generated_lints::Lint;
use syntax::{ast, T};

use crate::{
    context::CompletionContext,
    item::{CompletionItem, CompletionItemKind, CompletionKind},
    Completions,
};

pub(super) fn complete_lint(
    acc: &mut Completions,
    ctx: &CompletionContext,
    derive_input: ast::TokenTree,
    lints_completions: &[Lint],
) {
    if let Some(existing_lints) = super::parse_comma_sep_paths(derive_input) {
        for &Lint { label, description } in lints_completions {
            let (qual, name) = {
                // FIXME: change `Lint`'s label to not store a path in it but split the prefix off instead?
                let mut parts = label.split("::");
                let ns_or_label = match parts.next() {
                    Some(it) => it,
                    None => continue,
                };
                let label = parts.next();
                match label {
                    Some(label) => (Some(ns_or_label), label),
                    None => (None, ns_or_label),
                }
            };
            let lint_already_annotated = existing_lints
                .iter()
                .filter_map(|path| {
                    let q = path.qualifier();
                    if q.as_ref().and_then(|it| it.qualifier()).is_some() {
                        return None;
                    }
                    Some((q.and_then(|it| it.as_single_name_ref()), path.segment()?.name_ref()?))
                })
                .any(|(q, name_ref)| {
                    let qualifier_matches = match (q, qual) {
                        (None, None) => true,
                        (None, Some(_)) => false,
                        (Some(_), None) => false,
                        (Some(q), Some(ns)) => q.text() == ns,
                    };
                    qualifier_matches && name_ref.text() == name
                });
            if lint_already_annotated {
                continue;
            }
            let insert = match (qual, ctx.previous_token_is(T![:])) {
                (Some(qual), false) => format!("{}::{}", qual, name),
                // user is completing a qualified path but this completion has no qualifier
                // so discard this completion
                // FIXME: This is currently very hacky and will propose odd completions if
                // we add more qualified (tool) completions other than clippy
                (None, true) => continue,
                _ => name.to_owned(),
            };
            let mut item =
                CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label);
            item.kind(CompletionItemKind::Attribute)
                .insert_text(insert)
                .documentation(hir::Documentation::new(description.to_owned()));
            item.add_to(acc)
        }
    }
}
<|endoftext|>


<commit_before>

fn main() {

    // v is owner of the vector object
    let v1 = vec![2, 4, 5];

    // this is not reference, but a move semantics
    let v2 = v1; // now on v1 is not allowed to use unless...

    // illegal
    // println!("{}", v1[0]);

    // now we pass v2 to take function
    // which is moved as well
    take(v2);

    // so this is illegal also
    // println!("{}", v2[0]);

    // there are copy types as well
    // implemented Copy traits
    let i1 = 1;

    // this is simply copied
    let i2 = i1;

    println!("i1 is {}", i1);

    // all primitives implement copy traits
}

fn take(v: Vec<i32>) {
    // does something here
}
<commit_msg>references and borrowing<commit_after>

fn main() {

    // v is owner of the vector object
    let v1 = vec![2, 4, 5];

    // this is not reference, but a move semantics
    let v2 = v1; // now on v1 is not allowed to use unless...

    // illegal
    // println!("{}", v1[0]);

    // now we pass v2 to take function
    // which is moved as well
    let v3 = take(v2);

    // so this is illegal also
    // as v3 is new owner here
    // println!("{}", v2[0]);

    // there are copy types as well
    // implemented Copy traits
    let i1 = 1;

    // this is simply copied
    let i2 = i1;

    println!("i1 is {}", i1);

    // all primitives implement copy traits

    // borrowing ... references
    let mut ans = take2(&v3);
    println!("first item of vector is {}", ans);

    {
        // y is a reference
        let y = &mut ans;

        // *y is needed to access value ... dereference
        *y += 1;
    }
    println!("ans added by one {}", ans);

    // rules
    // any borrow should last a scope no greater than that of owner
    // one or more references but exactly one &mut reference
}

/// using references
/// immutable bindings
/// we cannot change v inside take2
fn take2(v: &Vec<i32>) -> i32 {
    // v.push(5);
    v[0]
}

/// using mutable reference
fn take3(v: &mut Vec<i32>) -> i32 {
    // update new one and return old one
    v.push(5);
    v[v.len() - 1]
}

fn take(v: Vec<i32>) -> Vec<i32> {
    // does something here

    // pass ownership back
    v
}
<|endoftext|>


<commit_before>extern crate serde_json;
extern crate uuid;

use self::uuid::Uuid;
use errors::anoncreds::AnoncredsError;
use services::crypto::CryptoService;
use services::pool::PoolService;
use services::wallet::WalletService;
use std::rc::Rc;

pub enum ProverCommand {
    StoreClaimOffer(
        i32, // wallet handle
        String, // claim offer json
        Box<Fn(Result<(), AnoncredsError>) + Send>),
    GetClaimOffers(
        i32, // wallet handle
        String, // filter json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    CreateMasterSecret(
        i32, // wallet handle
        String, // master secret name
        Box<Fn(Result<(), AnoncredsError>) + Send>),
    CreateAndStoreClaimRequest(
        i32, // wallet handle
        String, // claim offer json
        String, // claim def json
        String, // master secret name
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    StoreClaim(
        i32, // wallet handle
        String, // claims json
        Box<Fn(Result<(), AnoncredsError>) + Send>),
    GetClaims(
        i32, // wallet handle
        String, // filter json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    GetClaimsForProofReq(
        i32, // wallet handle
        String, // proof request json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    CreateProof(
        i32, // wallet handle
        String, // proof request json
        String, // requested claims json
        String, // schemas json
        String, // claim defs json
        String, // revoc regs json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
}

pub struct ProverCommandExecutor {
    crypto_service: Rc<CryptoService>,
    pool_service: Rc<PoolService>,
    wallet_service: Rc<WalletService>
}

impl ProverCommandExecutor {
    pub fn new(crypto_service: Rc<CryptoService>,
               pool_service: Rc<PoolService>,
               wallet_service: Rc<WalletService>) -> ProverCommandExecutor {
        ProverCommandExecutor {
            crypto_service: crypto_service,
            pool_service: pool_service,
            wallet_service: wallet_service,
        }
    }

    pub fn execute(&self, command: ProverCommand) {
        match command {
            ProverCommand::StoreClaimOffer(wallet_handle, claim_offer_json, cb) => {
                info!(target: "prover_command_executor", "StoreClaimOffer command received");
                self.store_claim_offer(wallet_handle, &claim_offer_json, cb);
            },
            ProverCommand::GetClaimOffers(wallet_handle, filter_json, cb) => {
                info!(target: "prover_command_executor", "GetClaimOffers command received");
                self.get_claim_offers(wallet_handle, &filter_json, cb);
            },
            ProverCommand::CreateMasterSecret(wallet_handle, master_secret_name, cb) => {
                info!(target: "prover_command_executor", "CreateMasterSecret command received");
                self.create_master_secret(wallet_handle, &master_secret_name, cb);
            },
            ProverCommand::CreateAndStoreClaimRequest(wallet_handle, claim_offer_json,
                                                      claim_def_json, master_secret_name, cb) => {
                info!(target: "prover_command_executor", "CreateAndStoreClaimRequest command received");
                self.create_and_store_claim_request(wallet_handle, &claim_offer_json,
                                                    &claim_def_json, &master_secret_name, cb);
            },
            ProverCommand::StoreClaim(wallet_handle, claims_json, cb) => {
                info!(target: "prover_command_executor", "StoreClaim command received");
                self.store_claim(wallet_handle, &claims_json, cb);
            },
            ProverCommand::GetClaims(wallet_handle, filter_json, cb) => {
                info!(target: "prover_command_executor", "GetClaims command received");
                self.get_claims(wallet_handle, &filter_json, cb);
            },
            ProverCommand::GetClaimsForProofReq(wallet_handle, proof_req_json, cb) => {
                info!(target: "prover_command_executor", "GetClaimsForProofReq command received");
                self.get_claims_for_proof_req(wallet_handle, &proof_req_json, cb);
            },
            ProverCommand::CreateProof(wallet_handle, proof_req_json, requested_claims_json, schemas_jsons,
                                       claim_def_jsons, revoc_regs_jsons, cb) => {
                info!(target: "prover_command_executor", "CreateProof command received");
                self.create_proof(wallet_handle, &proof_req_json, &requested_claims_json, &schemas_jsons,
                                  &claim_def_jsons, &revoc_regs_jsons, cb);
            }
        };
    }

    fn store_claim_offer(&self,
                         wallet_handle: i32,
                         claim_offer_json: &str,
                         cb: Box<Fn(Result<(), AnoncredsError>) + Send>) {
        cb(self._store_claim_offer(wallet_handle, claim_offer_json));
    }

    fn _store_claim_offer(&self, wallet_handle: i32,  claim_offer_json: &str) -> Result<(), AnoncredsError> {
        let uuid = Uuid::new_v4().to_string();
        self.wallet_service.set(wallet_handle, &format!("claim_offer_json::{}", &uuid), &claim_offer_json)?;

        Ok(())
    }

    fn get_claim_offers(&self,
                        wallet_handle: i32,
                        filter_json: &str,
                        cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        unimplemented!();
//        let result =
//            serde_json::from_str(&filter_json)
//                .map_err(|err| AnoncredsError::CryptoError(CryptoError::InvalidStructure(err.to_string())))
//                .and_then(|filter: Value| {
//                    let claim_offers =
//                        self.wallet_service.get(wallet_handle, &format!("claim_offer {}", &filter["issuer_did"]))?; //TODO LIST METHOD
//
//                    Ok((claim_offers))
//                });
//
//        match result {
//            Ok(claim_offers) => cb(Ok(claim_offers)),
//            Err(err) => cb(Err(err))
//        }
    }

    fn create_master_secret(&self,
                            wallet_handle: i32,
                            master_secret_name: &str,
                            cb: Box<Fn(Result<(), AnoncredsError>) + Send>) {
        unimplemented!();
//        let result =
//            self.crypto_service.anoncreds.prover.generate_master_secret()
//                .map_err(|err| AnoncredsError::CryptoError(CryptoError::InvalidStructure(err.to_string())))
//                .and_then(|master_secret| {
//                    let master_secret_string = master_secret.to_dec()?;
//
//                    self.wallet_service.set(wallet_handle, &format!("master_secret {}", &master_secret_name), &master_secret_string)?;
//
//                    Ok(())
//                });
//
//        match result {
//            Ok(()) => cb(Ok(())),
//            Err(err) => cb(Err(err))
//        }
    }

    fn create_and_store_claim_request(&self,
                                      wallet_handle: i32,
                                      claim_offer_json: &str,
                                      claim_def_json: &str,
                                      master_secret_name: &str,
                                      cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        unimplemented!();
//        let result =
//            ClaimOffer::from_str(&claim_offer_json)
//                .map_err(|err| AnoncredsError::CryptoError(CryptoError::InvalidStructure(err.to_string())))
//                .and_then(|claim_offer| {
//                    let claim_def_json = ClaimDefinition::from_str(&claim_def_json)?;
//
//                    let pk_string = self.wallet_service.get(wallet_handle, &format!("public_key {}", &claim_offer.issuer_did))?;
//                    let pkr_string = self.wallet_service.get(wallet_handle, &format!("public_key_revocation {}", &claim_offer.issuer_did))?;
//                    let ms_string = self.wallet_service.get(wallet_handle,&format!("master_secret {}", master_secret_name))?;
//
//                    let pk = PublicKey::from_str(&pk_string)?;
//                    let pkr = RevocationPublicKey::from_str(&pkr_string)?;
//                    let ms = BigNumber::from_dec(&ms_string)?;
//
//                    let (claim_request, claim_init_data, revocation_claim_init_data) =
//                        self.crypto_service.anoncreds.prover.create_claim_request(pk, pkr, ms, "1".to_string(), true)?;
//
//                    let claim_request_json = ClaimRequest::to_string(&claim_request)?;
//                    let claim_init_data_json = ClaimRequest::to_string(&claim_request);
//                    let revocation_claim_init_data_json = ClaimRequest::to_string(&claim_request)?;
//
//                    Ok(claim_request_json)
//                });
//
//        match result {
//            Ok(claim_request_json) => cb(Ok(claim_request_json)),
//            Err(err) => cb(Err(err))
//        }
    }

    fn store_claim(&self,
                   wallet_handle: i32,
                   claims_json: &str,
                   cb: Box<Fn(Result<(), AnoncredsError>) + Send>) {
        cb(Ok(()));
    }

    fn get_claims(&self,
                  wallet_handle: i32,
                  filter_json: &str,
                  cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }

    fn get_claims_for_proof_req(&self,
                                wallet_handle: i32,
                                proof_req_json: &str,
                                cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }

    fn parse_proof_request(&self,
                           wallet_handle: i32,
                           proof_request_json: &str,
                           cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }

    fn create_proof(&self,
                    wallet_handle: i32,
                    proof_req_json: &str,
                    requested_claims_json: &str,
                    schemas_jsons: &str,
                    claim_def_jsons: &str,
                    revoc_regs_jsons: &str,
                    cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }
}<commit_msg>added implementation for CreateMasterSecret<commit_after>extern crate serde_json;
extern crate uuid;

use self::uuid::Uuid;
use errors::anoncreds::AnoncredsError;
use services::crypto::CryptoService;
use services::pool::PoolService;
use services::wallet::WalletService;
use std::rc::Rc;

pub enum ProverCommand {
    StoreClaimOffer(
        i32, // wallet handle
        String, // claim offer json
        Box<Fn(Result<(), AnoncredsError>) + Send>),
    GetClaimOffers(
        i32, // wallet handle
        String, // filter json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    CreateMasterSecret(
        i32, // wallet handle
        String, // master secret name
        Box<Fn(Result<(), AnoncredsError>) + Send>),
    CreateAndStoreClaimRequest(
        i32, // wallet handle
        String, // claim offer json
        String, // claim def json
        String, // master secret name
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    StoreClaim(
        i32, // wallet handle
        String, // claims json
        Box<Fn(Result<(), AnoncredsError>) + Send>),
    GetClaims(
        i32, // wallet handle
        String, // filter json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    GetClaimsForProofReq(
        i32, // wallet handle
        String, // proof request json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
    CreateProof(
        i32, // wallet handle
        String, // proof request json
        String, // requested claims json
        String, // schemas json
        String, // claim defs json
        String, // revoc regs json
        Box<Fn(Result<String, AnoncredsError>) + Send>),
}

pub struct ProverCommandExecutor {
    crypto_service: Rc<CryptoService>,
    pool_service: Rc<PoolService>,
    wallet_service: Rc<WalletService>
}

impl ProverCommandExecutor {
    pub fn new(crypto_service: Rc<CryptoService>,
               pool_service: Rc<PoolService>,
               wallet_service: Rc<WalletService>) -> ProverCommandExecutor {
        ProverCommandExecutor {
            crypto_service: crypto_service,
            pool_service: pool_service,
            wallet_service: wallet_service,
        }
    }

    pub fn execute(&self, command: ProverCommand) {
        match command {
            ProverCommand::StoreClaimOffer(wallet_handle, claim_offer_json, cb) => {
                info!(target: "prover_command_executor", "StoreClaimOffer command received");
                self.store_claim_offer(wallet_handle, &claim_offer_json, cb);
            },
            ProverCommand::GetClaimOffers(wallet_handle, filter_json, cb) => {
                info!(target: "prover_command_executor", "GetClaimOffers command received");
                self.get_claim_offers(wallet_handle, &filter_json, cb);
            },
            ProverCommand::CreateMasterSecret(wallet_handle, master_secret_name, cb) => {
                info!(target: "prover_command_executor", "CreateMasterSecret command received");
                self.create_master_secret(wallet_handle, &master_secret_name, cb);
            },
            ProverCommand::CreateAndStoreClaimRequest(wallet_handle, claim_offer_json,
                                                      claim_def_json, master_secret_name, cb) => {
                info!(target: "prover_command_executor", "CreateAndStoreClaimRequest command received");
                self.create_and_store_claim_request(wallet_handle, &claim_offer_json,
                                                    &claim_def_json, &master_secret_name, cb);
            },
            ProverCommand::StoreClaim(wallet_handle, claims_json, cb) => {
                info!(target: "prover_command_executor", "StoreClaim command received");
                self.store_claim(wallet_handle, &claims_json, cb);
            },
            ProverCommand::GetClaims(wallet_handle, filter_json, cb) => {
                info!(target: "prover_command_executor", "GetClaims command received");
                self.get_claims(wallet_handle, &filter_json, cb);
            },
            ProverCommand::GetClaimsForProofReq(wallet_handle, proof_req_json, cb) => {
                info!(target: "prover_command_executor", "GetClaimsForProofReq command received");
                self.get_claims_for_proof_req(wallet_handle, &proof_req_json, cb);
            },
            ProverCommand::CreateProof(wallet_handle, proof_req_json, requested_claims_json, schemas_jsons,
                                       claim_def_jsons, revoc_regs_jsons, cb) => {
                info!(target: "prover_command_executor", "CreateProof command received");
                self.create_proof(wallet_handle, &proof_req_json, &requested_claims_json, &schemas_jsons,
                                  &claim_def_jsons, &revoc_regs_jsons, cb);
            }
        };
    }

    fn store_claim_offer(&self,
                         wallet_handle: i32,
                         claim_offer_json: &str,
                         cb: Box<Fn(Result<(), AnoncredsError>) + Send>) {
        cb(self._store_claim_offer(wallet_handle, claim_offer_json));
    }

    fn _store_claim_offer(&self, wallet_handle: i32,  claim_offer_json: &str) -> Result<(), AnoncredsError> {
        let uuid = Uuid::new_v4().to_string();
        self.wallet_service.set(wallet_handle, &format!("claim_offer_json::{}", &uuid), &claim_offer_json)?;

        Ok(())
    }

    fn get_claim_offers(&self,
                        wallet_handle: i32,
                        filter_json: &str,
                        cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        unimplemented!();
//        let result =
//            serde_json::from_str(&filter_json)
//                .map_err(|err| AnoncredsError::CryptoError(CryptoError::InvalidStructure(err.to_string())))
//                .and_then(|filter: Value| {
//                    let claim_offers =
//                        self.wallet_service.get(wallet_handle, &format!("claim_offer {}", &filter["issuer_did"]))?; //TODO LIST METHOD
//
//                    Ok((claim_offers))
//                });
//
//        match result {
//            Ok(claim_offers) => cb(Ok(claim_offers)),
//            Err(err) => cb(Err(err))
//        }
    }

    fn create_master_secret(&self,
                            wallet_handle: i32,
                            master_secret_name: &str,
                            cb: Box<Fn(Result<(), AnoncredsError>) + Send>) {
        cb(self._create_master_secret(wallet_handle, master_secret_name))
    }

    fn _create_master_secret(&self, wallet_handle: i32, master_secret_name: &str) -> Result<(), AnoncredsError> {
        let master_secret = self.crypto_service.anoncreds.prover.generate_master_secret()?;
        self.wallet_service.set(wallet_handle, &format!("master_secret::{}", master_secret_name), &master_secret.to_dec()?)?;
        Ok(())
    }

    fn create_and_store_claim_request(&self,
                                      wallet_handle: i32,
                                      claim_offer_json: &str,
                                      claim_def_json: &str,
                                      master_secret_name: &str,
                                      cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        unimplemented!();
//        let result =
//            ClaimOffer::from_str(&claim_offer_json)
//                .map_err(|err| AnoncredsError::CryptoError(CryptoError::InvalidStructure(err.to_string())))
//                .and_then(|claim_offer| {
//                    let claim_def_json = ClaimDefinition::from_str(&claim_def_json)?;
//
//                    let pk_string = self.wallet_service.get(wallet_handle, &format!("public_key {}", &claim_offer.issuer_did))?;
//                    let pkr_string = self.wallet_service.get(wallet_handle, &format!("public_key_revocation {}", &claim_offer.issuer_did))?;
//                    let ms_string = self.wallet_service.get(wallet_handle,&format!("master_secret {}", master_secret_name))?;
//
//                    let pk = PublicKey::from_str(&pk_string)?;
//                    let pkr = RevocationPublicKey::from_str(&pkr_string)?;
//                    let ms = BigNumber::from_dec(&ms_string)?;
//
//                    let (claim_request, claim_init_data, revocation_claim_init_data) =
//                        self.crypto_service.anoncreds.prover.create_claim_request(pk, pkr, ms, "1".to_string(), true)?;
//
//                    let claim_request_json = ClaimRequest::to_string(&claim_request)?;
//                    let claim_init_data_json = ClaimRequest::to_string(&claim_request);
//                    let revocation_claim_init_data_json = ClaimRequest::to_string(&claim_request)?;
//
//                    Ok(claim_request_json)
//                });
//
//        match result {
//            Ok(claim_request_json) => cb(Ok(claim_request_json)),
//            Err(err) => cb(Err(err))
//        }
    }

    fn store_claim(&self,
                   wallet_handle: i32,
                   claims_json: &str,
                   cb: Box<Fn(Result<(), AnoncredsError>) + Send>) {
        cb(Ok(()));
    }

    fn get_claims(&self,
                  wallet_handle: i32,
                  filter_json: &str,
                  cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }

    fn get_claims_for_proof_req(&self,
                                wallet_handle: i32,
                                proof_req_json: &str,
                                cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }

    fn parse_proof_request(&self,
                           wallet_handle: i32,
                           proof_request_json: &str,
                           cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }

    fn create_proof(&self,
                    wallet_handle: i32,
                    proof_req_json: &str,
                    requested_claims_json: &str,
                    schemas_jsons: &str,
                    claim_def_jsons: &str,
                    revoc_regs_jsons: &str,
                    cb: Box<Fn(Result<String, AnoncredsError>) + Send>) {
        cb(Ok("".to_string()));
    }
}<|endoftext|>


<commit_before>/* 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 https://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

// SVG 1.1 (Second Edition)
// https://www.w3.org/TR/SVG/
<% data.new_style_struct("InheritedSVG", inherited=True, gecko_name="SVG") %>

// Section 10 - Text

${helpers.single_keyword(
    "text-anchor",
    "start middle end",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG/text.html#TextAnchorProperty",
)}

// Section 11 - Painting: Filling, Stroking and Marker Symbols
${helpers.single_keyword(
    "color-interpolation",
    "srgb auto linearrgb",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationProperty",
)}

${helpers.single_keyword(
    "color-interpolation-filters",
    "linearrgb auto srgb",
    products="gecko",
    gecko_constant_prefix="NS_STYLE_COLOR_INTERPOLATION",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty",
)}

${helpers.predefined_type(
    "fill",
    "SVGPaint",
    "crate::values::computed::SVGPaint::black()",
    products="gecko",
    animation_value_type="IntermediateSVGPaint",
    boxed=True,
    spec="https://www.w3.org/TR/SVG2/painting.html#SpecifyingFillPaint",
)}

${helpers.predefined_type(
    "fill-opacity",
    "SVGOpacity",
    "Default::default()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://www.w3.org/TR/SVG11/painting.html#FillOpacityProperty",
)}

${helpers.predefined_type(
    "fill-rule",
    "FillRule",
    "Default::default()",
    needs_context=False,
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#FillRuleProperty",
)}

${helpers.single_keyword(
    "shape-rendering",
    "auto optimizespeed crispedges geometricprecision",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#ShapeRenderingProperty",
)}

${helpers.predefined_type(
    "stroke",
    "SVGPaint",
    "Default::default()",
    products="gecko",
    animation_value_type="IntermediateSVGPaint",
    boxed=True,
    spec="https://www.w3.org/TR/SVG2/painting.html#SpecifyingStrokePaint",
)}

${helpers.predefined_type(
    "stroke-width",
    "SVGWidth",
    "computed::SVGWidth::one()",
    products="gecko",
    animation_value_type="crate::values::computed::SVGWidth",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeWidth",
)}

${helpers.single_keyword(
    "stroke-linecap",
    "butt round square",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeLinecapProperty",
)}

${helpers.single_keyword(
    "stroke-linejoin",
    "miter round bevel",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeLinejoinProperty",
)}

${helpers.predefined_type(
    "stroke-miterlimit",
    "GreaterThanOrEqualToOneNumber",
    "From::from(4.0)",
    products="gecko",
    animation_value_type="crate::values::computed::GreaterThanOrEqualToOneNumber",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeMiterlimitProperty",
)}

${helpers.predefined_type(
    "stroke-opacity",
    "SVGOpacity",
    "Default::default()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeOpacityProperty",
)}

${helpers.predefined_type(
    "stroke-dasharray",
    "SVGStrokeDashArray",
    "Default::default()",
    products="gecko",
    animation_value_type="crate::values::computed::SVGStrokeDashArray",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeDashing",
)}

${helpers.predefined_type(
    "stroke-dashoffset",
    "SVGLength",
    "computed::SVGLength::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeDashing",
)}

// Section 14 - Clipping, Masking and Compositing
${helpers.predefined_type(
    "clip-rule",
    "FillRule",
    "Default::default()",
    needs_context=False,
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/masking.html#ClipRuleProperty",
)}

${helpers.predefined_type(
    "marker-start",
    "url::UrlOrNone",
    "computed::url::UrlOrNone::none()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties",
)}

${helpers.predefined_type(
    "marker-mid",
    "url::UrlOrNone",
    "computed::url::UrlOrNone::none()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties",
)}

${helpers.predefined_type(
    "marker-end",
    "url::UrlOrNone",
    "computed::url::UrlOrNone::none()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties",
)}

${helpers.predefined_type(
    "paint-order",
    "SVGPaintOrder",
    "computed::SVGPaintOrder::normal()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#PaintOrder",
)}

${helpers.predefined_type(
    "-moz-context-properties",
    "MozContextProperties",
    initial_value=None,
    vector=True,
    need_index=True,
    animation_value_type="none",
    products="gecko",
    spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-context-properties)",
    allow_empty=True,
)}
<commit_msg>style: Change stroke-miterlimit restriction from GreaterThanOrEqualToOneNumber to NonNegativeNumber.<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 https://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

// SVG 1.1 (Second Edition)
// https://www.w3.org/TR/SVG/
<% data.new_style_struct("InheritedSVG", inherited=True, gecko_name="SVG") %>

// Section 10 - Text

${helpers.single_keyword(
    "text-anchor",
    "start middle end",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG/text.html#TextAnchorProperty",
)}

// Section 11 - Painting: Filling, Stroking and Marker Symbols
${helpers.single_keyword(
    "color-interpolation",
    "srgb auto linearrgb",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationProperty",
)}

${helpers.single_keyword(
    "color-interpolation-filters",
    "linearrgb auto srgb",
    products="gecko",
    gecko_constant_prefix="NS_STYLE_COLOR_INTERPOLATION",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty",
)}

${helpers.predefined_type(
    "fill",
    "SVGPaint",
    "crate::values::computed::SVGPaint::black()",
    products="gecko",
    animation_value_type="IntermediateSVGPaint",
    boxed=True,
    spec="https://www.w3.org/TR/SVG2/painting.html#SpecifyingFillPaint",
)}

${helpers.predefined_type(
    "fill-opacity",
    "SVGOpacity",
    "Default::default()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://www.w3.org/TR/SVG11/painting.html#FillOpacityProperty",
)}

${helpers.predefined_type(
    "fill-rule",
    "FillRule",
    "Default::default()",
    needs_context=False,
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#FillRuleProperty",
)}

${helpers.single_keyword(
    "shape-rendering",
    "auto optimizespeed crispedges geometricprecision",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#ShapeRenderingProperty",
)}

${helpers.predefined_type(
    "stroke",
    "SVGPaint",
    "Default::default()",
    products="gecko",
    animation_value_type="IntermediateSVGPaint",
    boxed=True,
    spec="https://www.w3.org/TR/SVG2/painting.html#SpecifyingStrokePaint",
)}

${helpers.predefined_type(
    "stroke-width",
    "SVGWidth",
    "computed::SVGWidth::one()",
    products="gecko",
    animation_value_type="crate::values::computed::SVGWidth",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeWidth",
)}

${helpers.single_keyword(
    "stroke-linecap",
    "butt round square",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeLinecapProperty",
)}

${helpers.single_keyword(
    "stroke-linejoin",
    "miter round bevel",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeLinejoinProperty",
)}

${helpers.predefined_type(
    "stroke-miterlimit",
    "NonNegativeNumber",
    "From::from(4.0)",
    products="gecko",
    animation_value_type="crate::values::computed::NonNegativeNumber",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeMiterlimitProperty",
)}

${helpers.predefined_type(
    "stroke-opacity",
    "SVGOpacity",
    "Default::default()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://www.w3.org/TR/SVG11/painting.html#StrokeOpacityProperty",
)}

${helpers.predefined_type(
    "stroke-dasharray",
    "SVGStrokeDashArray",
    "Default::default()",
    products="gecko",
    animation_value_type="crate::values::computed::SVGStrokeDashArray",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeDashing",
)}

${helpers.predefined_type(
    "stroke-dashoffset",
    "SVGLength",
    "computed::SVGLength::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://www.w3.org/TR/SVG2/painting.html#StrokeDashing",
)}

// Section 14 - Clipping, Masking and Compositing
${helpers.predefined_type(
    "clip-rule",
    "FillRule",
    "Default::default()",
    needs_context=False,
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/masking.html#ClipRuleProperty",
)}

${helpers.predefined_type(
    "marker-start",
    "url::UrlOrNone",
    "computed::url::UrlOrNone::none()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties",
)}

${helpers.predefined_type(
    "marker-mid",
    "url::UrlOrNone",
    "computed::url::UrlOrNone::none()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties",
)}

${helpers.predefined_type(
    "marker-end",
    "url::UrlOrNone",
    "computed::url::UrlOrNone::none()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties",
)}

${helpers.predefined_type(
    "paint-order",
    "SVGPaintOrder",
    "computed::SVGPaintOrder::normal()",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG2/painting.html#PaintOrder",
)}

${helpers.predefined_type(
    "-moz-context-properties",
    "MozContextProperties",
    initial_value=None,
    vector=True,
    need_index=True,
    animation_value_type="none",
    products="gecko",
    spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-context-properties)",
    allow_empty=True,
)}
<|endoftext|>