file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
failure.rs
// 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. //! Failure support for libcore //! //! The core library cannot define failure, but it does *declare* failure. This //! means that the functions inside of libcore are allowed to fail, but to be //! useful an upstream crate must define failure for libcore to use. The current //! interface for failure is: //! //! ```ignore //! fn begin_unwind(fmt: &fmt::Arguments, &(&'static str, uint)) ->!; //! ``` //! //! This definition allows for failing with any general message, but it does not //! allow for failing with a `~Any` value. The reason for this is that libcore //! is not allowed to allocate. //! //! This module contains a few other failure functions, but these are just the //! necessary lang items for the compiler. All failure is funneled through this //! one function. Currently, the actual symbol is declared in the standard //! library, but the location of this may change over time. #![allow(dead_code, missing_doc)] use fmt; use intrinsics; #[cold] #[inline(never)] // this is the slow path, always #[lang="fail_"] fn fail_(expr_file_line: &(&'static str, &'static str, uint)) ->! { let (expr, file, line) = *expr_file_line; let ref file_line = (file, line); format_args!(|args| -> () { begin_unwind(args, file_line); }, "{}", expr); unsafe { intrinsics::abort() } } #[cold] #[inline(never)] #[lang="fail_bounds_check"] fn fail_bounds_check(file_line: &(&'static str, uint), index: uint, len: uint) ->! { format_args!(|args| -> () { begin_unwind(args, file_line); }, "index out of bounds: the len is {} but the index is {}", len, index); unsafe { intrinsics::abort() } } #[cold] #[inline(never)] pub fn begin_unwind(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) ->!
{ #[allow(ctypes)] extern { #[lang = "begin_unwind"] fn begin_unwind(fmt: &fmt::Arguments, file: &'static str, line: uint) -> !; } let (file, line) = *file_line; unsafe { begin_unwind(fmt, file, line) } }
identifier_body
vm.rs
//! Regular expression virtual machine. use std; use std::mem::swap; use collections::TrieSet; /// A single instruction in the program. pub enum Inst { /// Jump to all locations in the list simultaneously. This /// corresponds to `jmp` and `split` in the original paper. Jump(~[uint]), /// Match any code point in the range, inclusive. Range(char, char), /// Save the current position in the specified register. Save(uint) } struct Thread { pc: uint, registers: ~[Option<u64>] } impl Thread { fn new(pc: uint) -> Thread { Thread { pc: pc, registers: ~[] } } fn with_pc(&self, pc: uint) -> Thread { Thread { pc: pc, registers: self.registers.clone() } } fn with_reg(&self, reg: uint, data: Option<u64>) -> Thread { let mut registers = self.registers.clone(); registers.grow_set(reg, &None, data); Thread { pc: 1 + self.pc, registers: registers } } } struct ThreadList { threads: ~[Thread], indices: TrieSet } impl ThreadList { /// Create a new, empty, `ThreadList`. fn new() -> ThreadList { ThreadList { threads: ~[], indices: TrieSet::new() } } /// Clear all threads from the list. fn clear(&mut self) { self.threads.clear(); self.indices.clear(); } /// Add a thread to the list, if one with the same `pc` is not /// already present. fn add(&mut self, t: Thread) { if self.indices.insert(t.pc) { self.threads.push(t); } } /// Iterate over the list of threads. fn iter<'a>(&'a self) -> std::vec::Items<'a, Thread> { self.threads.iter() } } /// A regular expression virtual machine, loosely based on the Pike VM. pub struct VM<'a> { priv states: &'a [Inst], priv index: Option<u64>, priv threads: ThreadList, priv next: ThreadList, priv matched: bool } impl<'a> VM<'a> { pub fn new(states: &'a [Inst]) -> VM<'a> { let mut vm = VM { states: states, index: None, threads: ThreadList::new(), next: ThreadList::new(), matched: false }; // Add the initial thread vm.matched = follow(Thread::new(0), vm.index, vm.states, &mut vm.threads); vm } /// Feed a character into the automaton. pub fn feed(&mut self, c: char) {
match self.states[t.pc] { Range(lo, hi) => if lo <= c && c <= hi { if follow(t.with_pc(1 + t.pc), self.index, self.states, &mut self.next) { self.matched = true; // Cut off lower priority threads break } }, Jump(..) | Save(..) => unreachable!() } } // Swap the thread buffers swap(&mut self.threads, &mut self.next); self.next.clear(); } /// Determine if we have a match, given the existing input. pub fn is_match(&self) -> bool { self.matched } } /// Add all targets of the given thread to the thread list. /// Returns `true` if a matching state is reached; otherwise `false`. fn follow(t: Thread, index: Option<u64>, states: &[Inst], threads: &mut ThreadList) -> bool { if t.pc == states.len() { true } else { match states[t.pc] { Jump(ref exits) => { let mut matched = false; for &exit in exits.iter() { matched |= follow(t.with_pc(exit), index, states, threads); } matched }, Save(reg) => follow(t.with_reg(reg, index), index, states, threads), Range(..) => { threads.add(t); false } } } }
self.index.mutate_or_set(0, |i| 1 + i); self.matched = false; // Run through all the threads for t in self.threads.iter() {
random_line_split
vm.rs
//! Regular expression virtual machine. use std; use std::mem::swap; use collections::TrieSet; /// A single instruction in the program. pub enum Inst { /// Jump to all locations in the list simultaneously. This /// corresponds to `jmp` and `split` in the original paper. Jump(~[uint]), /// Match any code point in the range, inclusive. Range(char, char), /// Save the current position in the specified register. Save(uint) } struct Thread { pc: uint, registers: ~[Option<u64>] } impl Thread { fn new(pc: uint) -> Thread { Thread { pc: pc, registers: ~[] } } fn with_pc(&self, pc: uint) -> Thread { Thread { pc: pc, registers: self.registers.clone() } } fn with_reg(&self, reg: uint, data: Option<u64>) -> Thread { let mut registers = self.registers.clone(); registers.grow_set(reg, &None, data); Thread { pc: 1 + self.pc, registers: registers } } } struct ThreadList { threads: ~[Thread], indices: TrieSet } impl ThreadList { /// Create a new, empty, `ThreadList`. fn new() -> ThreadList { ThreadList { threads: ~[], indices: TrieSet::new() } } /// Clear all threads from the list. fn clear(&mut self) { self.threads.clear(); self.indices.clear(); } /// Add a thread to the list, if one with the same `pc` is not /// already present. fn add(&mut self, t: Thread) { if self.indices.insert(t.pc) { self.threads.push(t); } } /// Iterate over the list of threads. fn iter<'a>(&'a self) -> std::vec::Items<'a, Thread> { self.threads.iter() } } /// A regular expression virtual machine, loosely based on the Pike VM. pub struct VM<'a> { priv states: &'a [Inst], priv index: Option<u64>, priv threads: ThreadList, priv next: ThreadList, priv matched: bool } impl<'a> VM<'a> { pub fn new(states: &'a [Inst]) -> VM<'a> { let mut vm = VM { states: states, index: None, threads: ThreadList::new(), next: ThreadList::new(), matched: false }; // Add the initial thread vm.matched = follow(Thread::new(0), vm.index, vm.states, &mut vm.threads); vm } /// Feed a character into the automaton. pub fn feed(&mut self, c: char) { self.index.mutate_or_set(0, |i| 1 + i); self.matched = false; // Run through all the threads for t in self.threads.iter() { match self.states[t.pc] { Range(lo, hi) => if lo <= c && c <= hi { if follow(t.with_pc(1 + t.pc), self.index, self.states, &mut self.next)
}, Jump(..) | Save(..) => unreachable!() } } // Swap the thread buffers swap(&mut self.threads, &mut self.next); self.next.clear(); } /// Determine if we have a match, given the existing input. pub fn is_match(&self) -> bool { self.matched } } /// Add all targets of the given thread to the thread list. /// Returns `true` if a matching state is reached; otherwise `false`. fn follow(t: Thread, index: Option<u64>, states: &[Inst], threads: &mut ThreadList) -> bool { if t.pc == states.len() { true } else { match states[t.pc] { Jump(ref exits) => { let mut matched = false; for &exit in exits.iter() { matched |= follow(t.with_pc(exit), index, states, threads); } matched }, Save(reg) => follow(t.with_reg(reg, index), index, states, threads), Range(..) => { threads.add(t); false } } } }
{ self.matched = true; // Cut off lower priority threads break }
conditional_block
vm.rs
//! Regular expression virtual machine. use std; use std::mem::swap; use collections::TrieSet; /// A single instruction in the program. pub enum Inst { /// Jump to all locations in the list simultaneously. This /// corresponds to `jmp` and `split` in the original paper. Jump(~[uint]), /// Match any code point in the range, inclusive. Range(char, char), /// Save the current position in the specified register. Save(uint) } struct Thread { pc: uint, registers: ~[Option<u64>] } impl Thread { fn new(pc: uint) -> Thread { Thread { pc: pc, registers: ~[] } } fn with_pc(&self, pc: uint) -> Thread { Thread { pc: pc, registers: self.registers.clone() } } fn with_reg(&self, reg: uint, data: Option<u64>) -> Thread { let mut registers = self.registers.clone(); registers.grow_set(reg, &None, data); Thread { pc: 1 + self.pc, registers: registers } } } struct ThreadList { threads: ~[Thread], indices: TrieSet } impl ThreadList { /// Create a new, empty, `ThreadList`. fn new() -> ThreadList { ThreadList { threads: ~[], indices: TrieSet::new() } } /// Clear all threads from the list. fn clear(&mut self)
/// Add a thread to the list, if one with the same `pc` is not /// already present. fn add(&mut self, t: Thread) { if self.indices.insert(t.pc) { self.threads.push(t); } } /// Iterate over the list of threads. fn iter<'a>(&'a self) -> std::vec::Items<'a, Thread> { self.threads.iter() } } /// A regular expression virtual machine, loosely based on the Pike VM. pub struct VM<'a> { priv states: &'a [Inst], priv index: Option<u64>, priv threads: ThreadList, priv next: ThreadList, priv matched: bool } impl<'a> VM<'a> { pub fn new(states: &'a [Inst]) -> VM<'a> { let mut vm = VM { states: states, index: None, threads: ThreadList::new(), next: ThreadList::new(), matched: false }; // Add the initial thread vm.matched = follow(Thread::new(0), vm.index, vm.states, &mut vm.threads); vm } /// Feed a character into the automaton. pub fn feed(&mut self, c: char) { self.index.mutate_or_set(0, |i| 1 + i); self.matched = false; // Run through all the threads for t in self.threads.iter() { match self.states[t.pc] { Range(lo, hi) => if lo <= c && c <= hi { if follow(t.with_pc(1 + t.pc), self.index, self.states, &mut self.next) { self.matched = true; // Cut off lower priority threads break } }, Jump(..) | Save(..) => unreachable!() } } // Swap the thread buffers swap(&mut self.threads, &mut self.next); self.next.clear(); } /// Determine if we have a match, given the existing input. pub fn is_match(&self) -> bool { self.matched } } /// Add all targets of the given thread to the thread list. /// Returns `true` if a matching state is reached; otherwise `false`. fn follow(t: Thread, index: Option<u64>, states: &[Inst], threads: &mut ThreadList) -> bool { if t.pc == states.len() { true } else { match states[t.pc] { Jump(ref exits) => { let mut matched = false; for &exit in exits.iter() { matched |= follow(t.with_pc(exit), index, states, threads); } matched }, Save(reg) => follow(t.with_reg(reg, index), index, states, threads), Range(..) => { threads.add(t); false } } } }
{ self.threads.clear(); self.indices.clear(); }
identifier_body
vm.rs
//! Regular expression virtual machine. use std; use std::mem::swap; use collections::TrieSet; /// A single instruction in the program. pub enum Inst { /// Jump to all locations in the list simultaneously. This /// corresponds to `jmp` and `split` in the original paper. Jump(~[uint]), /// Match any code point in the range, inclusive. Range(char, char), /// Save the current position in the specified register. Save(uint) } struct Thread { pc: uint, registers: ~[Option<u64>] } impl Thread { fn new(pc: uint) -> Thread { Thread { pc: pc, registers: ~[] } } fn with_pc(&self, pc: uint) -> Thread { Thread { pc: pc, registers: self.registers.clone() } } fn with_reg(&self, reg: uint, data: Option<u64>) -> Thread { let mut registers = self.registers.clone(); registers.grow_set(reg, &None, data); Thread { pc: 1 + self.pc, registers: registers } } } struct ThreadList { threads: ~[Thread], indices: TrieSet } impl ThreadList { /// Create a new, empty, `ThreadList`. fn new() -> ThreadList { ThreadList { threads: ~[], indices: TrieSet::new() } } /// Clear all threads from the list. fn clear(&mut self) { self.threads.clear(); self.indices.clear(); } /// Add a thread to the list, if one with the same `pc` is not /// already present. fn add(&mut self, t: Thread) { if self.indices.insert(t.pc) { self.threads.push(t); } } /// Iterate over the list of threads. fn iter<'a>(&'a self) -> std::vec::Items<'a, Thread> { self.threads.iter() } } /// A regular expression virtual machine, loosely based on the Pike VM. pub struct VM<'a> { priv states: &'a [Inst], priv index: Option<u64>, priv threads: ThreadList, priv next: ThreadList, priv matched: bool } impl<'a> VM<'a> { pub fn new(states: &'a [Inst]) -> VM<'a> { let mut vm = VM { states: states, index: None, threads: ThreadList::new(), next: ThreadList::new(), matched: false }; // Add the initial thread vm.matched = follow(Thread::new(0), vm.index, vm.states, &mut vm.threads); vm } /// Feed a character into the automaton. pub fn feed(&mut self, c: char) { self.index.mutate_or_set(0, |i| 1 + i); self.matched = false; // Run through all the threads for t in self.threads.iter() { match self.states[t.pc] { Range(lo, hi) => if lo <= c && c <= hi { if follow(t.with_pc(1 + t.pc), self.index, self.states, &mut self.next) { self.matched = true; // Cut off lower priority threads break } }, Jump(..) | Save(..) => unreachable!() } } // Swap the thread buffers swap(&mut self.threads, &mut self.next); self.next.clear(); } /// Determine if we have a match, given the existing input. pub fn is_match(&self) -> bool { self.matched } } /// Add all targets of the given thread to the thread list. /// Returns `true` if a matching state is reached; otherwise `false`. fn
(t: Thread, index: Option<u64>, states: &[Inst], threads: &mut ThreadList) -> bool { if t.pc == states.len() { true } else { match states[t.pc] { Jump(ref exits) => { let mut matched = false; for &exit in exits.iter() { matched |= follow(t.with_pc(exit), index, states, threads); } matched }, Save(reg) => follow(t.with_reg(reg, index), index, states, threads), Range(..) => { threads.add(t); false } } } }
follow
identifier_name
user32.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> #![feature(test)] #![cfg(windows)] extern crate user32; extern crate test; use user32::*; use test::black_box as bb; #[cfg(target_arch = "x86_64")] #[test] fn functions_x64() { bb(GetClassLongPtrA); bb(GetClassLongPtrW); bb(GetWindowLongPtrA); bb(GetWindowLongPtrW); bb(SetClassLongPtrA); bb(SetClassLongPtrW); bb(SetWindowLongPtrA); bb(SetWindowLongPtrW); } #[test] fn functions() {
bb(ClipCursor); bb(CloseClipboard); bb(CloseDesktop); bb(CloseWindow); bb(CloseWindowStation); bb(CountClipboardFormats); bb(CreateCaret); bb(CreateCursor); bb(CreateWindowExW); bb(DefWindowProcW); bb(DeferWindowPos); bb(DeleteMenu); bb(DeregisterShellHookWindow); bb(DestroyAcceleratorTable); bb(DestroyCaret); bb(DestroyCursor); bb(DestroyIcon); bb(DestroyMenu); bb(DestroyWindow); bb(DispatchMessageW); bb(EmptyClipboard); bb(EnableScrollBar); bb(EnableWindow); bb(EndPaint); bb(EndTask); bb(EnumClipboardFormats); bb(EnumDisplayDevicesW); bb(EnumDisplaySettingsExW); bb(EnumThreadWindows); bb(EnumWindows); bb(FillRect); bb(FindWindowA ); bb(FindWindowExA); bb(FindWindowExW); bb(FindWindowW); bb(GetActiveWindow); bb(GetAncestor); bb(GetAsyncKeyState); bb(GetCaretBlinkTime); bb(GetCaretPos); bb(GetClassInfoExW); bb(GetClassInfoW); bb(GetClassLongA); bb(GetClassLongW); bb(GetClassWord); bb(GetClientRect); bb(GetClipCursor); bb(GetClipboardData); bb(GetClipboardFormatNameA); bb(GetClipboardFormatNameW); bb(GetClipboardOwner); bb(GetClipboardSequenceNumber); bb(GetClipboardViewer); bb(GetCursor); bb(GetCursorPos); bb(GetDC); bb(GetDesktopWindow); bb(GetFocus); bb(GetForegroundWindow); bb(GetKBCodePage); bb(GetKeyNameTextA); bb(GetKeyNameTextW); bb(GetKeyState); bb(GetKeyboardLayout); bb(GetKeyboardLayoutList); bb(GetKeyboardLayoutNameA); bb(GetKeyboardLayoutNameW); bb(GetKeyboardState); bb(GetKeyboardType); bb(GetMessageW); bb(GetOpenClipboardWindow); bb(GetParent); // bb(GetPhysicalCursorPos); bb(GetScrollPos); bb(GetScrollRange); bb(GetShellWindow); bb(GetSysColor); bb(GetSystemMetrics); bb(GetThreadDesktop); // bb(GetUpdatedClipboardFormats); bb(GetWindow); bb(GetWindowLongA); bb(GetWindowLongW); bb(GetWindowPlacement); bb(GetWindowRect); bb(GetWindowTextA); bb(GetWindowTextLengthA); bb(GetWindowTextLengthW); bb(GetWindowTextW); bb(HideCaret); bb(InvalidateRect); bb(IsClipboardFormatAvailable); bb(IsIconic); bb(IsWindow); bb(IsWindowEnabled); bb(IsWindowVisible); bb(LoadCursorFromFileW); bb(LoadCursorW); bb(LoadImageA); bb(LoadImageW); bb(MessageBoxA); bb(MessageBoxExA); bb(MessageBoxExW); bb(MessageBoxW); bb(OpenClipboard); bb(PeekMessageW); bb(PostMessageW); bb(PostQuitMessage); bb(RegisterClassExW); bb(RegisterClipboardFormatA); bb(RegisterClipboardFormatW); bb(ReleaseDC); bb(ScrollDC); bb(ScrollWindow); bb(ScrollWindowEx); bb(SendInput); bb(SendMessageA); bb(SendMessageTimeoutA); bb(SendMessageTimeoutW); bb(SendMessageW); bb(SendNotifyMessageA); bb(SendNotifyMessageW); bb(SetActiveWindow); bb(SetCaretBlinkTime); bb(SetCaretPos); bb(SetClassLongA); bb(SetClassLongW); bb(SetClassWord); bb(SetClipboardViewer); bb(SetCursor); bb(SetCursorPos); bb(SetFocus); bb(SetForegroundWindow); // bb(SetPhysicalCursorPos); bb(SetScrollPos); bb(SetScrollRange); bb(SetSystemCursor); bb(SetWindowLongA); bb(SetWindowLongW); bb(SetWindowPos); bb(SetWindowTextW); bb(ShowCaret); bb(ShowCursor); bb(ShowWindow); bb(ShowWindowAsync); bb(TranslateMessage); bb(UnregisterClassA); bb(UnregisterClassW); bb(UpdateWindow); bb(WaitMessage); }
bb(ActivateKeyboardLayout); // bb(AddClipboardFormatListener); bb(AdjustWindowRect); bb(AdjustWindowRectEx); bb(AllowSetForegroundWindow); bb(AnimateWindow); bb(AnyPopup); bb(ArrangeIconicWindows); bb(AttachThreadInput); bb(BeginPaint); bb(BlockInput); bb(BringWindowToTop); // bb(CalculatePopupWindowPosition); bb(CascadeWindows); bb(ChangeClipboardChain); bb(ChangeDisplaySettingsExW); bb(ChangeDisplaySettingsW); bb(ChildWindowFromPoint); bb(ChildWindowFromPointEx);
identifier_body
user32.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> #![feature(test)] #![cfg(windows)] extern crate user32; extern crate test; use user32::*; use test::black_box as bb; #[cfg(target_arch = "x86_64")] #[test] fn functions_x64() { bb(GetClassLongPtrA); bb(GetClassLongPtrW); bb(GetWindowLongPtrA); bb(GetWindowLongPtrW);
bb(SetWindowLongPtrA); bb(SetWindowLongPtrW); } #[test] fn functions() { bb(ActivateKeyboardLayout); // bb(AddClipboardFormatListener); bb(AdjustWindowRect); bb(AdjustWindowRectEx); bb(AllowSetForegroundWindow); bb(AnimateWindow); bb(AnyPopup); bb(ArrangeIconicWindows); bb(AttachThreadInput); bb(BeginPaint); bb(BlockInput); bb(BringWindowToTop); // bb(CalculatePopupWindowPosition); bb(CascadeWindows); bb(ChangeClipboardChain); bb(ChangeDisplaySettingsExW); bb(ChangeDisplaySettingsW); bb(ChildWindowFromPoint); bb(ChildWindowFromPointEx); bb(ClipCursor); bb(CloseClipboard); bb(CloseDesktop); bb(CloseWindow); bb(CloseWindowStation); bb(CountClipboardFormats); bb(CreateCaret); bb(CreateCursor); bb(CreateWindowExW); bb(DefWindowProcW); bb(DeferWindowPos); bb(DeleteMenu); bb(DeregisterShellHookWindow); bb(DestroyAcceleratorTable); bb(DestroyCaret); bb(DestroyCursor); bb(DestroyIcon); bb(DestroyMenu); bb(DestroyWindow); bb(DispatchMessageW); bb(EmptyClipboard); bb(EnableScrollBar); bb(EnableWindow); bb(EndPaint); bb(EndTask); bb(EnumClipboardFormats); bb(EnumDisplayDevicesW); bb(EnumDisplaySettingsExW); bb(EnumThreadWindows); bb(EnumWindows); bb(FillRect); bb(FindWindowA ); bb(FindWindowExA); bb(FindWindowExW); bb(FindWindowW); bb(GetActiveWindow); bb(GetAncestor); bb(GetAsyncKeyState); bb(GetCaretBlinkTime); bb(GetCaretPos); bb(GetClassInfoExW); bb(GetClassInfoW); bb(GetClassLongA); bb(GetClassLongW); bb(GetClassWord); bb(GetClientRect); bb(GetClipCursor); bb(GetClipboardData); bb(GetClipboardFormatNameA); bb(GetClipboardFormatNameW); bb(GetClipboardOwner); bb(GetClipboardSequenceNumber); bb(GetClipboardViewer); bb(GetCursor); bb(GetCursorPos); bb(GetDC); bb(GetDesktopWindow); bb(GetFocus); bb(GetForegroundWindow); bb(GetKBCodePage); bb(GetKeyNameTextA); bb(GetKeyNameTextW); bb(GetKeyState); bb(GetKeyboardLayout); bb(GetKeyboardLayoutList); bb(GetKeyboardLayoutNameA); bb(GetKeyboardLayoutNameW); bb(GetKeyboardState); bb(GetKeyboardType); bb(GetMessageW); bb(GetOpenClipboardWindow); bb(GetParent); // bb(GetPhysicalCursorPos); bb(GetScrollPos); bb(GetScrollRange); bb(GetShellWindow); bb(GetSysColor); bb(GetSystemMetrics); bb(GetThreadDesktop); // bb(GetUpdatedClipboardFormats); bb(GetWindow); bb(GetWindowLongA); bb(GetWindowLongW); bb(GetWindowPlacement); bb(GetWindowRect); bb(GetWindowTextA); bb(GetWindowTextLengthA); bb(GetWindowTextLengthW); bb(GetWindowTextW); bb(HideCaret); bb(InvalidateRect); bb(IsClipboardFormatAvailable); bb(IsIconic); bb(IsWindow); bb(IsWindowEnabled); bb(IsWindowVisible); bb(LoadCursorFromFileW); bb(LoadCursorW); bb(LoadImageA); bb(LoadImageW); bb(MessageBoxA); bb(MessageBoxExA); bb(MessageBoxExW); bb(MessageBoxW); bb(OpenClipboard); bb(PeekMessageW); bb(PostMessageW); bb(PostQuitMessage); bb(RegisterClassExW); bb(RegisterClipboardFormatA); bb(RegisterClipboardFormatW); bb(ReleaseDC); bb(ScrollDC); bb(ScrollWindow); bb(ScrollWindowEx); bb(SendInput); bb(SendMessageA); bb(SendMessageTimeoutA); bb(SendMessageTimeoutW); bb(SendMessageW); bb(SendNotifyMessageA); bb(SendNotifyMessageW); bb(SetActiveWindow); bb(SetCaretBlinkTime); bb(SetCaretPos); bb(SetClassLongA); bb(SetClassLongW); bb(SetClassWord); bb(SetClipboardViewer); bb(SetCursor); bb(SetCursorPos); bb(SetFocus); bb(SetForegroundWindow); // bb(SetPhysicalCursorPos); bb(SetScrollPos); bb(SetScrollRange); bb(SetSystemCursor); bb(SetWindowLongA); bb(SetWindowLongW); bb(SetWindowPos); bb(SetWindowTextW); bb(ShowCaret); bb(ShowCursor); bb(ShowWindow); bb(ShowWindowAsync); bb(TranslateMessage); bb(UnregisterClassA); bb(UnregisterClassW); bb(UpdateWindow); bb(WaitMessage); }
bb(SetClassLongPtrA); bb(SetClassLongPtrW);
random_line_split
user32.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> #![feature(test)] #![cfg(windows)] extern crate user32; extern crate test; use user32::*; use test::black_box as bb; #[cfg(target_arch = "x86_64")] #[test] fn functions_x64() { bb(GetClassLongPtrA); bb(GetClassLongPtrW); bb(GetWindowLongPtrA); bb(GetWindowLongPtrW); bb(SetClassLongPtrA); bb(SetClassLongPtrW); bb(SetWindowLongPtrA); bb(SetWindowLongPtrW); } #[test] fn f
) { bb(ActivateKeyboardLayout); // bb(AddClipboardFormatListener); bb(AdjustWindowRect); bb(AdjustWindowRectEx); bb(AllowSetForegroundWindow); bb(AnimateWindow); bb(AnyPopup); bb(ArrangeIconicWindows); bb(AttachThreadInput); bb(BeginPaint); bb(BlockInput); bb(BringWindowToTop); // bb(CalculatePopupWindowPosition); bb(CascadeWindows); bb(ChangeClipboardChain); bb(ChangeDisplaySettingsExW); bb(ChangeDisplaySettingsW); bb(ChildWindowFromPoint); bb(ChildWindowFromPointEx); bb(ClipCursor); bb(CloseClipboard); bb(CloseDesktop); bb(CloseWindow); bb(CloseWindowStation); bb(CountClipboardFormats); bb(CreateCaret); bb(CreateCursor); bb(CreateWindowExW); bb(DefWindowProcW); bb(DeferWindowPos); bb(DeleteMenu); bb(DeregisterShellHookWindow); bb(DestroyAcceleratorTable); bb(DestroyCaret); bb(DestroyCursor); bb(DestroyIcon); bb(DestroyMenu); bb(DestroyWindow); bb(DispatchMessageW); bb(EmptyClipboard); bb(EnableScrollBar); bb(EnableWindow); bb(EndPaint); bb(EndTask); bb(EnumClipboardFormats); bb(EnumDisplayDevicesW); bb(EnumDisplaySettingsExW); bb(EnumThreadWindows); bb(EnumWindows); bb(FillRect); bb(FindWindowA ); bb(FindWindowExA); bb(FindWindowExW); bb(FindWindowW); bb(GetActiveWindow); bb(GetAncestor); bb(GetAsyncKeyState); bb(GetCaretBlinkTime); bb(GetCaretPos); bb(GetClassInfoExW); bb(GetClassInfoW); bb(GetClassLongA); bb(GetClassLongW); bb(GetClassWord); bb(GetClientRect); bb(GetClipCursor); bb(GetClipboardData); bb(GetClipboardFormatNameA); bb(GetClipboardFormatNameW); bb(GetClipboardOwner); bb(GetClipboardSequenceNumber); bb(GetClipboardViewer); bb(GetCursor); bb(GetCursorPos); bb(GetDC); bb(GetDesktopWindow); bb(GetFocus); bb(GetForegroundWindow); bb(GetKBCodePage); bb(GetKeyNameTextA); bb(GetKeyNameTextW); bb(GetKeyState); bb(GetKeyboardLayout); bb(GetKeyboardLayoutList); bb(GetKeyboardLayoutNameA); bb(GetKeyboardLayoutNameW); bb(GetKeyboardState); bb(GetKeyboardType); bb(GetMessageW); bb(GetOpenClipboardWindow); bb(GetParent); // bb(GetPhysicalCursorPos); bb(GetScrollPos); bb(GetScrollRange); bb(GetShellWindow); bb(GetSysColor); bb(GetSystemMetrics); bb(GetThreadDesktop); // bb(GetUpdatedClipboardFormats); bb(GetWindow); bb(GetWindowLongA); bb(GetWindowLongW); bb(GetWindowPlacement); bb(GetWindowRect); bb(GetWindowTextA); bb(GetWindowTextLengthA); bb(GetWindowTextLengthW); bb(GetWindowTextW); bb(HideCaret); bb(InvalidateRect); bb(IsClipboardFormatAvailable); bb(IsIconic); bb(IsWindow); bb(IsWindowEnabled); bb(IsWindowVisible); bb(LoadCursorFromFileW); bb(LoadCursorW); bb(LoadImageA); bb(LoadImageW); bb(MessageBoxA); bb(MessageBoxExA); bb(MessageBoxExW); bb(MessageBoxW); bb(OpenClipboard); bb(PeekMessageW); bb(PostMessageW); bb(PostQuitMessage); bb(RegisterClassExW); bb(RegisterClipboardFormatA); bb(RegisterClipboardFormatW); bb(ReleaseDC); bb(ScrollDC); bb(ScrollWindow); bb(ScrollWindowEx); bb(SendInput); bb(SendMessageA); bb(SendMessageTimeoutA); bb(SendMessageTimeoutW); bb(SendMessageW); bb(SendNotifyMessageA); bb(SendNotifyMessageW); bb(SetActiveWindow); bb(SetCaretBlinkTime); bb(SetCaretPos); bb(SetClassLongA); bb(SetClassLongW); bb(SetClassWord); bb(SetClipboardViewer); bb(SetCursor); bb(SetCursorPos); bb(SetFocus); bb(SetForegroundWindow); // bb(SetPhysicalCursorPos); bb(SetScrollPos); bb(SetScrollRange); bb(SetSystemCursor); bb(SetWindowLongA); bb(SetWindowLongW); bb(SetWindowPos); bb(SetWindowTextW); bb(ShowCaret); bb(ShowCursor); bb(ShowWindow); bb(ShowWindowAsync); bb(TranslateMessage); bb(UnregisterClassA); bb(UnregisterClassW); bb(UpdateWindow); bb(WaitMessage); }
unctions(
identifier_name
test.rs
// 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. extern crate drops_console; extern crate drops; extern crate serialize; use serialize::json; use drops::register::Register; #[test] fn
() { let mut reg = Register::new("/home/flaper87/workspace/personal/rust-drops/build"); reg.load("drops_console"); reg.call("info", Some(json::Decoder::new(json::from_str("\"My String\"").unwrap()))); reg.call("info", None); }
test_register_console
identifier_name
test.rs
// 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. extern crate drops_console; extern crate drops; extern crate serialize; use serialize::json; use drops::register::Register; #[test] fn test_register_console()
{ let mut reg = Register::new("/home/flaper87/workspace/personal/rust-drops/build"); reg.load("drops_console"); reg.call("info", Some(json::Decoder::new(json::from_str("\"My String\"").unwrap()))); reg.call("info", None); }
identifier_body
test.rs
// 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
// // 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. extern crate drops_console; extern crate drops; extern crate serialize; use serialize::json; use drops::register::Register; #[test] fn test_register_console() { let mut reg = Register::new("/home/flaper87/workspace/personal/rust-drops/build"); reg.load("drops_console"); reg.call("info", Some(json::Decoder::new(json::from_str("\"My String\"").unwrap()))); reg.call("info", None); }
// // http://www.apache.org/licenses/LICENSE-2.0
random_line_split
lib.rs
/* 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/. */ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate num_derive; #[macro_use] extern crate serde; pub mod resources; use crossbeam_channel::{Receiver, Sender}; use ipc_channel::ipc::IpcSender; use keyboard_types::KeyboardEvent; use msg::constellation_msg::{InputMethodType, PipelineId, TopLevelBrowsingContextId}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize}; pub use webxr_api::MainThreadWaker as EventLoopWaker; /// A cursor for the window. This is different from a CSS cursor (see /// `CursorKind`) in that it has no `Auto` value. #[repr(u8)] #[derive(Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)] pub enum Cursor { None, Default, Pointer, ContextMenu, Help, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, EResize, NResize, NeResize, NwResize, SResize, SeResize, SwResize, WResize, EwResize, NsResize, NeswResize, NwseResize, ColResize, RowResize, AllScroll, ZoomIn, ZoomOut, } /// Sends messages to the embedder. pub struct EmbedderProxy { pub sender: Sender<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, pub event_loop_waker: Box<dyn EventLoopWaker>, } impl EmbedderProxy { pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) { // Send a message and kick the OS event loop awake. if let Err(err) = self.sender.send(msg) { warn!("Failed to send response ({:?}).", err); } self.event_loop_waker.wake(); } } impl Clone for EmbedderProxy { fn clone(&self) -> EmbedderProxy { EmbedderProxy { sender: self.sender.clone(), event_loop_waker: self.event_loop_waker.clone(), } } } /// The port that the embedder receives messages on. pub struct EmbedderReceiver { pub receiver: Receiver<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, } impl EmbedderReceiver { pub fn try_recv_embedder_msg( &mut self, ) -> Option<(Option<TopLevelBrowsingContextId>, EmbedderMsg)> { self.receiver.try_recv().ok() } pub fn recv_embedder_msg(&mut self) -> (Option<TopLevelBrowsingContextId>, EmbedderMsg) { self.receiver.recv().unwrap() } } #[derive(Deserialize, Serialize)] pub enum ContextMenuResult { Dismissed, Ignored, Selected(usize), } #[derive(Deserialize, Serialize)] pub enum PromptDefinition { /// Show a message. Alert(String, IpcSender<()>), /// Ask a Ok/Cancel question. OkCancel(String, IpcSender<PromptResult>), /// Ask a Yes/No question. YesNo(String, IpcSender<PromptResult>), /// Ask the user to enter text. Input(String, String, IpcSender<Option<String>>), } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptOrigin { /// Prompt is triggered from content (window.prompt/alert/confirm/…). /// Prompt message is unknown. Untrusted, /// Prompt is triggered from Servo (ask for permission, show error,…). Trusted, } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptResult { /// Prompt was closed by clicking on the primary button (ok/yes) Primary, /// Prompt was closed by clicking on the secondary button (cancel/no) Secondary, /// Prompt was dismissed Dismissed, } #[derive(Deserialize, Serialize)] pub enum EmbedderMsg { /// A status message to be displayed by the browser chrome. Status(Option<String>), /// Alerts the embedder that the current page has changed its title. ChangePageTitle(Option<String>), /// Move the window to a point MoveTo(DeviceIntPoint), /// Resize the window to size ResizeTo(DeviceIntSize), /// Show dialog to user Prompt(PromptDefinition, PromptOrigin), /// Show a context menu to the user ShowContextMenu(IpcSender<ContextMenuResult>, Option<String>, Vec<String>), /// Whether or not to allow a pipeline to load a url. AllowNavigationRequest(PipelineId, ServoUrl), /// Whether or not to allow script to open a new tab/browser AllowOpeningBrowser(IpcSender<bool>), /// A new browser was created by script BrowserCreated(TopLevelBrowsingContextId), /// Wether or not to unload a document AllowUnload(IpcSender<bool>), /// Sends an unconsumed key event back to the embedder. Keyboard(KeyboardEvent), /// Gets system clipboard contents GetClipboardContents(IpcSender<String>), /// Sets system clipboard contents SetClipboardContents(String), /// Changes the cursor. SetCursor(Cursor), /// A favicon was detected NewFavicon(ServoUrl), /// <head> tag finished parsing HeadParsed, /// The history state has changed. HistoryChanged(Vec<ServoUrl>, usize), /// Enter or exit fullscreen SetFullscreenState(bool), /// The load of a page has begun LoadStart, /// The load of a page has completed LoadComplete, /// A browser is to be closed CloseBrowser, /// A pipeline panicked. First string is the reason, second one is the backtrace. Panic(String, Option<String>), /// Open dialog to select bluetooth device. GetSelectedBluetoothDevice(Vec<String>, IpcSender<Option<String>>), /// Open file dialog to select files. Set boolean flag to true allows to select multiple files. SelectFiles(Vec<FilterPattern>, bool, IpcSender<Option<Vec<String>>>), /// Open interface to request permission specified by prompt. PromptPermission(PermissionPrompt, IpcSender<PermissionRequest>), /// Request to present an IME to the user when an editable element is focused. /// If the input is text, the second parameter defines the pre-existing string /// text content and the zero-based index into the string locating the insertion point. /// bool is true for multi-line and false otherwise. ShowIME(InputMethodType, Option<(String, i32)>, bool, DeviceIntRect), /// Request to hide the IME when the editable element is blurred. HideIME, /// Servo has shut down Shutdown, /// Report a complete sampled profile ReportProfile(Vec<u8>), /// Notifies the embedder about media session events /// (i.e. when there is metadata for the active media session, playback state changes...). MediaSessionEvent(MediaSessionEvent), /// Report the status of Devtools Server with a token that can be used to bypass the permission prompt. OnDevtoolsStarted(Result<u16, ()>, String), } impl Debug for EmbedderMsg { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { EmbedderMsg::Status(..) => write!(f, "Status"), EmbedderMsg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), EmbedderMsg::MoveTo(..) => write!(f, "MoveTo"), EmbedderMsg::ResizeTo(..) => write!(f, "ResizeTo"), EmbedderMsg::Prompt(..) => write!(f, "Prompt"), EmbedderMsg::AllowUnload(..) => write!(f, "AllowUnload"), EmbedderMsg::AllowNavigationRequest(..) => write!(f, "AllowNavigationRequest"), EmbedderMsg::Keyboard(..) => write!(f, "Keyboard"), EmbedderMsg::GetClipboardContents(..) => write!(f, "GetClipboardContents"), EmbedderMsg::SetClipboardContents(..) => write!(f, "SetClipboardContents"), EmbedderMsg::SetCursor(..) => write!(f, "SetCursor"), EmbedderMsg::NewFavicon(..) => write!(f, "NewFavicon"), EmbedderMsg::HeadParsed => write!(f, "HeadParsed"), EmbedderMsg::CloseBrowser => write!(f, "CloseBrowser"), EmbedderMsg::HistoryChanged(..) => write!(f, "HistoryChanged"), EmbedderMsg::SetFullscreenState(..) => write!(f, "SetFullscreenState"), EmbedderMsg::LoadStart => write!(f, "LoadStart"), EmbedderMsg::LoadComplete => write!(f, "LoadComplete"), EmbedderMsg::Panic(..) => write!(f, "Panic"), EmbedderMsg::GetSelectedBluetoothDevice(..) => write!(f, "GetSelectedBluetoothDevice"), EmbedderMsg::SelectFiles(..) => write!(f, "SelectFiles"), EmbedderMsg::PromptPermission(..) => write!(f, "PromptPermission"), EmbedderMsg::ShowIME(..) => write!(f, "ShowIME"), EmbedderMsg::HideIME => write!(f, "HideIME"), EmbedderMsg::Shutdown => write!(f, "Shutdown"), EmbedderMsg::AllowOpeningBrowser(..) => write!(f, "AllowOpeningBrowser"), EmbedderMsg::BrowserCreated(..) => write!(f, "BrowserCreated"), EmbedderMsg::ReportProfile(..) => write!(f, "ReportProfile"), EmbedderMsg::MediaSessionEvent(..) => write!(f, "MediaSessionEvent"), EmbedderMsg::OnDevtoolsStarted(..) => write!(f, "OnDevtoolsStarted"), EmbedderMsg::ShowContextMenu(..) => write!(f, "ShowContextMenu"), } } } /// Filter for file selection; /// the `String` content is expected to be extension (e.g, "doc", without the prefixing ".") #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FilterPattern(pub String); /// https://w3c.github.io/mediasession/#mediametadata #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaMetadata { /// Title pub title: String, /// Artist pub artist: String, /// Album pub album: String, } impl MediaMetadata { pub fn new(title: String) -> Self {
/// https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate #[repr(i32)] #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionPlaybackState { /// The browsing context does not specify whether it’s playing or paused. None_ = 1, /// The browsing context is currently playing media and it can be paused. Playing, /// The browsing context has paused media and it can be resumed. Paused, } /// https://w3c.github.io/mediasession/#dictdef-mediapositionstate #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaPositionState { pub duration: f64, pub playback_rate: f64, pub position: f64, } impl MediaPositionState { pub fn new(duration: f64, playback_rate: f64, position: f64) -> Self { Self { duration, playback_rate, position, } } } /// Type of events sent from script to the embedder about the media session. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionEvent { /// Indicates that the media metadata is available. SetMetadata(MediaMetadata), /// Indicates that the playback state has changed. PlaybackStateChange(MediaSessionPlaybackState), /// Indicates that the position state is set. SetPositionState(MediaPositionState), } /// Enum with variants that match the DOM PermissionName enum #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionName { Geolocation, Notifications, Push, Midi, Camera, Microphone, Speaker, DeviceInfo, BackgroundSync, Bluetooth, PersistentStorage, } /// Information required to display a permission prompt #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionPrompt { Insecure(PermissionName), Request(PermissionName), } /// Status for prompting user for permission. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionRequest { Granted, Denied, }
Self { title, artist: "".to_owned(), album: "".to_owned(), } } }
identifier_body
lib.rs
/* 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/. */ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate num_derive; #[macro_use] extern crate serde; pub mod resources; use crossbeam_channel::{Receiver, Sender}; use ipc_channel::ipc::IpcSender; use keyboard_types::KeyboardEvent; use msg::constellation_msg::{InputMethodType, PipelineId, TopLevelBrowsingContextId}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize}; pub use webxr_api::MainThreadWaker as EventLoopWaker; /// A cursor for the window. This is different from a CSS cursor (see /// `CursorKind`) in that it has no `Auto` value. #[repr(u8)] #[derive(Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)] pub enum Cursor { None,
ContextMenu, Help, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, EResize, NResize, NeResize, NwResize, SResize, SeResize, SwResize, WResize, EwResize, NsResize, NeswResize, NwseResize, ColResize, RowResize, AllScroll, ZoomIn, ZoomOut, } /// Sends messages to the embedder. pub struct EmbedderProxy { pub sender: Sender<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, pub event_loop_waker: Box<dyn EventLoopWaker>, } impl EmbedderProxy { pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) { // Send a message and kick the OS event loop awake. if let Err(err) = self.sender.send(msg) { warn!("Failed to send response ({:?}).", err); } self.event_loop_waker.wake(); } } impl Clone for EmbedderProxy { fn clone(&self) -> EmbedderProxy { EmbedderProxy { sender: self.sender.clone(), event_loop_waker: self.event_loop_waker.clone(), } } } /// The port that the embedder receives messages on. pub struct EmbedderReceiver { pub receiver: Receiver<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, } impl EmbedderReceiver { pub fn try_recv_embedder_msg( &mut self, ) -> Option<(Option<TopLevelBrowsingContextId>, EmbedderMsg)> { self.receiver.try_recv().ok() } pub fn recv_embedder_msg(&mut self) -> (Option<TopLevelBrowsingContextId>, EmbedderMsg) { self.receiver.recv().unwrap() } } #[derive(Deserialize, Serialize)] pub enum ContextMenuResult { Dismissed, Ignored, Selected(usize), } #[derive(Deserialize, Serialize)] pub enum PromptDefinition { /// Show a message. Alert(String, IpcSender<()>), /// Ask a Ok/Cancel question. OkCancel(String, IpcSender<PromptResult>), /// Ask a Yes/No question. YesNo(String, IpcSender<PromptResult>), /// Ask the user to enter text. Input(String, String, IpcSender<Option<String>>), } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptOrigin { /// Prompt is triggered from content (window.prompt/alert/confirm/…). /// Prompt message is unknown. Untrusted, /// Prompt is triggered from Servo (ask for permission, show error,…). Trusted, } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptResult { /// Prompt was closed by clicking on the primary button (ok/yes) Primary, /// Prompt was closed by clicking on the secondary button (cancel/no) Secondary, /// Prompt was dismissed Dismissed, } #[derive(Deserialize, Serialize)] pub enum EmbedderMsg { /// A status message to be displayed by the browser chrome. Status(Option<String>), /// Alerts the embedder that the current page has changed its title. ChangePageTitle(Option<String>), /// Move the window to a point MoveTo(DeviceIntPoint), /// Resize the window to size ResizeTo(DeviceIntSize), /// Show dialog to user Prompt(PromptDefinition, PromptOrigin), /// Show a context menu to the user ShowContextMenu(IpcSender<ContextMenuResult>, Option<String>, Vec<String>), /// Whether or not to allow a pipeline to load a url. AllowNavigationRequest(PipelineId, ServoUrl), /// Whether or not to allow script to open a new tab/browser AllowOpeningBrowser(IpcSender<bool>), /// A new browser was created by script BrowserCreated(TopLevelBrowsingContextId), /// Wether or not to unload a document AllowUnload(IpcSender<bool>), /// Sends an unconsumed key event back to the embedder. Keyboard(KeyboardEvent), /// Gets system clipboard contents GetClipboardContents(IpcSender<String>), /// Sets system clipboard contents SetClipboardContents(String), /// Changes the cursor. SetCursor(Cursor), /// A favicon was detected NewFavicon(ServoUrl), /// <head> tag finished parsing HeadParsed, /// The history state has changed. HistoryChanged(Vec<ServoUrl>, usize), /// Enter or exit fullscreen SetFullscreenState(bool), /// The load of a page has begun LoadStart, /// The load of a page has completed LoadComplete, /// A browser is to be closed CloseBrowser, /// A pipeline panicked. First string is the reason, second one is the backtrace. Panic(String, Option<String>), /// Open dialog to select bluetooth device. GetSelectedBluetoothDevice(Vec<String>, IpcSender<Option<String>>), /// Open file dialog to select files. Set boolean flag to true allows to select multiple files. SelectFiles(Vec<FilterPattern>, bool, IpcSender<Option<Vec<String>>>), /// Open interface to request permission specified by prompt. PromptPermission(PermissionPrompt, IpcSender<PermissionRequest>), /// Request to present an IME to the user when an editable element is focused. /// If the input is text, the second parameter defines the pre-existing string /// text content and the zero-based index into the string locating the insertion point. /// bool is true for multi-line and false otherwise. ShowIME(InputMethodType, Option<(String, i32)>, bool, DeviceIntRect), /// Request to hide the IME when the editable element is blurred. HideIME, /// Servo has shut down Shutdown, /// Report a complete sampled profile ReportProfile(Vec<u8>), /// Notifies the embedder about media session events /// (i.e. when there is metadata for the active media session, playback state changes...). MediaSessionEvent(MediaSessionEvent), /// Report the status of Devtools Server with a token that can be used to bypass the permission prompt. OnDevtoolsStarted(Result<u16, ()>, String), } impl Debug for EmbedderMsg { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { EmbedderMsg::Status(..) => write!(f, "Status"), EmbedderMsg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), EmbedderMsg::MoveTo(..) => write!(f, "MoveTo"), EmbedderMsg::ResizeTo(..) => write!(f, "ResizeTo"), EmbedderMsg::Prompt(..) => write!(f, "Prompt"), EmbedderMsg::AllowUnload(..) => write!(f, "AllowUnload"), EmbedderMsg::AllowNavigationRequest(..) => write!(f, "AllowNavigationRequest"), EmbedderMsg::Keyboard(..) => write!(f, "Keyboard"), EmbedderMsg::GetClipboardContents(..) => write!(f, "GetClipboardContents"), EmbedderMsg::SetClipboardContents(..) => write!(f, "SetClipboardContents"), EmbedderMsg::SetCursor(..) => write!(f, "SetCursor"), EmbedderMsg::NewFavicon(..) => write!(f, "NewFavicon"), EmbedderMsg::HeadParsed => write!(f, "HeadParsed"), EmbedderMsg::CloseBrowser => write!(f, "CloseBrowser"), EmbedderMsg::HistoryChanged(..) => write!(f, "HistoryChanged"), EmbedderMsg::SetFullscreenState(..) => write!(f, "SetFullscreenState"), EmbedderMsg::LoadStart => write!(f, "LoadStart"), EmbedderMsg::LoadComplete => write!(f, "LoadComplete"), EmbedderMsg::Panic(..) => write!(f, "Panic"), EmbedderMsg::GetSelectedBluetoothDevice(..) => write!(f, "GetSelectedBluetoothDevice"), EmbedderMsg::SelectFiles(..) => write!(f, "SelectFiles"), EmbedderMsg::PromptPermission(..) => write!(f, "PromptPermission"), EmbedderMsg::ShowIME(..) => write!(f, "ShowIME"), EmbedderMsg::HideIME => write!(f, "HideIME"), EmbedderMsg::Shutdown => write!(f, "Shutdown"), EmbedderMsg::AllowOpeningBrowser(..) => write!(f, "AllowOpeningBrowser"), EmbedderMsg::BrowserCreated(..) => write!(f, "BrowserCreated"), EmbedderMsg::ReportProfile(..) => write!(f, "ReportProfile"), EmbedderMsg::MediaSessionEvent(..) => write!(f, "MediaSessionEvent"), EmbedderMsg::OnDevtoolsStarted(..) => write!(f, "OnDevtoolsStarted"), EmbedderMsg::ShowContextMenu(..) => write!(f, "ShowContextMenu"), } } } /// Filter for file selection; /// the `String` content is expected to be extension (e.g, "doc", without the prefixing ".") #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FilterPattern(pub String); /// https://w3c.github.io/mediasession/#mediametadata #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaMetadata { /// Title pub title: String, /// Artist pub artist: String, /// Album pub album: String, } impl MediaMetadata { pub fn new(title: String) -> Self { Self { title, artist: "".to_owned(), album: "".to_owned(), } } } /// https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate #[repr(i32)] #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionPlaybackState { /// The browsing context does not specify whether it’s playing or paused. None_ = 1, /// The browsing context is currently playing media and it can be paused. Playing, /// The browsing context has paused media and it can be resumed. Paused, } /// https://w3c.github.io/mediasession/#dictdef-mediapositionstate #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaPositionState { pub duration: f64, pub playback_rate: f64, pub position: f64, } impl MediaPositionState { pub fn new(duration: f64, playback_rate: f64, position: f64) -> Self { Self { duration, playback_rate, position, } } } /// Type of events sent from script to the embedder about the media session. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionEvent { /// Indicates that the media metadata is available. SetMetadata(MediaMetadata), /// Indicates that the playback state has changed. PlaybackStateChange(MediaSessionPlaybackState), /// Indicates that the position state is set. SetPositionState(MediaPositionState), } /// Enum with variants that match the DOM PermissionName enum #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionName { Geolocation, Notifications, Push, Midi, Camera, Microphone, Speaker, DeviceInfo, BackgroundSync, Bluetooth, PersistentStorage, } /// Information required to display a permission prompt #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionPrompt { Insecure(PermissionName), Request(PermissionName), } /// Status for prompting user for permission. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionRequest { Granted, Denied, }
Default, Pointer,
random_line_split
lib.rs
/* 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/. */ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate num_derive; #[macro_use] extern crate serde; pub mod resources; use crossbeam_channel::{Receiver, Sender}; use ipc_channel::ipc::IpcSender; use keyboard_types::KeyboardEvent; use msg::constellation_msg::{InputMethodType, PipelineId, TopLevelBrowsingContextId}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize}; pub use webxr_api::MainThreadWaker as EventLoopWaker; /// A cursor for the window. This is different from a CSS cursor (see /// `CursorKind`) in that it has no `Auto` value. #[repr(u8)] #[derive(Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)] pub enum
{ None, Default, Pointer, ContextMenu, Help, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, EResize, NResize, NeResize, NwResize, SResize, SeResize, SwResize, WResize, EwResize, NsResize, NeswResize, NwseResize, ColResize, RowResize, AllScroll, ZoomIn, ZoomOut, } /// Sends messages to the embedder. pub struct EmbedderProxy { pub sender: Sender<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, pub event_loop_waker: Box<dyn EventLoopWaker>, } impl EmbedderProxy { pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) { // Send a message and kick the OS event loop awake. if let Err(err) = self.sender.send(msg) { warn!("Failed to send response ({:?}).", err); } self.event_loop_waker.wake(); } } impl Clone for EmbedderProxy { fn clone(&self) -> EmbedderProxy { EmbedderProxy { sender: self.sender.clone(), event_loop_waker: self.event_loop_waker.clone(), } } } /// The port that the embedder receives messages on. pub struct EmbedderReceiver { pub receiver: Receiver<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, } impl EmbedderReceiver { pub fn try_recv_embedder_msg( &mut self, ) -> Option<(Option<TopLevelBrowsingContextId>, EmbedderMsg)> { self.receiver.try_recv().ok() } pub fn recv_embedder_msg(&mut self) -> (Option<TopLevelBrowsingContextId>, EmbedderMsg) { self.receiver.recv().unwrap() } } #[derive(Deserialize, Serialize)] pub enum ContextMenuResult { Dismissed, Ignored, Selected(usize), } #[derive(Deserialize, Serialize)] pub enum PromptDefinition { /// Show a message. Alert(String, IpcSender<()>), /// Ask a Ok/Cancel question. OkCancel(String, IpcSender<PromptResult>), /// Ask a Yes/No question. YesNo(String, IpcSender<PromptResult>), /// Ask the user to enter text. Input(String, String, IpcSender<Option<String>>), } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptOrigin { /// Prompt is triggered from content (window.prompt/alert/confirm/…). /// Prompt message is unknown. Untrusted, /// Prompt is triggered from Servo (ask for permission, show error,…). Trusted, } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptResult { /// Prompt was closed by clicking on the primary button (ok/yes) Primary, /// Prompt was closed by clicking on the secondary button (cancel/no) Secondary, /// Prompt was dismissed Dismissed, } #[derive(Deserialize, Serialize)] pub enum EmbedderMsg { /// A status message to be displayed by the browser chrome. Status(Option<String>), /// Alerts the embedder that the current page has changed its title. ChangePageTitle(Option<String>), /// Move the window to a point MoveTo(DeviceIntPoint), /// Resize the window to size ResizeTo(DeviceIntSize), /// Show dialog to user Prompt(PromptDefinition, PromptOrigin), /// Show a context menu to the user ShowContextMenu(IpcSender<ContextMenuResult>, Option<String>, Vec<String>), /// Whether or not to allow a pipeline to load a url. AllowNavigationRequest(PipelineId, ServoUrl), /// Whether or not to allow script to open a new tab/browser AllowOpeningBrowser(IpcSender<bool>), /// A new browser was created by script BrowserCreated(TopLevelBrowsingContextId), /// Wether or not to unload a document AllowUnload(IpcSender<bool>), /// Sends an unconsumed key event back to the embedder. Keyboard(KeyboardEvent), /// Gets system clipboard contents GetClipboardContents(IpcSender<String>), /// Sets system clipboard contents SetClipboardContents(String), /// Changes the cursor. SetCursor(Cursor), /// A favicon was detected NewFavicon(ServoUrl), /// <head> tag finished parsing HeadParsed, /// The history state has changed. HistoryChanged(Vec<ServoUrl>, usize), /// Enter or exit fullscreen SetFullscreenState(bool), /// The load of a page has begun LoadStart, /// The load of a page has completed LoadComplete, /// A browser is to be closed CloseBrowser, /// A pipeline panicked. First string is the reason, second one is the backtrace. Panic(String, Option<String>), /// Open dialog to select bluetooth device. GetSelectedBluetoothDevice(Vec<String>, IpcSender<Option<String>>), /// Open file dialog to select files. Set boolean flag to true allows to select multiple files. SelectFiles(Vec<FilterPattern>, bool, IpcSender<Option<Vec<String>>>), /// Open interface to request permission specified by prompt. PromptPermission(PermissionPrompt, IpcSender<PermissionRequest>), /// Request to present an IME to the user when an editable element is focused. /// If the input is text, the second parameter defines the pre-existing string /// text content and the zero-based index into the string locating the insertion point. /// bool is true for multi-line and false otherwise. ShowIME(InputMethodType, Option<(String, i32)>, bool, DeviceIntRect), /// Request to hide the IME when the editable element is blurred. HideIME, /// Servo has shut down Shutdown, /// Report a complete sampled profile ReportProfile(Vec<u8>), /// Notifies the embedder about media session events /// (i.e. when there is metadata for the active media session, playback state changes...). MediaSessionEvent(MediaSessionEvent), /// Report the status of Devtools Server with a token that can be used to bypass the permission prompt. OnDevtoolsStarted(Result<u16, ()>, String), } impl Debug for EmbedderMsg { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { EmbedderMsg::Status(..) => write!(f, "Status"), EmbedderMsg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), EmbedderMsg::MoveTo(..) => write!(f, "MoveTo"), EmbedderMsg::ResizeTo(..) => write!(f, "ResizeTo"), EmbedderMsg::Prompt(..) => write!(f, "Prompt"), EmbedderMsg::AllowUnload(..) => write!(f, "AllowUnload"), EmbedderMsg::AllowNavigationRequest(..) => write!(f, "AllowNavigationRequest"), EmbedderMsg::Keyboard(..) => write!(f, "Keyboard"), EmbedderMsg::GetClipboardContents(..) => write!(f, "GetClipboardContents"), EmbedderMsg::SetClipboardContents(..) => write!(f, "SetClipboardContents"), EmbedderMsg::SetCursor(..) => write!(f, "SetCursor"), EmbedderMsg::NewFavicon(..) => write!(f, "NewFavicon"), EmbedderMsg::HeadParsed => write!(f, "HeadParsed"), EmbedderMsg::CloseBrowser => write!(f, "CloseBrowser"), EmbedderMsg::HistoryChanged(..) => write!(f, "HistoryChanged"), EmbedderMsg::SetFullscreenState(..) => write!(f, "SetFullscreenState"), EmbedderMsg::LoadStart => write!(f, "LoadStart"), EmbedderMsg::LoadComplete => write!(f, "LoadComplete"), EmbedderMsg::Panic(..) => write!(f, "Panic"), EmbedderMsg::GetSelectedBluetoothDevice(..) => write!(f, "GetSelectedBluetoothDevice"), EmbedderMsg::SelectFiles(..) => write!(f, "SelectFiles"), EmbedderMsg::PromptPermission(..) => write!(f, "PromptPermission"), EmbedderMsg::ShowIME(..) => write!(f, "ShowIME"), EmbedderMsg::HideIME => write!(f, "HideIME"), EmbedderMsg::Shutdown => write!(f, "Shutdown"), EmbedderMsg::AllowOpeningBrowser(..) => write!(f, "AllowOpeningBrowser"), EmbedderMsg::BrowserCreated(..) => write!(f, "BrowserCreated"), EmbedderMsg::ReportProfile(..) => write!(f, "ReportProfile"), EmbedderMsg::MediaSessionEvent(..) => write!(f, "MediaSessionEvent"), EmbedderMsg::OnDevtoolsStarted(..) => write!(f, "OnDevtoolsStarted"), EmbedderMsg::ShowContextMenu(..) => write!(f, "ShowContextMenu"), } } } /// Filter for file selection; /// the `String` content is expected to be extension (e.g, "doc", without the prefixing ".") #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FilterPattern(pub String); /// https://w3c.github.io/mediasession/#mediametadata #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaMetadata { /// Title pub title: String, /// Artist pub artist: String, /// Album pub album: String, } impl MediaMetadata { pub fn new(title: String) -> Self { Self { title, artist: "".to_owned(), album: "".to_owned(), } } } /// https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate #[repr(i32)] #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionPlaybackState { /// The browsing context does not specify whether it’s playing or paused. None_ = 1, /// The browsing context is currently playing media and it can be paused. Playing, /// The browsing context has paused media and it can be resumed. Paused, } /// https://w3c.github.io/mediasession/#dictdef-mediapositionstate #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaPositionState { pub duration: f64, pub playback_rate: f64, pub position: f64, } impl MediaPositionState { pub fn new(duration: f64, playback_rate: f64, position: f64) -> Self { Self { duration, playback_rate, position, } } } /// Type of events sent from script to the embedder about the media session. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionEvent { /// Indicates that the media metadata is available. SetMetadata(MediaMetadata), /// Indicates that the playback state has changed. PlaybackStateChange(MediaSessionPlaybackState), /// Indicates that the position state is set. SetPositionState(MediaPositionState), } /// Enum with variants that match the DOM PermissionName enum #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionName { Geolocation, Notifications, Push, Midi, Camera, Microphone, Speaker, DeviceInfo, BackgroundSync, Bluetooth, PersistentStorage, } /// Information required to display a permission prompt #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionPrompt { Insecure(PermissionName), Request(PermissionName), } /// Status for prompting user for permission. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionRequest { Granted, Denied, }
Cursor
identifier_name
arrays.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. use rust_sodium::crypto::box_::{ NONCEBYTES as ASYM_NONCE_LEN, PUBLICKEYBYTES as ASYM_PUBLIC_KEY_LEN, SECRETKEYBYTES as ASYM_SECRET_KEY_LEN, }; use rust_sodium::crypto::secretbox::{KEYBYTES as SYM_KEY_LEN, NONCEBYTES as SYM_NONCE_LEN}; use rust_sodium::crypto::sign::{ PUBLICKEYBYTES as SIGN_PUBLIC_KEY_LEN, SECRETKEYBYTES as SIGN_SECRET_KEY_LEN, }; use safe_nd::XOR_NAME_LEN; use threshold_crypto::PK_SIZE as BLS_PUBLIC_KEY_LEN; /// Array containing public key bytes. pub type AsymPublicKey = [u8; ASYM_PUBLIC_KEY_LEN]; /// Array containing private key bytes. pub type AsymSecretKey = [u8; ASYM_SECRET_KEY_LEN]; /// Array containing nonce bytes. pub type AsymNonce = [u8; ASYM_NONCE_LEN]; /// Array containing private key bytes. pub type SymSecretKey = [u8; SYM_KEY_LEN]; /// Array containing nonce bytes. pub type SymNonce = [u8; SYM_NONCE_LEN];
/// Array containing sign public key bytes. pub type SignPublicKey = [u8; SIGN_PUBLIC_KEY_LEN]; /// Array containing sign private key bytes. pub type SignSecretKey = [u8; SIGN_SECRET_KEY_LEN]; /// Array containing `XorName` bytes. pub type XorNameArray = [u8; XOR_NAME_LEN];
/// Array containing BLS public key. pub type BlsPublicKey = [u8; BLS_PUBLIC_KEY_LEN];
random_line_split
instr_kandw.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn kandw_1() { run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 65, 207], OperandSize::Dword) } #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K7)), operand2: Some(Direct(K2)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 236, 65, 255], OperandSize::Qword) }
kandw_2
identifier_name
instr_kandw.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn kandw_1() { run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 65, 207], OperandSize::Dword) } #[test] fn kandw_2()
{ run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K7)), operand2: Some(Direct(K2)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 236, 65, 255], OperandSize::Qword) }
identifier_body
instr_kandw.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn kandw_1() { run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 65, 207], OperandSize::Dword) } #[test] fn kandw_2() { run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K7)), operand2: Some(Direct(K2)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 236, 65, 255], OperandSize::Qword)
}
random_line_split
context.rs
::<usize>().expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags, /// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> ScaleFactor<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } // We manually implement Debug for CascadeInputs so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for CascadeInputs { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CascadeInputs {{ rules: {:?}, visited_rules: {:?},.. }}", self.rules, self.visited_rules) } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn clone(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None) } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Information about the current element being processed. We group this /// together into a single struct within ThreadLocalStyleContext so that we can /// instantiate and destroy it easily at the beginning and end of element /// processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we /// only use this for identity checks, but we could use SendElement if there /// were a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] #[cfg(feature = "servo")] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, /// Whether this is a "large" traversal. pub is_large: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> ops::Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); debug_assert!(self.selectors == 0, "set at the end"); debug_assert!(self.revalidation_selectors == 0, "set at the end"); debug_assert!(self.dependency_selectors == 0, "set at the end"); debug_assert!(self.declarations == 0, "set at the end"); debug_assert!(self.stylist_rebuilds == 0, "set at the end"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, styles_reused: self.styles_reused + other.styles_reused, selectors: 0, revalidation_selectors: 0, dependency_selectors: 0, declarations: 0, stylist_rebuilds: 0, traversal_time_ms: 0.0, is_parallel: None, is_large: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time"); writeln!(f, "[PERF] perf block start")?; writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })?; writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)?; writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)?; writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)?; writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!(f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors)?; writeln!(f, "[PERF],dependency_selectors,{}", self.dependency_selectors)?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, parallel: bool, start: f64) where E: TElement, D: DomTraversal<E>, { let threshold = traversal.shared_context().options.style_statistics_threshold; let stylist = traversal.shared_context().stylist; self.is_parallel = Some(parallel); self.is_large = Some(self.elements_traversed as usize >= threshold); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; self.selectors = stylist.num_selectors() as u32; self.revalidation_selectors = stylist.num_revalidation_selectors() as u32; self.dependency_selectors = stylist.num_invalidations() as u32; self.declarations = stylist.num_declarations() as u32; self.stylist_rebuilds = stylist.num_rebuilds() as u32; } /// Returns whether this traversal is 'large' in order to avoid console spam /// from lots of tiny traversals. pub fn is_large_traversal(&self) -> bool { self.is_large.unwrap() } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating animations based on the /// |tasks| field. These include updating CSS animations/transitions that changed as part /// of the non-animation style traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style as the initial /// value of its Keyframe. Required if |tasks| includes CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks }, /// Performs one of a number of possible tasks as a result of animation-only restyle. /// Currently we do only process for resolving descendant elements that were display:none /// subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks } => { unsafe { el.update_animations(before_change_style, tasks) }; } #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { unsafe { el.process_post_animation(tasks) }; } } } /// Creates a task to update various animation-related state on /// a given (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations(el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style: before_change_style, tasks: tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks: tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FnvHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<CacheItem<E>, [Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self { SelectorFlagsMap { map: FnvHashMap::default(), cache: LRUCache::default(), } } /// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if self.cache.iter().find(|&(_, ref x)| x.0 == el) .map_or(ElementSelectorFlags::empty(), |(_, x)| x.1) .contains(flags) { return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; // Insert into the cache. We don't worry about duplicate entries, // which lets us avoid reshuffling. self.cache.insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. pub fn apply_flags(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement;
impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn new(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this once black_box is stable. #[inline(always)] fn get_sp() -> usize { let mut foo: usize = 42; (&mut foo as *mut usize) as usize } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able to mutate
random_line_split
context.rs
usize>().expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags, /// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> ScaleFactor<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } // We manually implement Debug for CascadeInputs so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for CascadeInputs { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CascadeInputs {{ rules: {:?}, visited_rules: {:?},.. }}", self.rules, self.visited_rules) } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn clone(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None) } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Information about the current element being processed. We group this /// together into a single struct within ThreadLocalStyleContext so that we can /// instantiate and destroy it easily at the beginning and end of element /// processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we /// only use this for identity checks, but we could use SendElement if there /// were a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] #[cfg(feature = "servo")] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, /// Whether this is a "large" traversal. pub is_large: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> ops::Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); debug_assert!(self.selectors == 0, "set at the end"); debug_assert!(self.revalidation_selectors == 0, "set at the end"); debug_assert!(self.dependency_selectors == 0, "set at the end"); debug_assert!(self.declarations == 0, "set at the end"); debug_assert!(self.stylist_rebuilds == 0, "set at the end"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, styles_reused: self.styles_reused + other.styles_reused, selectors: 0, revalidation_selectors: 0, dependency_selectors: 0, declarations: 0, stylist_rebuilds: 0, traversal_time_ms: 0.0, is_parallel: None, is_large: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time"); writeln!(f, "[PERF] perf block start")?; writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })?; writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)?; writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)?; writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)?; writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!(f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors)?; writeln!(f, "[PERF],dependency_selectors,{}", self.dependency_selectors)?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, parallel: bool, start: f64) where E: TElement, D: DomTraversal<E>, { let threshold = traversal.shared_context().options.style_statistics_threshold; let stylist = traversal.shared_context().stylist; self.is_parallel = Some(parallel); self.is_large = Some(self.elements_traversed as usize >= threshold); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; self.selectors = stylist.num_selectors() as u32; self.revalidation_selectors = stylist.num_revalidation_selectors() as u32; self.dependency_selectors = stylist.num_invalidations() as u32; self.declarations = stylist.num_declarations() as u32; self.stylist_rebuilds = stylist.num_rebuilds() as u32; } /// Returns whether this traversal is 'large' in order to avoid console spam /// from lots of tiny traversals. pub fn is_large_traversal(&self) -> bool { self.is_large.unwrap() } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating animations based on the /// |tasks| field. These include updating CSS animations/transitions that changed as part /// of the non-animation style traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style as the initial /// value of its Keyframe. Required if |tasks| includes CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks }, /// Performs one of a number of possible tasks as a result of animation-only restyle. /// Currently we do only process for resolving descendant elements that were display:none /// subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks } =>
#[cfg(feature = "gecko")] PostAnimation { el, tasks } => { unsafe { el.process_post_animation(tasks) }; } } } /// Creates a task to update various animation-related state on /// a given (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations(el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style: before_change_style, tasks: tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks: tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FnvHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<CacheItem<E>, [Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self { SelectorFlagsMap { map: FnvHashMap::default(), cache: LRUCache::default(), } } /// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if self.cache.iter().find(|&(_, ref x)| x.0 == el) .map_or(ElementSelectorFlags::empty(), |(_, x)| x.1) .contains(flags) { return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; // Insert into the cache. We don't worry about duplicate entries, // which lets us avoid reshuffling. self.cache.insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. pub fn apply_flags(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement; impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn new(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this once black_box is stable. #[inline(always)] fn get_sp() -> usize { let mut foo: usize = 42; (&mut foo as *mut usize) as usize } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able
{ unsafe { el.update_animations(before_change_style, tasks) }; }
conditional_block
context.rs
usize>().expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags, /// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> ScaleFactor<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } // We manually implement Debug for CascadeInputs so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for CascadeInputs { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CascadeInputs {{ rules: {:?}, visited_rules: {:?},.. }}", self.rules, self.visited_rules) } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn
(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None) } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Information about the current element being processed. We group this /// together into a single struct within ThreadLocalStyleContext so that we can /// instantiate and destroy it easily at the beginning and end of element /// processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we /// only use this for identity checks, but we could use SendElement if there /// were a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] #[cfg(feature = "servo")] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, /// Whether this is a "large" traversal. pub is_large: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> ops::Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); debug_assert!(self.selectors == 0, "set at the end"); debug_assert!(self.revalidation_selectors == 0, "set at the end"); debug_assert!(self.dependency_selectors == 0, "set at the end"); debug_assert!(self.declarations == 0, "set at the end"); debug_assert!(self.stylist_rebuilds == 0, "set at the end"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, styles_reused: self.styles_reused + other.styles_reused, selectors: 0, revalidation_selectors: 0, dependency_selectors: 0, declarations: 0, stylist_rebuilds: 0, traversal_time_ms: 0.0, is_parallel: None, is_large: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time"); writeln!(f, "[PERF] perf block start")?; writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })?; writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)?; writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)?; writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)?; writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!(f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors)?; writeln!(f, "[PERF],dependency_selectors,{}", self.dependency_selectors)?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, parallel: bool, start: f64) where E: TElement, D: DomTraversal<E>, { let threshold = traversal.shared_context().options.style_statistics_threshold; let stylist = traversal.shared_context().stylist; self.is_parallel = Some(parallel); self.is_large = Some(self.elements_traversed as usize >= threshold); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; self.selectors = stylist.num_selectors() as u32; self.revalidation_selectors = stylist.num_revalidation_selectors() as u32; self.dependency_selectors = stylist.num_invalidations() as u32; self.declarations = stylist.num_declarations() as u32; self.stylist_rebuilds = stylist.num_rebuilds() as u32; } /// Returns whether this traversal is 'large' in order to avoid console spam /// from lots of tiny traversals. pub fn is_large_traversal(&self) -> bool { self.is_large.unwrap() } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating animations based on the /// |tasks| field. These include updating CSS animations/transitions that changed as part /// of the non-animation style traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style as the initial /// value of its Keyframe. Required if |tasks| includes CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks }, /// Performs one of a number of possible tasks as a result of animation-only restyle. /// Currently we do only process for resolving descendant elements that were display:none /// subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks } => { unsafe { el.update_animations(before_change_style, tasks) }; } #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { unsafe { el.process_post_animation(tasks) }; } } } /// Creates a task to update various animation-related state on /// a given (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations(el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style: before_change_style, tasks: tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks: tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FnvHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<CacheItem<E>, [Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self { SelectorFlagsMap { map: FnvHashMap::default(), cache: LRUCache::default(), } } /// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if self.cache.iter().find(|&(_, ref x)| x.0 == el) .map_or(ElementSelectorFlags::empty(), |(_, x)| x.1) .contains(flags) { return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; // Insert into the cache. We don't worry about duplicate entries, // which lets us avoid reshuffling. self.cache.insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. pub fn apply_flags(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement; impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn new(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this once black_box is stable. #[inline(always)] fn get_sp() -> usize { let mut foo: usize = 42; (&mut foo as *mut usize) as usize } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able
clone
identifier_name
context.rs
usize>().expect("Couldn't parse environmental variable as usize") }) } impl Default for StyleSystemOptions { #[cfg(feature = "servo")] fn default() -> Self { use servo_config::opts; StyleSystemOptions { disable_style_sharing_cache: opts::get().disable_share_style_cache, dump_style_statistics: opts::get().style_sharing_stats, style_statistics_threshold: DEFAULT_STATISTICS_THRESHOLD, } } #[cfg(feature = "gecko")] fn default() -> Self { StyleSystemOptions { disable_style_sharing_cache: get_env_bool("DISABLE_STYLE_SHARING_CACHE"), dump_style_statistics: get_env_bool("DUMP_STYLE_STATISTICS"), style_statistics_threshold: get_env_usize("STYLE_STATISTICS_THRESHOLD") .unwrap_or(DEFAULT_STATISTICS_THRESHOLD), } } } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: &'a Stylist, /// Whether visited styles are enabled. /// /// They may be disabled when Gecko's pref layout.css.visited_links_enabled /// is false, or when in private browsing mode. pub visited_styles_enabled: bool, /// Configuration options. pub options: StyleSystemOptions, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags, /// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. #[cfg(feature = "servo")] pub expired_animations: Arc<RwLock<FnvHashMap<OpaqueNode, Vec<Animation>>>>, /// Paint worklets #[cfg(feature = "servo")] pub registered_speculative_painters: &'a RegisteredSpeculativePainters, /// Data needed to create the thread-local style context from the shared one. #[cfg(feature = "servo")] pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device().au_viewport_size() } /// The device pixel ratio pub fn device_pixel_ratio(&self) -> ScaleFactor<f32, CSSPixel, DevicePixel> { self.stylist.device().device_pixel_ratio() } /// The quirks mode of the document. pub fn quirks_mode(&self) -> QuirksMode { self.stylist.quirks_mode() } } /// The structure holds various intermediate inputs that are eventually used by /// by the cascade. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Default)] pub struct CascadeInputs { /// The rule node representing the ordered list of rules matched for this /// node. pub rules: Option<StrongRuleNode>, /// The rule node representing the ordered list of rules matched for this /// node if visited, only computed if there's a relevant link for this /// element. A element's "relevant link" is the element being matched if it /// is a link or the nearest ancestor link. pub visited_rules: Option<StrongRuleNode>, } impl CascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_style(style: &ComputedValues) -> Self { CascadeInputs { rules: style.rules.clone(), visited_rules: style.visited_style().and_then(|v| v.rules.clone()), } } } // We manually implement Debug for CascadeInputs so that we can avoid the // verbose stringification of ComputedValues for normal logging. impl fmt::Debug for CascadeInputs { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CascadeInputs {{ rules: {:?}, visited_rules: {:?},.. }}", self.rules, self.visited_rules) } } /// A list of cascade inputs for eagerly-cascaded pseudo-elements. /// The list is stored inline. #[derive(Debug)] pub struct EagerPseudoCascadeInputs(Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]>); // Manually implement `Clone` here because the derived impl of `Clone` for // array types assumes the value inside is `Copy`. impl Clone for EagerPseudoCascadeInputs { fn clone(&self) -> Self { if self.0.is_none() { return EagerPseudoCascadeInputs(None) } let self_inputs = self.0.as_ref().unwrap(); let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = self_inputs[i].clone(); } EagerPseudoCascadeInputs(Some(inputs)) } } impl EagerPseudoCascadeInputs { /// Construct inputs from previous cascade results, if any. fn new_from_style(styles: &EagerPseudoStyles) -> Self { EagerPseudoCascadeInputs(styles.as_optional_array().map(|styles| { let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default(); for i in 0..EAGER_PSEUDO_COUNT { inputs[i] = styles[i].as_ref().map(|s| CascadeInputs::new_from_style(s)); } inputs })) } /// Returns the list of rules, if they exist. pub fn into_array(self) -> Option<[Option<CascadeInputs>; EAGER_PSEUDO_COUNT]> { self.0 } } /// The cascade inputs associated with a node, including those for any /// pseudo-elements. /// /// The matching and cascading process stores them in this format temporarily /// within the `CurrentElementInfo`. At the end of the cascade, they are folded /// down into the main `ComputedValues` to reduce memory usage per element while /// still remaining accessible. #[derive(Clone, Debug)] pub struct ElementCascadeInputs { /// The element's cascade inputs. pub primary: CascadeInputs, /// A list of the inputs for the element's eagerly-cascaded pseudo-elements. pub pseudos: EagerPseudoCascadeInputs, } impl ElementCascadeInputs { /// Construct inputs from previous cascade results, if any. pub fn new_from_element_data(data: &ElementData) -> Self { debug_assert!(data.has_styles()); ElementCascadeInputs { primary: CascadeInputs::new_from_style(data.styles.primary()), pseudos: EagerPseudoCascadeInputs::new_from_style(&data.styles.pseudos), } } } /// Information about the current element being processed. We group this /// together into a single struct within ThreadLocalStyleContext so that we can /// instantiate and destroy it easily at the beginning and end of element /// processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we /// only use this for identity checks, but we could use SendElement if there /// were a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] #[cfg(feature = "servo")] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each /// thread and then combine them after the threads join via the Add /// implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// The number of styles reused via rule node comparison from the /// StyleSharingCache. pub styles_reused: u32, /// The number of selectors in the stylist. pub selectors: u32, /// The number of revalidation selectors. pub revalidation_selectors: u32, /// The number of state/attr dependencies in the dependency set. pub dependency_selectors: u32, /// The number of declarations in the stylist. pub declarations: u32, /// The number of times the stylist was rebuilt. pub stylist_rebuilds: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, /// Whether this is a "large" traversal. pub is_large: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> ops::Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); debug_assert!(self.selectors == 0, "set at the end"); debug_assert!(self.revalidation_selectors == 0, "set at the end"); debug_assert!(self.dependency_selectors == 0, "set at the end"); debug_assert!(self.declarations == 0, "set at the end"); debug_assert!(self.stylist_rebuilds == 0, "set at the end"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, styles_reused: self.styles_reused + other.styles_reused, selectors: 0, revalidation_selectors: 0, dependency_selectors: 0, declarations: 0, stylist_rebuilds: 0, traversal_time_ms: 0.0, is_parallel: None, is_large: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time"); writeln!(f, "[PERF] perf block start")?; writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })?; writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)?; writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)?; writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)?; writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)?; writeln!(f, "[PERF],styles_reused,{}", self.styles_reused)?; writeln!(f, "[PERF],selectors,{}", self.selectors)?; writeln!(f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors)?; writeln!(f, "[PERF],dependency_selectors,{}", self.dependency_selectors)?; writeln!(f, "[PERF],declarations,{}", self.declarations)?; writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?; writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?; writeln!(f, "[PERF] perf block end") } } impl TraversalStatistics { /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, parallel: bool, start: f64) where E: TElement, D: DomTraversal<E>, { let threshold = traversal.shared_context().options.style_statistics_threshold; let stylist = traversal.shared_context().stylist; self.is_parallel = Some(parallel); self.is_large = Some(self.elements_traversed as usize >= threshold); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; self.selectors = stylist.num_selectors() as u32; self.revalidation_selectors = stylist.num_revalidation_selectors() as u32; self.dependency_selectors = stylist.num_invalidations() as u32; self.declarations = stylist.num_declarations() as u32; self.stylist_rebuilds = stylist.num_rebuilds() as u32; } /// Returns whether this traversal is 'large' in order to avoid console spam /// from lots of tiny traversals. pub fn is_large_traversal(&self) -> bool { self.is_large.unwrap() } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of /// UpdateAnimations which is a result of normal restyle. pub struct UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations; /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions; /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties; /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask as a result of /// animation-only restyle. pub struct PostAnimationTasks: u8 { /// Display property was changed from none in animation-only restyle so /// that we need to resolve styles for descendants in a subsequent /// normal restyle. const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01; } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Entry to avoid an unused type parameter error on servo. Unused(SendElement<E>), /// Performs one of a number of possible tasks related to updating animations based on the /// |tasks| field. These include updating CSS animations/transitions that changed as part /// of the non-animation style traversal, and updating the computed effect properties. #[cfg(feature = "gecko")] UpdateAnimations { /// The target element or pseudo-element. el: SendElement<E>, /// The before-change style for transitions. We use before-change style as the initial /// value of its Keyframe. Required if |tasks| includes CSSTransitions. before_change_style: Option<Arc<ComputedValues>>, /// The tasks which are performed in this SequentialTask. tasks: UpdateAnimationsTasks }, /// Performs one of a number of possible tasks as a result of animation-only restyle. /// Currently we do only process for resolving descendant elements that were display:none /// subtree for SMIL animation. #[cfg(feature = "gecko")] PostAnimation { /// The target element. el: SendElement<E>, /// The tasks which are performed in this SequentialTask. tasks: PostAnimationTasks }, } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == ThreadState::LAYOUT); match self { Unused(_) => unreachable!(), #[cfg(feature = "gecko")] UpdateAnimations { el, before_change_style, tasks } => { unsafe { el.update_animations(before_change_style, tasks) }; } #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { unsafe { el.process_post_animation(tasks) }; } } } /// Creates a task to update various animation-related state on /// a given (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_animations(el: E, before_change_style: Option<Arc<ComputedValues>>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations { el: unsafe { SendElement::new(el) }, before_change_style: before_change_style, tasks: tasks, } } /// Creates a task to do post-process for a given element as a result of /// animation-only restyle. #[cfg(feature = "gecko")] pub fn process_post_animation(el: E, tasks: PostAnimationTasks) -> Self { use self::SequentialTask::*; PostAnimation { el: unsafe { SendElement::new(el) }, tasks: tasks, } } } type CacheItem<E> = (SendElement<E>, ElementSelectorFlags); /// Map from Elements to ElementSelectorFlags. Used to defer applying selector /// flags until after the traversal. pub struct SelectorFlagsMap<E: TElement> { /// The hashmap storing the flags to apply. map: FnvHashMap<SendElement<E>, ElementSelectorFlags>, /// An LRU cache to avoid hashmap lookups, which can be slow if the map /// gets big. cache: LRUCache<CacheItem<E>, [Entry<CacheItem<E>>; 4 + 1]>, } #[cfg(debug_assertions)] impl<E: TElement> Drop for SelectorFlagsMap<E> { fn drop(&mut self) { debug_assert!(self.map.is_empty()); } } impl<E: TElement> SelectorFlagsMap<E> { /// Creates a new empty SelectorFlagsMap. pub fn new() -> Self
/// Inserts some flags into the map for a given element. pub fn insert_flags(&mut self, element: E, flags: ElementSelectorFlags) { let el = unsafe { SendElement::new(element) }; // Check the cache. If the flags have already been noted, we're done. if self.cache.iter().find(|&(_, ref x)| x.0 == el) .map_or(ElementSelectorFlags::empty(), |(_, x)| x.1) .contains(flags) { return; } let f = self.map.entry(el).or_insert(ElementSelectorFlags::empty()); *f |= flags; // Insert into the cache. We don't worry about duplicate entries, // which lets us avoid reshuffling. self.cache.insert((unsafe { SendElement::new(element) }, *f)) } /// Applies the flags. Must be called on the main thread. pub fn apply_flags(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for (el, flags) in self.map.drain() { unsafe { el.set_selector_flags(flags); } } } } /// A list of SequentialTasks that get executed on Drop. pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>) where E: TElement; impl<E> ops::Deref for SequentialTaskList<E> where E: TElement, { type Target = Vec<SequentialTask<E>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<E> ops::DerefMut for SequentialTaskList<E> where E: TElement, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E> Drop for SequentialTaskList<E> where E: TElement, { fn drop(&mut self) { debug_assert!(thread_state::get() == ThreadState::LAYOUT); for task in self.0.drain(..) { task.execute() } } } /// A helper type for stack limit checking. This assumes that stacks grow /// down, which is true for all non-ancient CPU architectures. pub struct StackLimitChecker { lower_limit: usize } impl StackLimitChecker { /// Create a new limit checker, for this thread, allowing further use /// of up to |stack_size| bytes beyond (below) the current stack pointer. #[inline(never)] pub fn new(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = StackLimitChecker::get_sp(); // Do some sanity-checking to ensure that our invariants hold, even in // the case where we've exceeded the soft limit. // // The correctness of depends on the assumption that no stack wraps // around the end of the address space. if cfg!(debug_assertions) { // Compute the actual bottom of the stack by subtracting our safety // margin from our soft limit. Note that this will be slightly below // the actual bottom of the stack, because there are a few initial // frames on the stack before we do the measurement that computes // the limit. let stack_bottom = self.lower_limit - STACK_SAFETY_MARGIN_KB * 1024; // The bottom of the stack should be below the current sp. If it // isn't, that means we've either waited too long to check the limit // and burned through our safety margin (in which case we probably // would have segfaulted by now), or we're using a limit computed for // a different thread. debug_assert!(stack_bottom < curr_sp); // Compute the distance between the current sp and the bottom of // the stack, and compare it against the current stack. It should be // no further from us than the total stack size. We allow some slop // to handle the fact that stack_bottom is a bit further than the // bottom of the stack, as discussed above. let distance_to_stack_bottom = curr_sp - stack_bottom; let max_allowable_distance = (STYLE_THREAD_STACK_SIZE_KB + 10) * 1024; debug_assert!(distance_to_stack_bottom <= max_allowable_distance); } // The actual bounds check. curr_sp <= self.lower_limit } // Technically, rustc can optimize this away, but shouldn't for now. // We should fix this once black_box is stable. #[inline(always)] fn get_sp() -> usize { let mut foo: usize = 42; (&mut foo as *mut usize) as usize } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able
{ SelectorFlagsMap { map: FnvHashMap::default(), cache: LRUCache::default(), } }
identifier_body
db-restore.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use backup_cli::{ backup_types::{ epoch_ending::restore::{EpochEndingRestoreController, EpochEndingRestoreOpt}, state_snapshot::restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt}, transaction::restore::{TransactionRestoreController, TransactionRestoreOpt}, }, coordinators::restore::{RestoreCoordinator, RestoreCoordinatorOpt}, storage::StorageOpt, utils::{GlobalRestoreOpt, GlobalRestoreOptions}, }; use diem_logger::{prelude::*, Level, Logger}; use diem_secure_push_metrics::MetricsPusher; use std::convert::TryInto; use structopt::StructOpt; #[derive(StructOpt)] struct Opt { #[structopt(flatten)] global: GlobalRestoreOpt, #[structopt(subcommand)] restore_type: RestoreType, } #[derive(StructOpt)] enum RestoreType {
EpochEnding { #[structopt(flatten)] opt: EpochEndingRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, StateSnapshot { #[structopt(flatten)] opt: StateSnapshotRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, Transaction { #[structopt(flatten)] opt: TransactionRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, Auto { #[structopt(flatten)] opt: RestoreCoordinatorOpt, #[structopt(subcommand)] storage: StorageOpt, }, } #[tokio::main] async fn main() -> Result<()> { main_impl().await.map_err(|e| { error!("main_impl() failed: {}", e); e }) } async fn main_impl() -> Result<()> { Logger::new().level(Level::Info).read_env().init(); let _mp = MetricsPusher::start(); let opt = Opt::from_args(); let global_opt: GlobalRestoreOptions = opt.global.clone().try_into()?; match opt.restore_type { RestoreType::EpochEnding { opt, storage } => { EpochEndingRestoreController::new(opt, global_opt, storage.init_storage().await?) .run(None) .await?; } RestoreType::StateSnapshot { opt, storage } => { StateSnapshotRestoreController::new( opt, global_opt, storage.init_storage().await?, None, /* epoch_history */ ) .run() .await?; } RestoreType::Transaction { opt, storage } => { TransactionRestoreController::new( opt, global_opt, storage.init_storage().await?, None, /* epoch_history */ ) .run() .await?; } RestoreType::Auto { opt, storage } => { RestoreCoordinator::new(opt, global_opt, storage.init_storage().await?) .run() .await?; } } Ok(()) }
random_line_split
db-restore.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use backup_cli::{ backup_types::{ epoch_ending::restore::{EpochEndingRestoreController, EpochEndingRestoreOpt}, state_snapshot::restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt}, transaction::restore::{TransactionRestoreController, TransactionRestoreOpt}, }, coordinators::restore::{RestoreCoordinator, RestoreCoordinatorOpt}, storage::StorageOpt, utils::{GlobalRestoreOpt, GlobalRestoreOptions}, }; use diem_logger::{prelude::*, Level, Logger}; use diem_secure_push_metrics::MetricsPusher; use std::convert::TryInto; use structopt::StructOpt; #[derive(StructOpt)] struct Opt { #[structopt(flatten)] global: GlobalRestoreOpt, #[structopt(subcommand)] restore_type: RestoreType, } #[derive(StructOpt)] enum RestoreType { EpochEnding { #[structopt(flatten)] opt: EpochEndingRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, StateSnapshot { #[structopt(flatten)] opt: StateSnapshotRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, Transaction { #[structopt(flatten)] opt: TransactionRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, Auto { #[structopt(flatten)] opt: RestoreCoordinatorOpt, #[structopt(subcommand)] storage: StorageOpt, }, } #[tokio::main] async fn
() -> Result<()> { main_impl().await.map_err(|e| { error!("main_impl() failed: {}", e); e }) } async fn main_impl() -> Result<()> { Logger::new().level(Level::Info).read_env().init(); let _mp = MetricsPusher::start(); let opt = Opt::from_args(); let global_opt: GlobalRestoreOptions = opt.global.clone().try_into()?; match opt.restore_type { RestoreType::EpochEnding { opt, storage } => { EpochEndingRestoreController::new(opt, global_opt, storage.init_storage().await?) .run(None) .await?; } RestoreType::StateSnapshot { opt, storage } => { StateSnapshotRestoreController::new( opt, global_opt, storage.init_storage().await?, None, /* epoch_history */ ) .run() .await?; } RestoreType::Transaction { opt, storage } => { TransactionRestoreController::new( opt, global_opt, storage.init_storage().await?, None, /* epoch_history */ ) .run() .await?; } RestoreType::Auto { opt, storage } => { RestoreCoordinator::new(opt, global_opt, storage.init_storage().await?) .run() .await?; } } Ok(()) }
main
identifier_name
db-restore.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use backup_cli::{ backup_types::{ epoch_ending::restore::{EpochEndingRestoreController, EpochEndingRestoreOpt}, state_snapshot::restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt}, transaction::restore::{TransactionRestoreController, TransactionRestoreOpt}, }, coordinators::restore::{RestoreCoordinator, RestoreCoordinatorOpt}, storage::StorageOpt, utils::{GlobalRestoreOpt, GlobalRestoreOptions}, }; use diem_logger::{prelude::*, Level, Logger}; use diem_secure_push_metrics::MetricsPusher; use std::convert::TryInto; use structopt::StructOpt; #[derive(StructOpt)] struct Opt { #[structopt(flatten)] global: GlobalRestoreOpt, #[structopt(subcommand)] restore_type: RestoreType, } #[derive(StructOpt)] enum RestoreType { EpochEnding { #[structopt(flatten)] opt: EpochEndingRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, StateSnapshot { #[structopt(flatten)] opt: StateSnapshotRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, Transaction { #[structopt(flatten)] opt: TransactionRestoreOpt, #[structopt(subcommand)] storage: StorageOpt, }, Auto { #[structopt(flatten)] opt: RestoreCoordinatorOpt, #[structopt(subcommand)] storage: StorageOpt, }, } #[tokio::main] async fn main() -> Result<()>
async fn main_impl() -> Result<()> { Logger::new().level(Level::Info).read_env().init(); let _mp = MetricsPusher::start(); let opt = Opt::from_args(); let global_opt: GlobalRestoreOptions = opt.global.clone().try_into()?; match opt.restore_type { RestoreType::EpochEnding { opt, storage } => { EpochEndingRestoreController::new(opt, global_opt, storage.init_storage().await?) .run(None) .await?; } RestoreType::StateSnapshot { opt, storage } => { StateSnapshotRestoreController::new( opt, global_opt, storage.init_storage().await?, None, /* epoch_history */ ) .run() .await?; } RestoreType::Transaction { opt, storage } => { TransactionRestoreController::new( opt, global_opt, storage.init_storage().await?, None, /* epoch_history */ ) .run() .await?; } RestoreType::Auto { opt, storage } => { RestoreCoordinator::new(opt, global_opt, storage.init_storage().await?) .run() .await?; } } Ok(()) }
{ main_impl().await.map_err(|e| { error!("main_impl() failed: {}", e); e }) }
identifier_body
main.rs
#![warn(rust_2018_idioms)] // while we're getting used to 2018 #![cfg_attr(feature = "deny-warnings", deny(warnings))] #![allow(clippy::blacklisted_name)] #![allow(clippy::explicit_iter_loop)] #![allow(clippy::redundant_closure)] #![allow(clippy::blocks_in_if_conditions)] // clippy doesn't agree with rustfmt 😂 #![allow(clippy::inefficient_to_string)] // this causes suggestions that result in `(*s).to_string()` #![warn(clippy::needless_borrow)] #![warn(clippy::redundant_clone)] #[macro_use] extern crate cargo_test_macro; mod advanced_env; mod alt_registry; mod bad_config; mod bad_manifest_path; mod bench; mod build; mod build_plan; mod build_script; mod build_script_env; mod build_script_extra_link_arg; mod cache_messages; mod cargo_alias_config; mod cargo_command; mod cargo_features; mod cargo_targets; mod cfg; mod check; mod clean; mod collisions; mod concurrent; mod config; mod config_cli; mod config_include; mod corrupt_git; mod cross_compile; mod cross_publish; mod custom_target; mod death; mod dep_info; mod directory; mod doc; mod edition; mod error; mod features; mod features2; mod features_namespaced; mod fetch; mod fix; mod freshness; mod generate_lockfile; mod git; mod git_auth; mod git_gc; mod glob_targets; mod help; mod init; mod install; mod install_upgrade; mod jobserver; mod list_availables; mod local_registry; mod locate_project; mod lockfile_compat; mod login; mod lto; mod member_discovery; mod member_errors; mod message_format; mod metabuild; mod metadata; mod minimal_versions; mod multitarget; mod net_config; mod new; mod offline; mod out_dir; mod owner; mod package; mod package_features; mod patch; mod path; mod paths; mod pkgid; mod plugins; mod proc_macro; mod profile_config; mod profile_custom; mod profile_overrides; mod profile_targets; mod profiles; mod progress; mod pub_priv; mod publish; mod publish_lockfile; mod read_manifest; mod registry; mod rename_deps; mod replace; mod required_features; mod run; mod rustc; mod rustc_info_cache; mod rustdoc; mod rustdoc_extern_html;
mod shell_quoting; mod standard_lib; mod test; mod timings; mod tool_paths; mod tree; mod tree_graph_features; mod unit_graph; mod update; mod vendor; mod verify_project; mod version; mod warn_on_failure; mod weak_dep_features; mod workspaces; mod yank; #[cargo_test] fn aaa_trigger_cross_compile_disabled_check() { // This triggers the cross compile disabled check to run ASAP, see #5141 cargo_test_support::cross_compile::disabled(); }
mod rustdocflags; mod rustflags; mod search;
random_line_split
main.rs
#![warn(rust_2018_idioms)] // while we're getting used to 2018 #![cfg_attr(feature = "deny-warnings", deny(warnings))] #![allow(clippy::blacklisted_name)] #![allow(clippy::explicit_iter_loop)] #![allow(clippy::redundant_closure)] #![allow(clippy::blocks_in_if_conditions)] // clippy doesn't agree with rustfmt 😂 #![allow(clippy::inefficient_to_string)] // this causes suggestions that result in `(*s).to_string()` #![warn(clippy::needless_borrow)] #![warn(clippy::redundant_clone)] #[macro_use] extern crate cargo_test_macro; mod advanced_env; mod alt_registry; mod bad_config; mod bad_manifest_path; mod bench; mod build; mod build_plan; mod build_script; mod build_script_env; mod build_script_extra_link_arg; mod cache_messages; mod cargo_alias_config; mod cargo_command; mod cargo_features; mod cargo_targets; mod cfg; mod check; mod clean; mod collisions; mod concurrent; mod config; mod config_cli; mod config_include; mod corrupt_git; mod cross_compile; mod cross_publish; mod custom_target; mod death; mod dep_info; mod directory; mod doc; mod edition; mod error; mod features; mod features2; mod features_namespaced; mod fetch; mod fix; mod freshness; mod generate_lockfile; mod git; mod git_auth; mod git_gc; mod glob_targets; mod help; mod init; mod install; mod install_upgrade; mod jobserver; mod list_availables; mod local_registry; mod locate_project; mod lockfile_compat; mod login; mod lto; mod member_discovery; mod member_errors; mod message_format; mod metabuild; mod metadata; mod minimal_versions; mod multitarget; mod net_config; mod new; mod offline; mod out_dir; mod owner; mod package; mod package_features; mod patch; mod path; mod paths; mod pkgid; mod plugins; mod proc_macro; mod profile_config; mod profile_custom; mod profile_overrides; mod profile_targets; mod profiles; mod progress; mod pub_priv; mod publish; mod publish_lockfile; mod read_manifest; mod registry; mod rename_deps; mod replace; mod required_features; mod run; mod rustc; mod rustc_info_cache; mod rustdoc; mod rustdoc_extern_html; mod rustdocflags; mod rustflags; mod search; mod shell_quoting; mod standard_lib; mod test; mod timings; mod tool_paths; mod tree; mod tree_graph_features; mod unit_graph; mod update; mod vendor; mod verify_project; mod version; mod warn_on_failure; mod weak_dep_features; mod workspaces; mod yank; #[cargo_test] fn aaa_trigger_cross_compile_disabled_check() {
// This triggers the cross compile disabled check to run ASAP, see #5141 cargo_test_support::cross_compile::disabled(); }
identifier_body
main.rs
#![warn(rust_2018_idioms)] // while we're getting used to 2018 #![cfg_attr(feature = "deny-warnings", deny(warnings))] #![allow(clippy::blacklisted_name)] #![allow(clippy::explicit_iter_loop)] #![allow(clippy::redundant_closure)] #![allow(clippy::blocks_in_if_conditions)] // clippy doesn't agree with rustfmt 😂 #![allow(clippy::inefficient_to_string)] // this causes suggestions that result in `(*s).to_string()` #![warn(clippy::needless_borrow)] #![warn(clippy::redundant_clone)] #[macro_use] extern crate cargo_test_macro; mod advanced_env; mod alt_registry; mod bad_config; mod bad_manifest_path; mod bench; mod build; mod build_plan; mod build_script; mod build_script_env; mod build_script_extra_link_arg; mod cache_messages; mod cargo_alias_config; mod cargo_command; mod cargo_features; mod cargo_targets; mod cfg; mod check; mod clean; mod collisions; mod concurrent; mod config; mod config_cli; mod config_include; mod corrupt_git; mod cross_compile; mod cross_publish; mod custom_target; mod death; mod dep_info; mod directory; mod doc; mod edition; mod error; mod features; mod features2; mod features_namespaced; mod fetch; mod fix; mod freshness; mod generate_lockfile; mod git; mod git_auth; mod git_gc; mod glob_targets; mod help; mod init; mod install; mod install_upgrade; mod jobserver; mod list_availables; mod local_registry; mod locate_project; mod lockfile_compat; mod login; mod lto; mod member_discovery; mod member_errors; mod message_format; mod metabuild; mod metadata; mod minimal_versions; mod multitarget; mod net_config; mod new; mod offline; mod out_dir; mod owner; mod package; mod package_features; mod patch; mod path; mod paths; mod pkgid; mod plugins; mod proc_macro; mod profile_config; mod profile_custom; mod profile_overrides; mod profile_targets; mod profiles; mod progress; mod pub_priv; mod publish; mod publish_lockfile; mod read_manifest; mod registry; mod rename_deps; mod replace; mod required_features; mod run; mod rustc; mod rustc_info_cache; mod rustdoc; mod rustdoc_extern_html; mod rustdocflags; mod rustflags; mod search; mod shell_quoting; mod standard_lib; mod test; mod timings; mod tool_paths; mod tree; mod tree_graph_features; mod unit_graph; mod update; mod vendor; mod verify_project; mod version; mod warn_on_failure; mod weak_dep_features; mod workspaces; mod yank; #[cargo_test] fn aaa
{ // This triggers the cross compile disabled check to run ASAP, see #5141 cargo_test_support::cross_compile::disabled(); }
_trigger_cross_compile_disabled_check()
identifier_name
unboxed-closure-sugar-region.rs
// 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
// except according to those terms. // Test interaction between unboxed closure sugar and region // parameters (should be exactly as if angle brackets were used // and regions omitted). #![feature(unboxed_closures)] #![allow(dead_code)] use std::marker; trait Foo<'a,T> { type Output; fn dummy(&'a self) -> &'a (T,Self::Output); } trait Eq<X:?Sized> { fn is_of_eq_type(&self, x: &X) -> bool { true } } impl<X:?Sized> Eq<X> for X { } fn eq<A:?Sized,B:?Sized +Eq<A>>() { } fn same_type<A,B:Eq<A>>(a: A, b: B) { } fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),Output=()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),Output=()>, Foo(isize) >(); } fn test2(x: &Foo<(isize,),Output=()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer //~^ ERROR cannot infer } fn main() { }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
unboxed-closure-sugar-region.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test interaction between unboxed closure sugar and region // parameters (should be exactly as if angle brackets were used // and regions omitted). #![feature(unboxed_closures)] #![allow(dead_code)] use std::marker; trait Foo<'a,T> { type Output; fn dummy(&'a self) -> &'a (T,Self::Output); } trait Eq<X:?Sized> { fn is_of_eq_type(&self, x: &X) -> bool { true } } impl<X:?Sized> Eq<X> for X { } fn eq<A:?Sized,B:?Sized +Eq<A>>() { } fn same_type<A,B:Eq<A>>(a: A, b: B)
fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),Output=()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),Output=()>, Foo(isize) >(); } fn test2(x: &Foo<(isize,),Output=()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer //~^ ERROR cannot infer } fn main() { }
{ }
identifier_body
unboxed-closure-sugar-region.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test interaction between unboxed closure sugar and region // parameters (should be exactly as if angle brackets were used // and regions omitted). #![feature(unboxed_closures)] #![allow(dead_code)] use std::marker; trait Foo<'a,T> { type Output; fn dummy(&'a self) -> &'a (T,Self::Output); } trait Eq<X:?Sized> { fn
(&self, x: &X) -> bool { true } } impl<X:?Sized> Eq<X> for X { } fn eq<A:?Sized,B:?Sized +Eq<A>>() { } fn same_type<A,B:Eq<A>>(a: A, b: B) { } fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. eq::< Foo<(isize,),Output=()>, Foo(isize) >(); // Here we specify'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. eq::< Foo<'static, (isize,),Output=()>, Foo(isize) >(); } fn test2(x: &Foo<(isize,),Output=()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer //~^ ERROR cannot infer } fn main() { }
is_of_eq_type
identifier_name
recursion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test enum Nil {Nil} struct Cons<T> {head:int, tail:T} trait Dot {fn dot(other:self) -> int;} impl Dot for Nil { fn dot(_:Nil) -> int {0} } impl<T:Dot> Dot for Cons<T> { fn dot(other:Cons<T>) -> int { self.head * other.head + self.tail.dot(other.tail) } } fn test<T:Dot> (n:int, i:int, first:T, second:T) ->int { match n { 0 => {first.dot(second)} // Error message should be here. It should be a type error // to instantiate `test` at a type other than T. (See #4287) _ => {test (n-1, i+1, Cons {head:2*i+1, tail:first}, Cons{head:i*i, tail:second})} } } pub fn
() { let n = test(1, 0, Nil, Nil); println!("{}", n); }
main
identifier_name
recursion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test enum Nil {Nil} struct Cons<T> {head:int, tail:T} trait Dot {fn dot(other:self) -> int;} impl Dot for Nil { fn dot(_:Nil) -> int {0} } impl<T:Dot> Dot for Cons<T> { fn dot(other:Cons<T>) -> int { self.head * other.head + self.tail.dot(other.tail) } } fn test<T:Dot> (n:int, i:int, first:T, second:T) ->int { match n { 0 => {first.dot(second)} // Error message should be here. It should be a type error // to instantiate `test` at a type other than T. (See #4287) _ => {test (n-1, i+1, Cons {head:2*i+1, tail:first}, Cons{head:i*i, tail:second})} } }
}
pub fn main() { let n = test(1, 0, Nil, Nil); println!("{}", n);
random_line_split
recursion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test enum Nil {Nil} struct Cons<T> {head:int, tail:T} trait Dot {fn dot(other:self) -> int;} impl Dot for Nil { fn dot(_:Nil) -> int {0} } impl<T:Dot> Dot for Cons<T> { fn dot(other:Cons<T>) -> int
} fn test<T:Dot> (n:int, i:int, first:T, second:T) ->int { match n { 0 => {first.dot(second)} // Error message should be here. It should be a type error // to instantiate `test` at a type other than T. (See #4287) _ => {test (n-1, i+1, Cons {head:2*i+1, tail:first}, Cons{head:i*i, tail:second})} } } pub fn main() { let n = test(1, 0, Nil, Nil); println!("{}", n); }
{ self.head * other.head + self.tail.dot(other.tail) }
identifier_body
get_global_account_data.rs
//! `GET /_matrix/client/*/user/{userId}/account_data/{type}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype use ruma_common::{api::ruma_api, events::AnyGlobalAccountDataEventContent, UserId}; use ruma_serde::Raw; ruma_api! { metadata: { description: "Gets global account data for a user.", name: "get_global_account_data", method: GET, r0_path: "/_matrix/client/r0/user/:user_id/account_data/:event_type", stable_path: "/_matrix/client/v3/user/:user_id/account_data/:event_type", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// User ID of user for whom to retrieve data. #[ruma_api(path)] pub user_id: &'a UserId, /// Type of data to retrieve. #[ruma_api(path)] pub event_type: &'a str, } response: { /// Account data content for the given type. /// /// Use `ruma_common::events::RawExt` for deserialization. #[ruma_api(body)] pub account_data: Raw<AnyGlobalAccountDataEventContent>, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given user ID and event type. pub fn new(user_id: &'a UserId, event_type: &'a str) -> Self { Self { user_id, event_type } } } impl Response { /// Creates a new `Response` with the given account data. pub fn new(account_data: Raw<AnyGlobalAccountDataEventContent>) -> Self { Self { account_data } } }
}
random_line_split
get_global_account_data.rs
//! `GET /_matrix/client/*/user/{userId}/account_data/{type}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype use ruma_common::{api::ruma_api, events::AnyGlobalAccountDataEventContent, UserId}; use ruma_serde::Raw; ruma_api! { metadata: { description: "Gets global account data for a user.", name: "get_global_account_data", method: GET, r0_path: "/_matrix/client/r0/user/:user_id/account_data/:event_type", stable_path: "/_matrix/client/v3/user/:user_id/account_data/:event_type", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// User ID of user for whom to retrieve data. #[ruma_api(path)] pub user_id: &'a UserId, /// Type of data to retrieve. #[ruma_api(path)] pub event_type: &'a str, } response: { /// Account data content for the given type. /// /// Use `ruma_common::events::RawExt` for deserialization. #[ruma_api(body)] pub account_data: Raw<AnyGlobalAccountDataEventContent>, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given user ID and event type. pub fn new(user_id: &'a UserId, event_type: &'a str) -> Self
} impl Response { /// Creates a new `Response` with the given account data. pub fn new(account_data: Raw<AnyGlobalAccountDataEventContent>) -> Self { Self { account_data } } } }
{ Self { user_id, event_type } }
identifier_body
get_global_account_data.rs
//! `GET /_matrix/client/*/user/{userId}/account_data/{type}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype use ruma_common::{api::ruma_api, events::AnyGlobalAccountDataEventContent, UserId}; use ruma_serde::Raw; ruma_api! { metadata: { description: "Gets global account data for a user.", name: "get_global_account_data", method: GET, r0_path: "/_matrix/client/r0/user/:user_id/account_data/:event_type", stable_path: "/_matrix/client/v3/user/:user_id/account_data/:event_type", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// User ID of user for whom to retrieve data. #[ruma_api(path)] pub user_id: &'a UserId, /// Type of data to retrieve. #[ruma_api(path)] pub event_type: &'a str, } response: { /// Account data content for the given type. /// /// Use `ruma_common::events::RawExt` for deserialization. #[ruma_api(body)] pub account_data: Raw<AnyGlobalAccountDataEventContent>, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given user ID and event type. pub fn new(user_id: &'a UserId, event_type: &'a str) -> Self { Self { user_id, event_type } } } impl Response { /// Creates a new `Response` with the given account data. pub fn
(account_data: Raw<AnyGlobalAccountDataEventContent>) -> Self { Self { account_data } } } }
new
identifier_name
bench.rs
/* 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/. */ use cssparser::SourceLocation; use rayon; use servo_arc::Arc; use servo_url::ServoUrl; use style::context::QuirksMode; use style::error_reporting::{ContextualParseError, ParseErrorReporter}; use style::media_queries::MediaList; use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock}; use style::rule_tree::{CascadeLevel, RuleTree, StrongRuleNode, StyleSource}; use style::shared_lock::SharedRwLock; use style::stylesheets::{CssRule, Origin, Stylesheet}; use style::thread_state::{self, ThreadState}; use test::{self, Bencher}; struct ErrorringErrorReporter; impl ParseErrorReporter for ErrorringErrorReporter { fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { panic!( "CSS error: {}\t\n{}:{} {}", url.as_str(), location.line, location.column, error ); } } struct AutoGCRuleTree<'a>(&'a RuleTree); impl<'a> AutoGCRuleTree<'a> { fn new(r: &'a RuleTree) -> Self { AutoGCRuleTree(r) } } impl<'a> Drop for AutoGCRuleTree<'a> { fn drop(&mut self) { unsafe { self.0.gc(); assert!( ::std::thread::panicking() ||!self.0.root().has_children_for_testing(), "No rule nodes other than the root shall remain!" );
} } fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> { let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); let s = Stylesheet::from_str( css, ServoUrl::parse("http://localhost").unwrap(), Origin::Author, media, lock, None, Some(&ErrorringErrorReporter), QuirksMode::NoQuirks, 0, ); let guard = s.shared_lock.read(); let rules = s.contents.rules.read_with(&guard); rules .0 .iter() .filter_map(|rule| match *rule { CssRule::Style(ref style_rule) => Some(( StyleSource::from_rule(style_rule.clone()), CascadeLevel::UserNormal, )), _ => None, }) .collect() } fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode { rule_tree.insert_ordered_rules(rules.into_iter()) } fn test_insertion_style_attribute( rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)], shared_lock: &SharedRwLock, ) -> StrongRuleNode { let mut rules = rules.to_vec(); rules.push(( StyleSource::from_declarations(Arc::new(shared_lock.wrap( PropertyDeclarationBlock::with_one( PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), Importance::Normal, ), ))), CascadeLevel::UserNormal, )); test_insertion(rule_tree, rules) } #[bench] fn bench_insertion_basic(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { test::black_box(test_insertion(&r, rules_matched.clone())); } }) } #[bench] fn bench_insertion_basic_per_element(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); test::black_box(test_insertion(&r, rules_matched.clone())); }); } #[bench] fn bench_expensive_insertion(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); // This test case tests a case where you style a bunch of siblings // matching the same rules, with a different style attribute each // one. let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } }); } #[bench] fn bench_insertion_basic_parallel(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); rayon::scope(|s| { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { test::black_box(test_insertion(&r, rules_matched.clone())); } s.spawn(|_| { for _ in 0..100 { test::black_box(test_insertion(&r, rules_matched.clone())); } }) }) } }); }); } #[bench] fn bench_expensive_insertion_parallel(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); rayon::scope(|s| { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } s.spawn(|_| { for _ in 0..100 { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } }) }) } }); }); }
}
random_line_split
bench.rs
/* 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/. */ use cssparser::SourceLocation; use rayon; use servo_arc::Arc; use servo_url::ServoUrl; use style::context::QuirksMode; use style::error_reporting::{ContextualParseError, ParseErrorReporter}; use style::media_queries::MediaList; use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock}; use style::rule_tree::{CascadeLevel, RuleTree, StrongRuleNode, StyleSource}; use style::shared_lock::SharedRwLock; use style::stylesheets::{CssRule, Origin, Stylesheet}; use style::thread_state::{self, ThreadState}; use test::{self, Bencher}; struct ErrorringErrorReporter; impl ParseErrorReporter for ErrorringErrorReporter { fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { panic!( "CSS error: {}\t\n{}:{} {}", url.as_str(), location.line, location.column, error ); } } struct AutoGCRuleTree<'a>(&'a RuleTree); impl<'a> AutoGCRuleTree<'a> { fn new(r: &'a RuleTree) -> Self { AutoGCRuleTree(r) } } impl<'a> Drop for AutoGCRuleTree<'a> { fn drop(&mut self) { unsafe { self.0.gc(); assert!( ::std::thread::panicking() ||!self.0.root().has_children_for_testing(), "No rule nodes other than the root shall remain!" ); } } } fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> { let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); let s = Stylesheet::from_str( css, ServoUrl::parse("http://localhost").unwrap(), Origin::Author, media, lock, None, Some(&ErrorringErrorReporter), QuirksMode::NoQuirks, 0, ); let guard = s.shared_lock.read(); let rules = s.contents.rules.read_with(&guard); rules .0 .iter() .filter_map(|rule| match *rule { CssRule::Style(ref style_rule) => Some(( StyleSource::from_rule(style_rule.clone()), CascadeLevel::UserNormal, )), _ => None, }) .collect() } fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode { rule_tree.insert_ordered_rules(rules.into_iter()) } fn test_insertion_style_attribute( rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)], shared_lock: &SharedRwLock, ) -> StrongRuleNode
#[bench] fn bench_insertion_basic(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { test::black_box(test_insertion(&r, rules_matched.clone())); } }) } #[bench] fn bench_insertion_basic_per_element(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); test::black_box(test_insertion(&r, rules_matched.clone())); }); } #[bench] fn bench_expensive_insertion(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); // This test case tests a case where you style a bunch of siblings // matching the same rules, with a different style attribute each // one. let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } }); } #[bench] fn bench_insertion_basic_parallel(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); rayon::scope(|s| { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { test::black_box(test_insertion(&r, rules_matched.clone())); } s.spawn(|_| { for _ in 0..100 { test::black_box(test_insertion(&r, rules_matched.clone())); } }) }) } }); }); } #[bench] fn bench_expensive_insertion_parallel(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); rayon::scope(|s| { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } s.spawn(|_| { for _ in 0..100 { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } }) }) } }); }); }
{ let mut rules = rules.to_vec(); rules.push(( StyleSource::from_declarations(Arc::new(shared_lock.wrap( PropertyDeclarationBlock::with_one( PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), Importance::Normal, ), ))), CascadeLevel::UserNormal, )); test_insertion(rule_tree, rules) }
identifier_body
bench.rs
/* 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/. */ use cssparser::SourceLocation; use rayon; use servo_arc::Arc; use servo_url::ServoUrl; use style::context::QuirksMode; use style::error_reporting::{ContextualParseError, ParseErrorReporter}; use style::media_queries::MediaList; use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock}; use style::rule_tree::{CascadeLevel, RuleTree, StrongRuleNode, StyleSource}; use style::shared_lock::SharedRwLock; use style::stylesheets::{CssRule, Origin, Stylesheet}; use style::thread_state::{self, ThreadState}; use test::{self, Bencher}; struct ErrorringErrorReporter; impl ParseErrorReporter for ErrorringErrorReporter { fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { panic!( "CSS error: {}\t\n{}:{} {}", url.as_str(), location.line, location.column, error ); } } struct AutoGCRuleTree<'a>(&'a RuleTree); impl<'a> AutoGCRuleTree<'a> { fn new(r: &'a RuleTree) -> Self { AutoGCRuleTree(r) } } impl<'a> Drop for AutoGCRuleTree<'a> { fn drop(&mut self) { unsafe { self.0.gc(); assert!( ::std::thread::panicking() ||!self.0.root().has_children_for_testing(), "No rule nodes other than the root shall remain!" ); } } } fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> { let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); let s = Stylesheet::from_str( css, ServoUrl::parse("http://localhost").unwrap(), Origin::Author, media, lock, None, Some(&ErrorringErrorReporter), QuirksMode::NoQuirks, 0, ); let guard = s.shared_lock.read(); let rules = s.contents.rules.read_with(&guard); rules .0 .iter() .filter_map(|rule| match *rule { CssRule::Style(ref style_rule) => Some(( StyleSource::from_rule(style_rule.clone()), CascadeLevel::UserNormal, )), _ => None, }) .collect() } fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode { rule_tree.insert_ordered_rules(rules.into_iter()) } fn test_insertion_style_attribute( rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)], shared_lock: &SharedRwLock, ) -> StrongRuleNode { let mut rules = rules.to_vec(); rules.push(( StyleSource::from_declarations(Arc::new(shared_lock.wrap( PropertyDeclarationBlock::with_one( PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), Importance::Normal, ), ))), CascadeLevel::UserNormal, )); test_insertion(rule_tree, rules) } #[bench] fn
(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { test::black_box(test_insertion(&r, rules_matched.clone())); } }) } #[bench] fn bench_insertion_basic_per_element(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); test::black_box(test_insertion(&r, rules_matched.clone())); }); } #[bench] fn bench_expensive_insertion(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); // This test case tests a case where you style a bunch of siblings // matching the same rules, with a different style attribute each // one. let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } }); } #[bench] fn bench_insertion_basic_parallel(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); rayon::scope(|s| { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { test::black_box(test_insertion(&r, rules_matched.clone())); } s.spawn(|_| { for _ in 0..100 { test::black_box(test_insertion(&r, rules_matched.clone())); } }) }) } }); }); } #[bench] fn bench_expensive_insertion_parallel(b: &mut Bencher) { let r = RuleTree::new(); thread_state::initialize(ThreadState::SCRIPT); let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ .baz { display: block; }", ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); rayon::scope(|s| { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } s.spawn(|_| { for _ in 0..100 { test::black_box(test_insertion_style_attribute( &r, &rules_matched, &shared_lock, )); } }) }) } }); }); }
bench_insertion_basic
identifier_name
atomic_max_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_max_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_max_acqrel<T>(dst: *mut T, src: T) -> T; struct
<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = isize; macro_rules! atomic_max_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_max_acqrel::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_max_acqrel_test1() { atomic_max_acqrel_test!(!0, 0, 0 ); } }
A
identifier_name
atomic_max_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_max_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_max_acqrel<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = isize;
($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_max_acqrel::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_max_acqrel_test1() { atomic_max_acqrel_test!(!0, 0, 0 ); } }
macro_rules! atomic_max_acqrel_test {
random_line_split
atomic_max_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_max_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_max_acqrel<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T>
} type T = isize; macro_rules! atomic_max_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_max_acqrel::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_max_acqrel_test1() { atomic_max_acqrel_test!(!0, 0, 0 ); } }
{ A { v: UnsafeCell::<T>::new(v) } }
identifier_body
lib.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. #[macro_use] extern crate quote; extern crate proc_macro; use proc_macro2::{Group, TokenStream, TokenTree}; use quote::ToTokens; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Punctuated; use syn::*; /// This crate provides a macro that can be used to append a match expression with multiple /// arms, where the tokens in the first arm, as a template, can be subsitituted and the template /// arm will be expanded into multiple arms. /// /// For example, the following code /// /// ```ignore /// match_template! { /// T = [Int, Real, Double], /// match Foo { /// EvalType::T => { panic!("{}", EvalType::T); }, /// EvalType::Other => unreachable!(), /// } /// } /// ``` /// /// generates /// /// ```ignore /// match Foo { /// EvalType::Int => { panic!("{}", EvalType::Int); }, /// EvalType::Real => { panic!("{}", EvalType::Real); }, /// EvalType::Double => { panic!("{}", EvalType::Double); }, /// EvalType::Other => unreachable!(), /// } /// ``` /// /// In addition, substitution can vary on two sides of the arms. /// /// For example, /// /// ```ignore /// match_template! { /// T = [Foo, Bar => Baz], /// match Foo { /// EvalType::T => { panic!("{}", EvalType::T); }, /// } /// } /// ``` /// /// generates /// /// ```ignore /// match Foo { /// EvalType::Foo => { panic!("{}", EvalType::Foo); }, /// EvalType::Bar => { panic!("{}", EvalType::Baz); }, /// } /// ``` /// /// Wildcard match arm is also supported (but there will be no substitution). #[proc_macro] pub fn match_template(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mt = parse_macro_input!(input as MatchTemplate); mt.expand().into() } struct
{ template_ident: Ident, substitutes: Punctuated<Substitution, Token![,]>, match_exp: Box<Expr>, template_arm: Arm, remaining_arms: Vec<Arm>, } impl Parse for MatchTemplate { fn parse(input: ParseStream<'_>) -> Result<Self> { let template_ident = input.parse()?; input.parse::<Token![=]>()?; let substitutes_tokens; bracketed!(substitutes_tokens in input); let substitutes = Punctuated::<Substitution, Token![,]>::parse_terminated(&substitutes_tokens)?; input.parse::<Token![,]>()?; let m: ExprMatch = input.parse()?; let mut arms = m.arms; arms.iter_mut().for_each(|arm| arm.comma = None); assert!(!arms.is_empty(), "Expect at least 1 match arm"); let template_arm = arms.remove(0); assert!(template_arm.guard.is_none(), "Expect no match arm guard"); Ok(Self { template_ident, substitutes, match_exp: m.expr, template_arm, remaining_arms: arms, }) } } impl MatchTemplate { fn expand(self) -> TokenStream { let Self { template_ident, substitutes, match_exp, template_arm, remaining_arms, } = self; let match_arms = substitutes.into_iter().map(|substitute| { let mut arm = template_arm.clone(); let (left_tokens, right_tokens) = match substitute { Substitution::Identical(ident) => { (ident.clone().into_token_stream(), ident.into_token_stream()) } Substitution::Map(left_ident, right_tokens) => { (left_ident.into_token_stream(), right_tokens) } }; arm.pat = replace_in_token_stream(arm.pat, &template_ident, &left_tokens); arm.body = replace_in_token_stream(arm.body, &template_ident, &right_tokens); arm }); quote! { match #match_exp { #(#match_arms,)* #(#remaining_arms,)* } } } } #[derive(Debug)] enum Substitution { Identical(Ident), Map(Ident, TokenStream), } impl Parse for Substitution { fn parse(input: ParseStream<'_>) -> Result<Self> { let left_ident = input.parse()?; let fat_arrow: Option<Token![=>]> = input.parse()?; if fat_arrow.is_some() { let mut right_tokens: Vec<TokenTree> = vec![]; while!input.peek(Token![,]) &&!input.is_empty() { right_tokens.push(input.parse()?); } Ok(Substitution::Map( left_ident, right_tokens.into_iter().collect(), )) } else { Ok(Substitution::Identical(left_ident)) } } } fn replace_in_token_stream<T: ToTokens + Parse>( input: T, from_ident: &Ident, to_tokens: &TokenStream, ) -> T { let mut tokens = TokenStream::new(); input.to_tokens(&mut tokens); let tokens: TokenStream = tokens .into_iter() .flat_map(|token| match token { TokenTree::Ident(ident) if ident == *from_ident => to_tokens.clone(), TokenTree::Group(group) => Group::new( group.delimiter(), replace_in_token_stream(group.stream(), from_ident, to_tokens), ) .into_token_stream(), other => other.into(), }) .collect(); syn::parse2(tokens).unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic() { let input = r#" T = [Int, Real, Double], match foo() { EvalType::T => { panic!("{}", EvalType::T); }, EvalType::Other => unreachable!(), } "#; let expect_output = r#" match foo() { EvalType::Int => { panic!("{}", EvalType::Int); }, EvalType::Real => { panic!("{}", EvalType::Real); }, EvalType::Double => { panic!("{}", EvalType::Double); }, EvalType::Other => unreachable!(), } "#; let expect_output_stream: TokenStream = expect_output.parse().unwrap(); let mt: MatchTemplate = syn::parse_str(input).unwrap(); let output = mt.expand(); assert_eq!(output.to_string(), expect_output_stream.to_string()); } #[test] fn test_wildcard() { let input = r#" TT = [Foo, Bar], match v { VectorValue::TT => EvalType::TT, _ => unreachable!(), } "#; let expect_output = r#" match v { VectorValue::Foo => EvalType::Foo, VectorValue::Bar => EvalType::Bar, _ => unreachable!(), } "#; let expect_output_stream: TokenStream = expect_output.parse().unwrap(); let mt: MatchTemplate = syn::parse_str(input).unwrap(); let output = mt.expand(); assert_eq!(output.to_string(), expect_output_stream.to_string()); } #[test] fn test_map() { let input = r#" TT = [Foo, Bar => Baz, Bark => <&'static Whooh>()], match v { VectorValue::TT => EvalType::TT, EvalType::Other => unreachable!(), } "#; let expect_output = r#" match v { VectorValue::Foo => EvalType::Foo, VectorValue::Bar => EvalType::Baz, VectorValue::Bark => EvalType:: < &'static Whooh>(), EvalType::Other => unreachable!(), } "#; let expect_output_stream: TokenStream = expect_output.parse().unwrap(); let mt: MatchTemplate = syn::parse_str(input).unwrap(); let output = mt.expand(); assert_eq!(output.to_string(), expect_output_stream.to_string()); } }
MatchTemplate
identifier_name
lib.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. #[macro_use] extern crate quote; extern crate proc_macro; use proc_macro2::{Group, TokenStream, TokenTree}; use quote::ToTokens; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Punctuated; use syn::*; /// This crate provides a macro that can be used to append a match expression with multiple /// arms, where the tokens in the first arm, as a template, can be subsitituted and the template /// arm will be expanded into multiple arms. /// /// For example, the following code /// /// ```ignore /// match_template! { /// T = [Int, Real, Double], /// match Foo { /// EvalType::T => { panic!("{}", EvalType::T); }, /// EvalType::Other => unreachable!(), /// } /// } /// ``` /// /// generates /// /// ```ignore /// match Foo { /// EvalType::Int => { panic!("{}", EvalType::Int); }, /// EvalType::Real => { panic!("{}", EvalType::Real); }, /// EvalType::Double => { panic!("{}", EvalType::Double); }, /// EvalType::Other => unreachable!(), /// } /// ``` /// /// In addition, substitution can vary on two sides of the arms. /// /// For example, /// /// ```ignore /// match_template! { /// T = [Foo, Bar => Baz], /// match Foo { /// EvalType::T => { panic!("{}", EvalType::T); }, /// } /// } /// ``` /// /// generates /// /// ```ignore /// match Foo { /// EvalType::Foo => { panic!("{}", EvalType::Foo); }, /// EvalType::Bar => { panic!("{}", EvalType::Baz); }, /// } /// ``` /// /// Wildcard match arm is also supported (but there will be no substitution). #[proc_macro] pub fn match_template(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mt = parse_macro_input!(input as MatchTemplate); mt.expand().into() } struct MatchTemplate { template_ident: Ident, substitutes: Punctuated<Substitution, Token![,]>, match_exp: Box<Expr>, template_arm: Arm, remaining_arms: Vec<Arm>, } impl Parse for MatchTemplate { fn parse(input: ParseStream<'_>) -> Result<Self> { let template_ident = input.parse()?; input.parse::<Token![=]>()?; let substitutes_tokens; bracketed!(substitutes_tokens in input); let substitutes = Punctuated::<Substitution, Token![,]>::parse_terminated(&substitutes_tokens)?; input.parse::<Token![,]>()?; let m: ExprMatch = input.parse()?; let mut arms = m.arms; arms.iter_mut().for_each(|arm| arm.comma = None); assert!(!arms.is_empty(), "Expect at least 1 match arm"); let template_arm = arms.remove(0); assert!(template_arm.guard.is_none(), "Expect no match arm guard"); Ok(Self { template_ident, substitutes, match_exp: m.expr, template_arm, remaining_arms: arms, }) } } impl MatchTemplate { fn expand(self) -> TokenStream { let Self { template_ident, substitutes, match_exp, template_arm, remaining_arms, } = self; let match_arms = substitutes.into_iter().map(|substitute| { let mut arm = template_arm.clone(); let (left_tokens, right_tokens) = match substitute { Substitution::Identical(ident) => { (ident.clone().into_token_stream(), ident.into_token_stream()) } Substitution::Map(left_ident, right_tokens) => { (left_ident.into_token_stream(), right_tokens) } }; arm.pat = replace_in_token_stream(arm.pat, &template_ident, &left_tokens); arm.body = replace_in_token_stream(arm.body, &template_ident, &right_tokens); arm }); quote! { match #match_exp { #(#match_arms,)* #(#remaining_arms,)* } } } } #[derive(Debug)] enum Substitution { Identical(Ident), Map(Ident, TokenStream), } impl Parse for Substitution { fn parse(input: ParseStream<'_>) -> Result<Self> { let left_ident = input.parse()?; let fat_arrow: Option<Token![=>]> = input.parse()?; if fat_arrow.is_some() { let mut right_tokens: Vec<TokenTree> = vec![]; while!input.peek(Token![,]) &&!input.is_empty() { right_tokens.push(input.parse()?); } Ok(Substitution::Map( left_ident, right_tokens.into_iter().collect(), )) } else { Ok(Substitution::Identical(left_ident)) } } } fn replace_in_token_stream<T: ToTokens + Parse>( input: T, from_ident: &Ident, to_tokens: &TokenStream, ) -> T { let mut tokens = TokenStream::new(); input.to_tokens(&mut tokens); let tokens: TokenStream = tokens .into_iter() .flat_map(|token| match token { TokenTree::Ident(ident) if ident == *from_ident => to_tokens.clone(), TokenTree::Group(group) => Group::new( group.delimiter(), replace_in_token_stream(group.stream(), from_ident, to_tokens), ) .into_token_stream(), other => other.into(), }) .collect(); syn::parse2(tokens).unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic() { let input = r#" T = [Int, Real, Double], match foo() { EvalType::T => { panic!("{}", EvalType::T); }, EvalType::Other => unreachable!(), } "#; let expect_output = r#" match foo() { EvalType::Int => { panic!("{}", EvalType::Int); }, EvalType::Real => { panic!("{}", EvalType::Real); }, EvalType::Double => { panic!("{}", EvalType::Double); }, EvalType::Other => unreachable!(), } "#; let expect_output_stream: TokenStream = expect_output.parse().unwrap(); let mt: MatchTemplate = syn::parse_str(input).unwrap(); let output = mt.expand(); assert_eq!(output.to_string(), expect_output_stream.to_string()); } #[test] fn test_wildcard() { let input = r#" TT = [Foo, Bar], match v { VectorValue::TT => EvalType::TT, _ => unreachable!(), } "#; let expect_output = r#" match v { VectorValue::Foo => EvalType::Foo,
"#; let expect_output_stream: TokenStream = expect_output.parse().unwrap(); let mt: MatchTemplate = syn::parse_str(input).unwrap(); let output = mt.expand(); assert_eq!(output.to_string(), expect_output_stream.to_string()); } #[test] fn test_map() { let input = r#" TT = [Foo, Bar => Baz, Bark => <&'static Whooh>()], match v { VectorValue::TT => EvalType::TT, EvalType::Other => unreachable!(), } "#; let expect_output = r#" match v { VectorValue::Foo => EvalType::Foo, VectorValue::Bar => EvalType::Baz, VectorValue::Bark => EvalType:: < &'static Whooh>(), EvalType::Other => unreachable!(), } "#; let expect_output_stream: TokenStream = expect_output.parse().unwrap(); let mt: MatchTemplate = syn::parse_str(input).unwrap(); let output = mt.expand(); assert_eq!(output.to_string(), expect_output_stream.to_string()); } }
VectorValue::Bar => EvalType::Bar, _ => unreachable!(), }
random_line_split
score.rs
use std::collections::HashMap; use std::cmp::Ordering; ///An enum to store whether a scale is major or minor. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Scale { Major, Minor } ///A type of staff display. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum StaffType { Piano, Normal } ///A note with accidentals. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Note { pub base: u8, pub octave: i8, pub accidentals: i8, } ///The types of possible voices. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum Voice { Unison, Split(u8) } ///A clef. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Clef { Treble, Bass, Alto } ///Attachments to individual notes. /// ///For example, ties or slurs. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Attachments { pub tie: bool, pub start_slur: bool, pub end_slur: bool, pub start_beam: bool, pub end_beam: bool, pub articulation: Vec<String>, } ///The time value for a note, chord, or rest. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct TimeValue { pub time: u8, pub dots: u8 } ///An event token to be output to lilypond. #[derive(Clone, Debug, Eq, PartialEq)] pub enum Event { KeySignature { tonic: Note, scale: Scale }, TimeSignature(u8, u8), Note { note: Note, attachments: Attachments, time: Option<TimeValue> }, Chord { notes: Vec<Note>, attachments: Attachments, time: Option<TimeValue> }, Rest(Option<TimeValue>), Silence(Option<TimeValue>), Clef(Clef), Tempo(String), MidiTempo(String), Mark(String), Bar(String), BarCheck, Literal(String), } ///One part of the score. #[derive(Clone, Debug)] pub struct Part { pub name: String, pub staff: StaffType, pub global: Vec<HashMap<Voice, Vec<Event>>>, pub staffs: HashMap<String, Vec<HashMap<Voice, Vec<Event>>>> } ///The complete score. #[derive(Clone, Debug)] pub struct Score { pub has_midi: bool, pub header: Vec<String>, pub paper: Vec<String>, pub parts: HashMap<String, Part>, } impl Note { ///Convert a character into a note number. pub fn char_to_note(c: char) -> Option<u8> { "abcdefg".find(c).map(|n| n as u8) } ///Convert a note number into a character. pub fn note_to_char(n: u8) -> Option<char> { "abcdefg".chars().nth(n as usize) } } impl Part { ///Create a new, empty part. pub fn new(name: String) -> Part { let mut unison = HashMap::new(); unison.insert(Voice::Unison, Vec::new()); let mut staffs = HashMap::new(); staffs.insert("n".to_string(), vec![unison.clone()]); Part { name: name, global: vec![unison], staff: StaffType::Normal, staffs: staffs, } } ///Gets the staff associated with a given tag (or the global context). pub fn get_staff(&mut self, staff: &Option<String>) -> Option<&mut Vec<HashMap<Voice, Vec<Event>>>> { match *staff { None => Some(&mut self.global), Some(ref staff) => self.staffs.get_mut(staff) } } } impl Default for Attachments { fn
() -> Attachments { Attachments { tie: false, start_slur: false, end_slur: false, start_beam: false, end_beam: false, articulation: Vec::new(), } } } impl Ord for Voice { fn cmp(&self, other: &Voice) -> Ordering { match *self { Voice::Unison => match *other { Voice::Unison => Ordering::Equal, _ => Ordering::Less }, Voice::Split(a) => match *other { Voice::Unison => Ordering::Greater, Voice::Split(b) => a.cmp(&b) } } } } impl PartialOrd for Voice { fn partial_cmp(&self, other: &Voice) -> Option<Ordering> { Some(self.cmp(other)) } }
default
identifier_name
score.rs
use std::collections::HashMap; use std::cmp::Ordering; ///An enum to store whether a scale is major or minor.
} ///A type of staff display. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum StaffType { Piano, Normal } ///A note with accidentals. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Note { pub base: u8, pub octave: i8, pub accidentals: i8, } ///The types of possible voices. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum Voice { Unison, Split(u8) } ///A clef. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Clef { Treble, Bass, Alto } ///Attachments to individual notes. /// ///For example, ties or slurs. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Attachments { pub tie: bool, pub start_slur: bool, pub end_slur: bool, pub start_beam: bool, pub end_beam: bool, pub articulation: Vec<String>, } ///The time value for a note, chord, or rest. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct TimeValue { pub time: u8, pub dots: u8 } ///An event token to be output to lilypond. #[derive(Clone, Debug, Eq, PartialEq)] pub enum Event { KeySignature { tonic: Note, scale: Scale }, TimeSignature(u8, u8), Note { note: Note, attachments: Attachments, time: Option<TimeValue> }, Chord { notes: Vec<Note>, attachments: Attachments, time: Option<TimeValue> }, Rest(Option<TimeValue>), Silence(Option<TimeValue>), Clef(Clef), Tempo(String), MidiTempo(String), Mark(String), Bar(String), BarCheck, Literal(String), } ///One part of the score. #[derive(Clone, Debug)] pub struct Part { pub name: String, pub staff: StaffType, pub global: Vec<HashMap<Voice, Vec<Event>>>, pub staffs: HashMap<String, Vec<HashMap<Voice, Vec<Event>>>> } ///The complete score. #[derive(Clone, Debug)] pub struct Score { pub has_midi: bool, pub header: Vec<String>, pub paper: Vec<String>, pub parts: HashMap<String, Part>, } impl Note { ///Convert a character into a note number. pub fn char_to_note(c: char) -> Option<u8> { "abcdefg".find(c).map(|n| n as u8) } ///Convert a note number into a character. pub fn note_to_char(n: u8) -> Option<char> { "abcdefg".chars().nth(n as usize) } } impl Part { ///Create a new, empty part. pub fn new(name: String) -> Part { let mut unison = HashMap::new(); unison.insert(Voice::Unison, Vec::new()); let mut staffs = HashMap::new(); staffs.insert("n".to_string(), vec![unison.clone()]); Part { name: name, global: vec![unison], staff: StaffType::Normal, staffs: staffs, } } ///Gets the staff associated with a given tag (or the global context). pub fn get_staff(&mut self, staff: &Option<String>) -> Option<&mut Vec<HashMap<Voice, Vec<Event>>>> { match *staff { None => Some(&mut self.global), Some(ref staff) => self.staffs.get_mut(staff) } } } impl Default for Attachments { fn default() -> Attachments { Attachments { tie: false, start_slur: false, end_slur: false, start_beam: false, end_beam: false, articulation: Vec::new(), } } } impl Ord for Voice { fn cmp(&self, other: &Voice) -> Ordering { match *self { Voice::Unison => match *other { Voice::Unison => Ordering::Equal, _ => Ordering::Less }, Voice::Split(a) => match *other { Voice::Unison => Ordering::Greater, Voice::Split(b) => a.cmp(&b) } } } } impl PartialOrd for Voice { fn partial_cmp(&self, other: &Voice) -> Option<Ordering> { Some(self.cmp(other)) } }
#[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Scale { Major, Minor
random_line_split
lib.rs
extern crate regex; pub mod errors; pub mod known_hosts; pub mod launchagent; pub mod ssh_config; #[macro_use] extern crate error_chain; use std::collections::HashMap; use std::fs::File;
use errors::*; use regex::Regex; pub enum Condition { Include(Regex), Exclude(Regex), Everything, // TODO: do we need this? } impl Condition { pub fn exclude_from(spec: &str) -> Result<(PathBuf, Condition)> { let mut split = spec.splitn(2, ','); let path = PathBuf::from( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ); let cond = Condition::Exclude( Regex::new( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ) .chain_err(|| "could not parse the host regex")?, ); Ok((path, cond)) } pub fn include_from(spec: &str) -> Result<(PathBuf, Condition)> { let mut split = spec.splitn(2, ','); let path = PathBuf::from( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ); let cond = Condition::Include( Regex::new( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ) .chain_err(|| "could not parse the host regex")?, ); Ok((path, cond)) } } #[derive(Default)] pub struct Conditions { map: HashMap<PathBuf, Vec<Condition>>, } impl Conditions { pub fn add(&mut self, path: PathBuf, cond: Condition) { let v = self.map.entry(path).or_insert_with(|| vec![]); v.push(cond); } pub fn eligible(&self, host: &Host) -> bool { let mut default = true; match self.map.get(&host.from) { None => { return true; } Some(conds) => { for cond in conds.iter() { match cond { Condition::Everything => { return true; } Condition::Include(ref pat) => { if pat.is_match(&host.name) { return true; } default = false; } Condition::Exclude(ref pat) => { if pat.is_match(&host.name) { return false; } } } } } } default } } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Host { name: String, protocol: String, from: PathBuf, } impl Host { pub fn new(name: &str, protocol: &str, from: &Path) -> Host { Host { name: name.to_string(), protocol: protocol.to_string(), from: from.to_path_buf(), } } pub fn named(name: &str, from: &Path) -> Host { Host { name: name.to_string(), protocol: "ssh".to_string(), from: from.to_path_buf(), } } pub fn write_bookmark(&self, dir: &Path) -> Result<()> { let name = format!("{} ({}).webloc", self.name, self.protocol); let namepart = Path::new(&name); let mut path = PathBuf::from(dir); if namepart.is_absolute() { bail!(ErrorKind::NameError( self.name.to_string(), self.protocol.to_string() )); } path.push(namepart); let mut bookmark_text = String::new(); bookmark_text.push_str(self.protocol.as_str()); bookmark_text.push_str("://"); bookmark_text.push_str(self.name.as_str()); let bookmark = format!(r#"<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"><dict><key>URL</key><string>{}</string></dict></plist> "#, bookmark_text); let mut f = try!(File::create(path)); try!(f.write_all(bookmark.as_bytes())); Ok(()) } pub fn ineligible(&self, conds: &Conditions) -> bool { self.name.contains('*') || self.name.contains('?') ||!conds.eligible(self) } } pub trait ConfigFile { fn pathname(&self) -> &Path; fn parse_entries<R: BufRead>(&self, r: R) -> Result<Vec<Host>>; fn entries(&self) -> Result<Vec<Host>> { let f = try!(File::open(self.pathname())); let file = BufReader::new(&f); self.parse_entries(file) } } pub fn process<T>(pathnames: Vec<String>) -> Result<Vec<Host>> where T: From<PathBuf> + ConfigFile, { let mut hosts: Vec<Host> = vec![]; for pn in pathnames { let path = PathBuf::from(pn); let file = T::from(path); match file.entries() { Ok(entries) => hosts.extend(entries), Err(e) => println!( "Could not read config file {:?} ({}), continuing", file.pathname(), e ), } } Ok(hosts) } #[test] fn test_host_creation() { let from = Path::new("/dev/null"); let ohai = Host::named("ohai", from); assert_eq!(ohai.name, "ohai"); assert_eq!(ohai.protocol, "ssh"); assert_eq!(ohai.from, from); let mosh_ohai = Host::new("ohai", "mosh", from); assert_eq!(mosh_ohai.name, "ohai"); assert_eq!(mosh_ohai.protocol, "mosh"); assert_eq!(mosh_ohai.from, from); } #[test] fn test_host_eligibility() { let from = Path::new("/dev/null"); let conds = Conditions::default(); assert_eq!( Host::named("foo*.oink.example.com", from).ineligible(&conds), true ); assert_eq!(Host::named("*", from).ineligible(&conds), true); assert_eq!( Host::named("foobar.oink.example.com", from).ineligible(&conds), false ); } #[test] fn test_conditions_match() { let from = Path::new("/dev/null"); let host = Host::named("foo.bar.com", from); // empty conditions means the host goes in: { let conds = Conditions::default(); assert!(conds.eligible(&host)); } // An include for the host means the host goes in: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Include(Regex::new(r"^foo\.").unwrap()), ); assert!(conds.eligible(&host)); } // An exclude for the host means the host is not included: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^foo\.").unwrap()), ); assert!(!conds.eligible(&host)); } // An exclude for another host means the host is in: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^baz\.").unwrap()), ); assert!(conds.eligible(&host)); } // An exclude and an include that both don't match mean that the host is not included: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^baz\.").unwrap()), ); conds.add( from.to_path_buf(), Condition::Include(Regex::new(r"^qux\.").unwrap()), ); assert!(!conds.eligible(&host)); } }
use std::io::prelude::*; use std::io::BufReader; use std::path::{Path, PathBuf};
random_line_split
lib.rs
extern crate regex; pub mod errors; pub mod known_hosts; pub mod launchagent; pub mod ssh_config; #[macro_use] extern crate error_chain; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::{Path, PathBuf}; use errors::*; use regex::Regex; pub enum Condition { Include(Regex), Exclude(Regex), Everything, // TODO: do we need this? } impl Condition { pub fn exclude_from(spec: &str) -> Result<(PathBuf, Condition)> { let mut split = spec.splitn(2, ','); let path = PathBuf::from( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ); let cond = Condition::Exclude( Regex::new( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ) .chain_err(|| "could not parse the host regex")?, ); Ok((path, cond)) } pub fn include_from(spec: &str) -> Result<(PathBuf, Condition)> { let mut split = spec.splitn(2, ','); let path = PathBuf::from( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ); let cond = Condition::Include( Regex::new( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ) .chain_err(|| "could not parse the host regex")?, ); Ok((path, cond)) } } #[derive(Default)] pub struct Conditions { map: HashMap<PathBuf, Vec<Condition>>, } impl Conditions { pub fn add(&mut self, path: PathBuf, cond: Condition) { let v = self.map.entry(path).or_insert_with(|| vec![]); v.push(cond); } pub fn eligible(&self, host: &Host) -> bool { let mut default = true; match self.map.get(&host.from) { None => { return true; } Some(conds) => { for cond in conds.iter() { match cond { Condition::Everything => { return true; } Condition::Include(ref pat) => { if pat.is_match(&host.name) { return true; } default = false; } Condition::Exclude(ref pat) => { if pat.is_match(&host.name) { return false; } } } } } } default } } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Host { name: String, protocol: String, from: PathBuf, } impl Host { pub fn new(name: &str, protocol: &str, from: &Path) -> Host { Host { name: name.to_string(), protocol: protocol.to_string(), from: from.to_path_buf(), } } pub fn named(name: &str, from: &Path) -> Host { Host { name: name.to_string(), protocol: "ssh".to_string(), from: from.to_path_buf(), } } pub fn write_bookmark(&self, dir: &Path) -> Result<()> { let name = format!("{} ({}).webloc", self.name, self.protocol); let namepart = Path::new(&name); let mut path = PathBuf::from(dir); if namepart.is_absolute() { bail!(ErrorKind::NameError( self.name.to_string(), self.protocol.to_string() )); } path.push(namepart); let mut bookmark_text = String::new(); bookmark_text.push_str(self.protocol.as_str()); bookmark_text.push_str("://"); bookmark_text.push_str(self.name.as_str()); let bookmark = format!(r#"<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"><dict><key>URL</key><string>{}</string></dict></plist> "#, bookmark_text); let mut f = try!(File::create(path)); try!(f.write_all(bookmark.as_bytes())); Ok(()) } pub fn ineligible(&self, conds: &Conditions) -> bool { self.name.contains('*') || self.name.contains('?') ||!conds.eligible(self) } } pub trait ConfigFile { fn pathname(&self) -> &Path; fn parse_entries<R: BufRead>(&self, r: R) -> Result<Vec<Host>>; fn entries(&self) -> Result<Vec<Host>> { let f = try!(File::open(self.pathname())); let file = BufReader::new(&f); self.parse_entries(file) } } pub fn process<T>(pathnames: Vec<String>) -> Result<Vec<Host>> where T: From<PathBuf> + ConfigFile, { let mut hosts: Vec<Host> = vec![]; for pn in pathnames { let path = PathBuf::from(pn); let file = T::from(path); match file.entries() { Ok(entries) => hosts.extend(entries), Err(e) => println!( "Could not read config file {:?} ({}), continuing", file.pathname(), e ), } } Ok(hosts) } #[test] fn test_host_creation() { let from = Path::new("/dev/null"); let ohai = Host::named("ohai", from); assert_eq!(ohai.name, "ohai"); assert_eq!(ohai.protocol, "ssh"); assert_eq!(ohai.from, from); let mosh_ohai = Host::new("ohai", "mosh", from); assert_eq!(mosh_ohai.name, "ohai"); assert_eq!(mosh_ohai.protocol, "mosh"); assert_eq!(mosh_ohai.from, from); } #[test] fn
() { let from = Path::new("/dev/null"); let conds = Conditions::default(); assert_eq!( Host::named("foo*.oink.example.com", from).ineligible(&conds), true ); assert_eq!(Host::named("*", from).ineligible(&conds), true); assert_eq!( Host::named("foobar.oink.example.com", from).ineligible(&conds), false ); } #[test] fn test_conditions_match() { let from = Path::new("/dev/null"); let host = Host::named("foo.bar.com", from); // empty conditions means the host goes in: { let conds = Conditions::default(); assert!(conds.eligible(&host)); } // An include for the host means the host goes in: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Include(Regex::new(r"^foo\.").unwrap()), ); assert!(conds.eligible(&host)); } // An exclude for the host means the host is not included: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^foo\.").unwrap()), ); assert!(!conds.eligible(&host)); } // An exclude for another host means the host is in: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^baz\.").unwrap()), ); assert!(conds.eligible(&host)); } // An exclude and an include that both don't match mean that the host is not included: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^baz\.").unwrap()), ); conds.add( from.to_path_buf(), Condition::Include(Regex::new(r"^qux\.").unwrap()), ); assert!(!conds.eligible(&host)); } }
test_host_eligibility
identifier_name
lib.rs
extern crate regex; pub mod errors; pub mod known_hosts; pub mod launchagent; pub mod ssh_config; #[macro_use] extern crate error_chain; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::{Path, PathBuf}; use errors::*; use regex::Regex; pub enum Condition { Include(Regex), Exclude(Regex), Everything, // TODO: do we need this? } impl Condition { pub fn exclude_from(spec: &str) -> Result<(PathBuf, Condition)> { let mut split = spec.splitn(2, ','); let path = PathBuf::from( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ); let cond = Condition::Exclude( Regex::new( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ) .chain_err(|| "could not parse the host regex")?, ); Ok((path, cond)) } pub fn include_from(spec: &str) -> Result<(PathBuf, Condition)> { let mut split = spec.splitn(2, ','); let path = PathBuf::from( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ); let cond = Condition::Include( Regex::new( split .next() .ok_or_else(|| ErrorKind::ConditionFormat(spec.to_string()))?, ) .chain_err(|| "could not parse the host regex")?, ); Ok((path, cond)) } } #[derive(Default)] pub struct Conditions { map: HashMap<PathBuf, Vec<Condition>>, } impl Conditions { pub fn add(&mut self, path: PathBuf, cond: Condition) { let v = self.map.entry(path).or_insert_with(|| vec![]); v.push(cond); } pub fn eligible(&self, host: &Host) -> bool { let mut default = true; match self.map.get(&host.from) { None => { return true; } Some(conds) => { for cond in conds.iter() { match cond { Condition::Everything => { return true; } Condition::Include(ref pat) => { if pat.is_match(&host.name) { return true; } default = false; } Condition::Exclude(ref pat) => { if pat.is_match(&host.name) { return false; } } } } } } default } } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Host { name: String, protocol: String, from: PathBuf, } impl Host { pub fn new(name: &str, protocol: &str, from: &Path) -> Host { Host { name: name.to_string(), protocol: protocol.to_string(), from: from.to_path_buf(), } } pub fn named(name: &str, from: &Path) -> Host { Host { name: name.to_string(), protocol: "ssh".to_string(), from: from.to_path_buf(), } } pub fn write_bookmark(&self, dir: &Path) -> Result<()> { let name = format!("{} ({}).webloc", self.name, self.protocol); let namepart = Path::new(&name); let mut path = PathBuf::from(dir); if namepart.is_absolute() { bail!(ErrorKind::NameError( self.name.to_string(), self.protocol.to_string() )); } path.push(namepart); let mut bookmark_text = String::new(); bookmark_text.push_str(self.protocol.as_str()); bookmark_text.push_str("://"); bookmark_text.push_str(self.name.as_str()); let bookmark = format!(r#"<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"><dict><key>URL</key><string>{}</string></dict></plist> "#, bookmark_text); let mut f = try!(File::create(path)); try!(f.write_all(bookmark.as_bytes())); Ok(()) } pub fn ineligible(&self, conds: &Conditions) -> bool { self.name.contains('*') || self.name.contains('?') ||!conds.eligible(self) } } pub trait ConfigFile { fn pathname(&self) -> &Path; fn parse_entries<R: BufRead>(&self, r: R) -> Result<Vec<Host>>; fn entries(&self) -> Result<Vec<Host>> { let f = try!(File::open(self.pathname())); let file = BufReader::new(&f); self.parse_entries(file) } } pub fn process<T>(pathnames: Vec<String>) -> Result<Vec<Host>> where T: From<PathBuf> + ConfigFile, { let mut hosts: Vec<Host> = vec![]; for pn in pathnames { let path = PathBuf::from(pn); let file = T::from(path); match file.entries() { Ok(entries) => hosts.extend(entries), Err(e) => println!( "Could not read config file {:?} ({}), continuing", file.pathname(), e ), } } Ok(hosts) } #[test] fn test_host_creation() { let from = Path::new("/dev/null"); let ohai = Host::named("ohai", from); assert_eq!(ohai.name, "ohai"); assert_eq!(ohai.protocol, "ssh"); assert_eq!(ohai.from, from); let mosh_ohai = Host::new("ohai", "mosh", from); assert_eq!(mosh_ohai.name, "ohai"); assert_eq!(mosh_ohai.protocol, "mosh"); assert_eq!(mosh_ohai.from, from); } #[test] fn test_host_eligibility()
#[test] fn test_conditions_match() { let from = Path::new("/dev/null"); let host = Host::named("foo.bar.com", from); // empty conditions means the host goes in: { let conds = Conditions::default(); assert!(conds.eligible(&host)); } // An include for the host means the host goes in: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Include(Regex::new(r"^foo\.").unwrap()), ); assert!(conds.eligible(&host)); } // An exclude for the host means the host is not included: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^foo\.").unwrap()), ); assert!(!conds.eligible(&host)); } // An exclude for another host means the host is in: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^baz\.").unwrap()), ); assert!(conds.eligible(&host)); } // An exclude and an include that both don't match mean that the host is not included: { let mut conds = Conditions::default(); conds.add( from.to_path_buf(), Condition::Exclude(Regex::new(r"^baz\.").unwrap()), ); conds.add( from.to_path_buf(), Condition::Include(Regex::new(r"^qux\.").unwrap()), ); assert!(!conds.eligible(&host)); } }
{ let from = Path::new("/dev/null"); let conds = Conditions::default(); assert_eq!( Host::named("foo*.oink.example.com", from).ineligible(&conds), true ); assert_eq!(Host::named("*", from).ineligible(&conds), true); assert_eq!( Host::named("foobar.oink.example.com", from).ineligible(&conds), false ); }
identifier_body
js.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `Root<T>`: a stack-based reference to a rooted DOM object. //! - `JS<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! //! `JS<T>` does not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `Root<T>`, //! which causes the JS-owned value to be uncollectable for the duration of the //! `Root` object's lifetime. A reference to the object can then be obtained //! from the `Root` object. These references are not allowed to outlive their //! originating `Root<T>`. //! use core::nonzero::NonZero; use dom::bindings::conversions::DerivedFrom; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::trace::trace_reflector; use dom::node::Node; use js::jsapi::{Heap, JSObject, JSTracer}; use js::jsval::JSVal; use layout_interface::TrustedNodeAddress; use script_task::STACK_ROOTS; use std::cell::UnsafeCell; use std::default::Default; use std::hash::{Hash, Hasher}; use std::mem; use std::ops::Deref; use std::ptr; use util::mem::HeapSizeOf; use util::task_state; /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `JS<T>` /// on the stack, the `JS<T>` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[must_root] pub struct JS<T> { ptr: NonZero<*const T>, } // JS<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl<T> HeapSizeOf for JS<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T> JS<T> { /// Returns `LayoutJS<T>` containing the same pointer. pub unsafe fn to_layout(&self) -> LayoutJS<T> { debug_assert!(task_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } } } impl<T: Reflectable> JS<T> { /// Create a JS<T> from a Root<T> /// XXX Not a great API. Should be a call on Root<T> instead #[allow(unrooted_must_root)] pub fn from_rooted(root: &Root<T>) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&**root) }, } } /// Create a JS<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&*obj) }, } } } impl<T: Reflectable> Deref for JS<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(task_state::get().is_script()); // We can only have &JS<T> from a rooted thing, so it's safe to deref // it to &T. unsafe { &**self.ptr } } } impl<T: Reflectable> JSTraceable for JS<T> { fn trace(&self, trc: *mut JSTracer) { trace_reflector(trc, "", unsafe { (**self.ptr).reflector() }); } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. #[allow_unrooted_interior] pub struct LayoutJS<T> { ptr: NonZero<*const T>, } impl<T: Castable> LayoutJS<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutJS<U> where U: Castable, T: DerivedFrom<U> { debug_assert!(task_state::get().is_layout()); unsafe { mem::transmute_copy(self) } } /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutJS<U>> where U: DerivedFrom<T> { debug_assert!(task_state::get().is_layout()); unsafe { if (*self.unsafe_get()).is::<U>()
else { None } } } } impl<T: Reflectable> LayoutJS<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { debug_assert!(task_state::get().is_layout()); (**self.ptr).reflector().get_jsobject().get() } } impl<T> Copy for LayoutJS<T> {} impl<T> PartialEq for JS<T> { fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl<T> Eq for JS<T> {} impl<T> PartialEq for LayoutJS<T> { fn eq(&self, other: &LayoutJS<T>) -> bool { self.ptr == other.ptr } } impl<T> Eq for LayoutJS<T> {} impl<T> Hash for JS<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.hash(state) } } impl<T> Hash for LayoutJS<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.hash(state) } } impl <T> Clone for JS<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: self.ptr.clone(), } } } impl <T> Clone for LayoutJS<T> { #[inline] fn clone(&self) -> LayoutJS<T> { debug_assert!(task_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } } } impl LayoutJS<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutJS<Node> { debug_assert!(task_state::get().is_layout()); let TrustedNodeAddress(addr) = inner; LayoutJS { ptr: NonZero::new(addr as *const Node), } } } /// A trait to be implemented for JS-managed types that can be stored in /// mutable member fields. /// /// Do not implement this trait yourself. pub trait HeapGCValue: JSTraceable { } impl HeapGCValue for Heap<JSVal> { } impl<T: Reflectable> HeapGCValue for JS<T> { } /// A holder that provides interior mutability for GC-managed JSVals. /// /// Must be used in place of traditional interior mutability to ensure proper /// GC barriers are enforced. #[must_root] #[derive(JSTraceable)] pub struct MutHeapJSVal { val: UnsafeCell<Heap<JSVal>>, } impl MutHeapJSVal { /// Create a new `MutHeapJSVal`. pub fn new() -> MutHeapJSVal { debug_assert!(task_state::get().is_script()); MutHeapJSVal { val: UnsafeCell::new(Heap::default()), } } /// Set this `MutHeapJSVal` to the given value, calling write barriers as /// appropriate. pub fn set(&self, val: JSVal) { debug_assert!(task_state::get().is_script()); unsafe { let cell = self.val.get(); (*cell).set(val); } } /// Get the value in this `MutHeapJSVal`, calling read barriers as appropriate. pub fn get(&self) -> JSVal { debug_assert!(task_state::get().is_script()); unsafe { (*self.val.get()).get() } } } /// A holder that provides interior mutability for GC-managed values such as /// `JS<T>`. Essentially a `Cell<JS<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutHeap<T: HeapGCValue> { val: UnsafeCell<T>, } impl<T: Reflectable> MutHeap<JS<T>> { /// Create a new `MutHeap`. pub fn new(initial: &T) -> MutHeap<JS<T>> { debug_assert!(task_state::get().is_script()); MutHeap { val: UnsafeCell::new(JS::from_ref(initial)), } } /// Set this `MutHeap` to the given value. pub fn set(&self, val: &T) { debug_assert!(task_state::get().is_script()); unsafe { *self.val.get() = JS::from_ref(val); } } /// Get the value in this `MutHeap`. pub fn get(&self) -> Root<T> { debug_assert!(task_state::get().is_script()); unsafe { Root::from_ref(&*ptr::read(self.val.get())) } } } impl<T: HeapGCValue> HeapSizeOf for MutHeap<T> { fn heap_size_of_children(&self) -> usize { // See comment on HeapSizeOf for JS<T>. 0 } } impl<T: Reflectable> PartialEq for MutHeap<JS<T>> { fn eq(&self, other: &Self) -> bool { unsafe { *self.val.get() == *other.val.get() } } } impl<T: Reflectable + PartialEq> PartialEq<T> for MutHeap<JS<T>> { fn eq(&self, other: &T) -> bool { unsafe { **self.val.get() == *other } } } /// A holder that provides interior mutability for GC-managed values such as /// `JS<T>`, with nullability represented by an enclosing Option wrapper. /// Essentially a `Cell<Option<JS<T>>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutNullableHeap<T: HeapGCValue> { ptr: UnsafeCell<Option<T>>, } impl<T: Reflectable> MutNullableHeap<JS<T>> { /// Create a new `MutNullableHeap`. pub fn new(initial: Option<&T>) -> MutNullableHeap<JS<T>> { debug_assert!(task_state::get().is_script()); MutNullableHeap { ptr: UnsafeCell::new(initial.map(JS::from_ref)), } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> Root<T> where F: FnOnce() -> Root<T> { debug_assert!(task_state::get().is_script()); match self.get() { Some(inner) => inner, None => { let inner = cb(); self.set(Some(&inner)); inner }, } } /// Retrieve a copy of the inner optional `JS<T>` as `LayoutJS<T>`. /// For use by layout, which can't use safe types like Temporary. #[allow(unrooted_must_root)] pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutJS<T>> { debug_assert!(task_state::get().is_layout()); ptr::read(self.ptr.get()).map(|js| js.to_layout()) } /// Get a rooted value out of this object #[allow(unrooted_must_root)] pub fn get(&self) -> Option<Root<T>> { debug_assert!(task_state::get().is_script()); unsafe { ptr::read(self.ptr.get()).map(|o| Root::from_ref(&*o)) } } /// Set this `MutNullableHeap` to the given value. pub fn set(&self, val: Option<&T>) { debug_assert!(task_state::get().is_script()); unsafe { *self.ptr.get() = val.map(|p| JS::from_ref(p)); } } } impl<T: Reflectable> PartialEq for MutNullableHeap<JS<T>> { fn eq(&self, other: &Self) -> bool { unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: Reflectable> PartialEq<Option<&'a T>> for MutNullableHeap<JS<T>> { fn eq(&self, other: &Option<&T>) -> bool { unsafe { *self.ptr.get() == other.map(JS::from_ref) } } } impl<T: HeapGCValue> Default for MutNullableHeap<T> { #[allow(unrooted_must_root)] fn default() -> MutNullableHeap<T> { debug_assert!(task_state::get().is_script()); MutNullableHeap { ptr: UnsafeCell::new(None), } } } impl<T: HeapGCValue> HeapSizeOf for MutNullableHeap<T> { fn heap_size_of_children(&self) -> usize { // See comment on HeapSizeOf for JS<T>. 0 } } impl<T: Reflectable> LayoutJS<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { debug_assert!(task_state::get().is_layout()); *self.ptr } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { /// Obtain a safe optional reference to the wrapped JS owned-value that /// cannot outlive the lifetime of this root. fn r(&self) -> Option<&T>; } impl<T: Reflectable> RootedReference<T> for Option<Root<T>> { fn r(&self) -> Option<&T> { self.as_ref().map(|root| root.r()) } } /// Get an `Option<Option<&T>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { /// Obtain a safe optional optional reference to the wrapped JS owned-value /// that cannot outlive the lifetime of this root. fn r(&self) -> Option<Option<&T>>; } impl<T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<T>>> { fn r(&self) -> Option<Option<&T>> { self.as_ref().map(|inner| inner.r()) } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { roots: UnsafeCell<Vec<*const Reflector>>, } /// A pointer to a RootCollection, for use in global variables. pub struct RootCollectionPtr(pub *const RootCollection); impl Copy for RootCollectionPtr {} impl Clone for RootCollectionPtr { fn clone(&self) -> RootCollectionPtr { *self } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { debug_assert!(task_state::get().is_script()); RootCollection { roots: UnsafeCell::new(vec![]), } } /// Start tracking a stack-based root fn root(&self, untracked_reflector: *const Reflector) { debug_assert!(task_state::get().is_script()); unsafe { let mut roots = &mut *self.roots.get(); roots.push(untracked_reflector); assert!(!(*untracked_reflector).get_jsobject().is_null()) } } /// Stop tracking a stack-based root, asserting if the reflector isn't found fn unroot<T: Reflectable>(&self, rooted: &Root<T>) { debug_assert!(task_state::get().is_script()); unsafe { let mut roots = &mut *self.roots.get(); let old_reflector = &*rooted.reflector(); match roots.iter().rposition(|r| *r == old_reflector) { Some(idx) => { roots.remove(idx); }, None => panic!("Can't remove a root that was never rooted!"), } } } } /// SM Callback that traces the rooted reflectors pub unsafe fn trace_roots(tracer: *mut JSTracer) { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); let collection = &*(*collection).roots.get(); for root in collection { trace_reflector(tracer, "reflector", &**root); } }); } /// A rooted reference to a DOM object. /// /// The JS value is pinned for the duration of this object's lifetime; roots /// are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated /// `RootCollection` object. #[allow_unrooted_interior] pub struct Root<T: Reflectable> { /// Reference to rooted value that must not outlive this container ptr: NonZero<*const T>, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl<T: Castable> Root<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: Root<T>) -> Root<U> where U: Castable, T: DerivedFrom<U> { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: Root<T>) -> Option<Root<U>> where U: DerivedFrom<T> { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) } else { None } } } impl<T: Reflectable> Root<T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it gives /// out references which cannot outlive this new `Root`. pub fn new(unrooted: NonZero<*const T>) -> Root<T> { debug_assert!(task_state::get().is_script()); STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { (*collection).root(&*(**unrooted).reflector()) } Root { ptr: unrooted, root_list: collection, } }) } /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> Root<T> { Root::new(unsafe { NonZero::new(&*unrooted) }) } /// Obtain a safe reference to the wrapped JS owned-value that cannot /// outlive the lifetime of this root. pub fn r(&self) -> &T { &**self } } impl<T: Reflectable> Deref for Root<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(task_state::get().is_script()); unsafe { &**self.ptr.deref() } } } impl<T: Reflectable> PartialEq for Root<T> { fn eq(&self, other: &Root<T>) -> bool { self.ptr == other.ptr } } impl<T: Reflectable> Drop for Root<T> { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self); } } }
{ Some(mem::transmute_copy(self)) }
conditional_block
js.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `Root<T>`: a stack-based reference to a rooted DOM object. //! - `JS<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! //! `JS<T>` does not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `Root<T>`, //! which causes the JS-owned value to be uncollectable for the duration of the //! `Root` object's lifetime. A reference to the object can then be obtained //! from the `Root` object. These references are not allowed to outlive their //! originating `Root<T>`. //! use core::nonzero::NonZero; use dom::bindings::conversions::DerivedFrom; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::trace::trace_reflector; use dom::node::Node; use js::jsapi::{Heap, JSObject, JSTracer}; use js::jsval::JSVal; use layout_interface::TrustedNodeAddress; use script_task::STACK_ROOTS; use std::cell::UnsafeCell; use std::default::Default; use std::hash::{Hash, Hasher}; use std::mem; use std::ops::Deref; use std::ptr; use util::mem::HeapSizeOf; use util::task_state; /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `JS<T>` /// on the stack, the `JS<T>` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[must_root] pub struct
<T> { ptr: NonZero<*const T>, } // JS<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl<T> HeapSizeOf for JS<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T> JS<T> { /// Returns `LayoutJS<T>` containing the same pointer. pub unsafe fn to_layout(&self) -> LayoutJS<T> { debug_assert!(task_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } } } impl<T: Reflectable> JS<T> { /// Create a JS<T> from a Root<T> /// XXX Not a great API. Should be a call on Root<T> instead #[allow(unrooted_must_root)] pub fn from_rooted(root: &Root<T>) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&**root) }, } } /// Create a JS<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&*obj) }, } } } impl<T: Reflectable> Deref for JS<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(task_state::get().is_script()); // We can only have &JS<T> from a rooted thing, so it's safe to deref // it to &T. unsafe { &**self.ptr } } } impl<T: Reflectable> JSTraceable for JS<T> { fn trace(&self, trc: *mut JSTracer) { trace_reflector(trc, "", unsafe { (**self.ptr).reflector() }); } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. #[allow_unrooted_interior] pub struct LayoutJS<T> { ptr: NonZero<*const T>, } impl<T: Castable> LayoutJS<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutJS<U> where U: Castable, T: DerivedFrom<U> { debug_assert!(task_state::get().is_layout()); unsafe { mem::transmute_copy(self) } } /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutJS<U>> where U: DerivedFrom<T> { debug_assert!(task_state::get().is_layout()); unsafe { if (*self.unsafe_get()).is::<U>() { Some(mem::transmute_copy(self)) } else { None } } } } impl<T: Reflectable> LayoutJS<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { debug_assert!(task_state::get().is_layout()); (**self.ptr).reflector().get_jsobject().get() } } impl<T> Copy for LayoutJS<T> {} impl<T> PartialEq for JS<T> { fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl<T> Eq for JS<T> {} impl<T> PartialEq for LayoutJS<T> { fn eq(&self, other: &LayoutJS<T>) -> bool { self.ptr == other.ptr } } impl<T> Eq for LayoutJS<T> {} impl<T> Hash for JS<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.hash(state) } } impl<T> Hash for LayoutJS<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.hash(state) } } impl <T> Clone for JS<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: self.ptr.clone(), } } } impl <T> Clone for LayoutJS<T> { #[inline] fn clone(&self) -> LayoutJS<T> { debug_assert!(task_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } } } impl LayoutJS<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutJS<Node> { debug_assert!(task_state::get().is_layout()); let TrustedNodeAddress(addr) = inner; LayoutJS { ptr: NonZero::new(addr as *const Node), } } } /// A trait to be implemented for JS-managed types that can be stored in /// mutable member fields. /// /// Do not implement this trait yourself. pub trait HeapGCValue: JSTraceable { } impl HeapGCValue for Heap<JSVal> { } impl<T: Reflectable> HeapGCValue for JS<T> { } /// A holder that provides interior mutability for GC-managed JSVals. /// /// Must be used in place of traditional interior mutability to ensure proper /// GC barriers are enforced. #[must_root] #[derive(JSTraceable)] pub struct MutHeapJSVal { val: UnsafeCell<Heap<JSVal>>, } impl MutHeapJSVal { /// Create a new `MutHeapJSVal`. pub fn new() -> MutHeapJSVal { debug_assert!(task_state::get().is_script()); MutHeapJSVal { val: UnsafeCell::new(Heap::default()), } } /// Set this `MutHeapJSVal` to the given value, calling write barriers as /// appropriate. pub fn set(&self, val: JSVal) { debug_assert!(task_state::get().is_script()); unsafe { let cell = self.val.get(); (*cell).set(val); } } /// Get the value in this `MutHeapJSVal`, calling read barriers as appropriate. pub fn get(&self) -> JSVal { debug_assert!(task_state::get().is_script()); unsafe { (*self.val.get()).get() } } } /// A holder that provides interior mutability for GC-managed values such as /// `JS<T>`. Essentially a `Cell<JS<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutHeap<T: HeapGCValue> { val: UnsafeCell<T>, } impl<T: Reflectable> MutHeap<JS<T>> { /// Create a new `MutHeap`. pub fn new(initial: &T) -> MutHeap<JS<T>> { debug_assert!(task_state::get().is_script()); MutHeap { val: UnsafeCell::new(JS::from_ref(initial)), } } /// Set this `MutHeap` to the given value. pub fn set(&self, val: &T) { debug_assert!(task_state::get().is_script()); unsafe { *self.val.get() = JS::from_ref(val); } } /// Get the value in this `MutHeap`. pub fn get(&self) -> Root<T> { debug_assert!(task_state::get().is_script()); unsafe { Root::from_ref(&*ptr::read(self.val.get())) } } } impl<T: HeapGCValue> HeapSizeOf for MutHeap<T> { fn heap_size_of_children(&self) -> usize { // See comment on HeapSizeOf for JS<T>. 0 } } impl<T: Reflectable> PartialEq for MutHeap<JS<T>> { fn eq(&self, other: &Self) -> bool { unsafe { *self.val.get() == *other.val.get() } } } impl<T: Reflectable + PartialEq> PartialEq<T> for MutHeap<JS<T>> { fn eq(&self, other: &T) -> bool { unsafe { **self.val.get() == *other } } } /// A holder that provides interior mutability for GC-managed values such as /// `JS<T>`, with nullability represented by an enclosing Option wrapper. /// Essentially a `Cell<Option<JS<T>>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutNullableHeap<T: HeapGCValue> { ptr: UnsafeCell<Option<T>>, } impl<T: Reflectable> MutNullableHeap<JS<T>> { /// Create a new `MutNullableHeap`. pub fn new(initial: Option<&T>) -> MutNullableHeap<JS<T>> { debug_assert!(task_state::get().is_script()); MutNullableHeap { ptr: UnsafeCell::new(initial.map(JS::from_ref)), } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> Root<T> where F: FnOnce() -> Root<T> { debug_assert!(task_state::get().is_script()); match self.get() { Some(inner) => inner, None => { let inner = cb(); self.set(Some(&inner)); inner }, } } /// Retrieve a copy of the inner optional `JS<T>` as `LayoutJS<T>`. /// For use by layout, which can't use safe types like Temporary. #[allow(unrooted_must_root)] pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutJS<T>> { debug_assert!(task_state::get().is_layout()); ptr::read(self.ptr.get()).map(|js| js.to_layout()) } /// Get a rooted value out of this object #[allow(unrooted_must_root)] pub fn get(&self) -> Option<Root<T>> { debug_assert!(task_state::get().is_script()); unsafe { ptr::read(self.ptr.get()).map(|o| Root::from_ref(&*o)) } } /// Set this `MutNullableHeap` to the given value. pub fn set(&self, val: Option<&T>) { debug_assert!(task_state::get().is_script()); unsafe { *self.ptr.get() = val.map(|p| JS::from_ref(p)); } } } impl<T: Reflectable> PartialEq for MutNullableHeap<JS<T>> { fn eq(&self, other: &Self) -> bool { unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: Reflectable> PartialEq<Option<&'a T>> for MutNullableHeap<JS<T>> { fn eq(&self, other: &Option<&T>) -> bool { unsafe { *self.ptr.get() == other.map(JS::from_ref) } } } impl<T: HeapGCValue> Default for MutNullableHeap<T> { #[allow(unrooted_must_root)] fn default() -> MutNullableHeap<T> { debug_assert!(task_state::get().is_script()); MutNullableHeap { ptr: UnsafeCell::new(None), } } } impl<T: HeapGCValue> HeapSizeOf for MutNullableHeap<T> { fn heap_size_of_children(&self) -> usize { // See comment on HeapSizeOf for JS<T>. 0 } } impl<T: Reflectable> LayoutJS<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { debug_assert!(task_state::get().is_layout()); *self.ptr } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { /// Obtain a safe optional reference to the wrapped JS owned-value that /// cannot outlive the lifetime of this root. fn r(&self) -> Option<&T>; } impl<T: Reflectable> RootedReference<T> for Option<Root<T>> { fn r(&self) -> Option<&T> { self.as_ref().map(|root| root.r()) } } /// Get an `Option<Option<&T>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { /// Obtain a safe optional optional reference to the wrapped JS owned-value /// that cannot outlive the lifetime of this root. fn r(&self) -> Option<Option<&T>>; } impl<T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<T>>> { fn r(&self) -> Option<Option<&T>> { self.as_ref().map(|inner| inner.r()) } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { roots: UnsafeCell<Vec<*const Reflector>>, } /// A pointer to a RootCollection, for use in global variables. pub struct RootCollectionPtr(pub *const RootCollection); impl Copy for RootCollectionPtr {} impl Clone for RootCollectionPtr { fn clone(&self) -> RootCollectionPtr { *self } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { debug_assert!(task_state::get().is_script()); RootCollection { roots: UnsafeCell::new(vec![]), } } /// Start tracking a stack-based root fn root(&self, untracked_reflector: *const Reflector) { debug_assert!(task_state::get().is_script()); unsafe { let mut roots = &mut *self.roots.get(); roots.push(untracked_reflector); assert!(!(*untracked_reflector).get_jsobject().is_null()) } } /// Stop tracking a stack-based root, asserting if the reflector isn't found fn unroot<T: Reflectable>(&self, rooted: &Root<T>) { debug_assert!(task_state::get().is_script()); unsafe { let mut roots = &mut *self.roots.get(); let old_reflector = &*rooted.reflector(); match roots.iter().rposition(|r| *r == old_reflector) { Some(idx) => { roots.remove(idx); }, None => panic!("Can't remove a root that was never rooted!"), } } } } /// SM Callback that traces the rooted reflectors pub unsafe fn trace_roots(tracer: *mut JSTracer) { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); let collection = &*(*collection).roots.get(); for root in collection { trace_reflector(tracer, "reflector", &**root); } }); } /// A rooted reference to a DOM object. /// /// The JS value is pinned for the duration of this object's lifetime; roots /// are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated /// `RootCollection` object. #[allow_unrooted_interior] pub struct Root<T: Reflectable> { /// Reference to rooted value that must not outlive this container ptr: NonZero<*const T>, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl<T: Castable> Root<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: Root<T>) -> Root<U> where U: Castable, T: DerivedFrom<U> { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: Root<T>) -> Option<Root<U>> where U: DerivedFrom<T> { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) } else { None } } } impl<T: Reflectable> Root<T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it gives /// out references which cannot outlive this new `Root`. pub fn new(unrooted: NonZero<*const T>) -> Root<T> { debug_assert!(task_state::get().is_script()); STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { (*collection).root(&*(**unrooted).reflector()) } Root { ptr: unrooted, root_list: collection, } }) } /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> Root<T> { Root::new(unsafe { NonZero::new(&*unrooted) }) } /// Obtain a safe reference to the wrapped JS owned-value that cannot /// outlive the lifetime of this root. pub fn r(&self) -> &T { &**self } } impl<T: Reflectable> Deref for Root<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(task_state::get().is_script()); unsafe { &**self.ptr.deref() } } } impl<T: Reflectable> PartialEq for Root<T> { fn eq(&self, other: &Root<T>) -> bool { self.ptr == other.ptr } } impl<T: Reflectable> Drop for Root<T> { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self); } } }
JS
identifier_name
js.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `Root<T>`: a stack-based reference to a rooted DOM object. //! - `JS<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! //! `JS<T>` does not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `Root<T>`, //! which causes the JS-owned value to be uncollectable for the duration of the //! `Root` object's lifetime. A reference to the object can then be obtained //! from the `Root` object. These references are not allowed to outlive their //! originating `Root<T>`. //! use core::nonzero::NonZero; use dom::bindings::conversions::DerivedFrom; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::trace::trace_reflector; use dom::node::Node; use js::jsapi::{Heap, JSObject, JSTracer}; use js::jsval::JSVal; use layout_interface::TrustedNodeAddress; use script_task::STACK_ROOTS; use std::cell::UnsafeCell; use std::default::Default; use std::hash::{Hash, Hasher}; use std::mem; use std::ops::Deref; use std::ptr; use util::mem::HeapSizeOf; use util::task_state; /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `JS<T>` /// on the stack, the `JS<T>` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[must_root] pub struct JS<T> { ptr: NonZero<*const T>, } // JS<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl<T> HeapSizeOf for JS<T> { fn heap_size_of_children(&self) -> usize { 0 } } impl<T> JS<T> { /// Returns `LayoutJS<T>` containing the same pointer. pub unsafe fn to_layout(&self) -> LayoutJS<T> { debug_assert!(task_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } } } impl<T: Reflectable> JS<T> { /// Create a JS<T> from a Root<T> /// XXX Not a great API. Should be a call on Root<T> instead #[allow(unrooted_must_root)] pub fn from_rooted(root: &Root<T>) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&**root) }, } } /// Create a JS<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&*obj) }, } } } impl<T: Reflectable> Deref for JS<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(task_state::get().is_script()); // We can only have &JS<T> from a rooted thing, so it's safe to deref // it to &T. unsafe { &**self.ptr } } } impl<T: Reflectable> JSTraceable for JS<T> { fn trace(&self, trc: *mut JSTracer) { trace_reflector(trc, "", unsafe { (**self.ptr).reflector() }); } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. #[allow_unrooted_interior] pub struct LayoutJS<T> { ptr: NonZero<*const T>, } impl<T: Castable> LayoutJS<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutJS<U> where U: Castable, T: DerivedFrom<U> { debug_assert!(task_state::get().is_layout()); unsafe { mem::transmute_copy(self) } } /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutJS<U>> where U: DerivedFrom<T> { debug_assert!(task_state::get().is_layout()); unsafe { if (*self.unsafe_get()).is::<U>() { Some(mem::transmute_copy(self)) } else { None } } } } impl<T: Reflectable> LayoutJS<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { debug_assert!(task_state::get().is_layout()); (**self.ptr).reflector().get_jsobject().get() } } impl<T> Copy for LayoutJS<T> {} impl<T> PartialEq for JS<T> { fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl<T> Eq for JS<T> {} impl<T> PartialEq for LayoutJS<T> { fn eq(&self, other: &LayoutJS<T>) -> bool { self.ptr == other.ptr } } impl<T> Eq for LayoutJS<T> {} impl<T> Hash for JS<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.hash(state) } } impl<T> Hash for LayoutJS<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.hash(state) } } impl <T> Clone for JS<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> JS<T> { debug_assert!(task_state::get().is_script()); JS { ptr: self.ptr.clone(), } } } impl <T> Clone for LayoutJS<T> { #[inline] fn clone(&self) -> LayoutJS<T> { debug_assert!(task_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } } } impl LayoutJS<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutJS<Node> { debug_assert!(task_state::get().is_layout()); let TrustedNodeAddress(addr) = inner; LayoutJS { ptr: NonZero::new(addr as *const Node), } } } /// A trait to be implemented for JS-managed types that can be stored in /// mutable member fields. /// /// Do not implement this trait yourself. pub trait HeapGCValue: JSTraceable { } impl HeapGCValue for Heap<JSVal> { } impl<T: Reflectable> HeapGCValue for JS<T> { } /// A holder that provides interior mutability for GC-managed JSVals. /// /// Must be used in place of traditional interior mutability to ensure proper /// GC barriers are enforced. #[must_root] #[derive(JSTraceable)] pub struct MutHeapJSVal { val: UnsafeCell<Heap<JSVal>>, } impl MutHeapJSVal { /// Create a new `MutHeapJSVal`. pub fn new() -> MutHeapJSVal { debug_assert!(task_state::get().is_script()); MutHeapJSVal { val: UnsafeCell::new(Heap::default()), } } /// Set this `MutHeapJSVal` to the given value, calling write barriers as /// appropriate. pub fn set(&self, val: JSVal) { debug_assert!(task_state::get().is_script()); unsafe { let cell = self.val.get(); (*cell).set(val); } } /// Get the value in this `MutHeapJSVal`, calling read barriers as appropriate. pub fn get(&self) -> JSVal { debug_assert!(task_state::get().is_script()); unsafe { (*self.val.get()).get() } } } /// A holder that provides interior mutability for GC-managed values such as /// `JS<T>`. Essentially a `Cell<JS<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutHeap<T: HeapGCValue> { val: UnsafeCell<T>, } impl<T: Reflectable> MutHeap<JS<T>> { /// Create a new `MutHeap`. pub fn new(initial: &T) -> MutHeap<JS<T>> { debug_assert!(task_state::get().is_script()); MutHeap { val: UnsafeCell::new(JS::from_ref(initial)), } } /// Set this `MutHeap` to the given value. pub fn set(&self, val: &T) { debug_assert!(task_state::get().is_script()); unsafe { *self.val.get() = JS::from_ref(val); } } /// Get the value in this `MutHeap`. pub fn get(&self) -> Root<T> { debug_assert!(task_state::get().is_script()); unsafe { Root::from_ref(&*ptr::read(self.val.get())) } } } impl<T: HeapGCValue> HeapSizeOf for MutHeap<T> { fn heap_size_of_children(&self) -> usize { // See comment on HeapSizeOf for JS<T>. 0 } } impl<T: Reflectable> PartialEq for MutHeap<JS<T>> { fn eq(&self, other: &Self) -> bool { unsafe { *self.val.get() == *other.val.get() } } } impl<T: Reflectable + PartialEq> PartialEq<T> for MutHeap<JS<T>> { fn eq(&self, other: &T) -> bool { unsafe { **self.val.get() == *other } } } /// A holder that provides interior mutability for GC-managed values such as /// `JS<T>`, with nullability represented by an enclosing Option wrapper. /// Essentially a `Cell<Option<JS<T>>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutNullableHeap<T: HeapGCValue> { ptr: UnsafeCell<Option<T>>, } impl<T: Reflectable> MutNullableHeap<JS<T>> { /// Create a new `MutNullableHeap`. pub fn new(initial: Option<&T>) -> MutNullableHeap<JS<T>> { debug_assert!(task_state::get().is_script()); MutNullableHeap { ptr: UnsafeCell::new(initial.map(JS::from_ref)), } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> Root<T> where F: FnOnce() -> Root<T> { debug_assert!(task_state::get().is_script()); match self.get() { Some(inner) => inner, None => { let inner = cb(); self.set(Some(&inner)); inner }, } } /// Retrieve a copy of the inner optional `JS<T>` as `LayoutJS<T>`. /// For use by layout, which can't use safe types like Temporary. #[allow(unrooted_must_root)] pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutJS<T>> { debug_assert!(task_state::get().is_layout()); ptr::read(self.ptr.get()).map(|js| js.to_layout()) } /// Get a rooted value out of this object #[allow(unrooted_must_root)] pub fn get(&self) -> Option<Root<T>> { debug_assert!(task_state::get().is_script()); unsafe { ptr::read(self.ptr.get()).map(|o| Root::from_ref(&*o)) } } /// Set this `MutNullableHeap` to the given value. pub fn set(&self, val: Option<&T>) { debug_assert!(task_state::get().is_script()); unsafe { *self.ptr.get() = val.map(|p| JS::from_ref(p)); } } } impl<T: Reflectable> PartialEq for MutNullableHeap<JS<T>> { fn eq(&self, other: &Self) -> bool { unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: Reflectable> PartialEq<Option<&'a T>> for MutNullableHeap<JS<T>> { fn eq(&self, other: &Option<&T>) -> bool { unsafe { *self.ptr.get() == other.map(JS::from_ref) } } } impl<T: HeapGCValue> Default for MutNullableHeap<T> { #[allow(unrooted_must_root)] fn default() -> MutNullableHeap<T> { debug_assert!(task_state::get().is_script()); MutNullableHeap { ptr: UnsafeCell::new(None), } } } impl<T: HeapGCValue> HeapSizeOf for MutNullableHeap<T> { fn heap_size_of_children(&self) -> usize { // See comment on HeapSizeOf for JS<T>. 0 } } impl<T: Reflectable> LayoutJS<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { debug_assert!(task_state::get().is_layout()); *self.ptr } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { /// Obtain a safe optional reference to the wrapped JS owned-value that /// cannot outlive the lifetime of this root. fn r(&self) -> Option<&T>; } impl<T: Reflectable> RootedReference<T> for Option<Root<T>> { fn r(&self) -> Option<&T> { self.as_ref().map(|root| root.r()) } } /// Get an `Option<Option<&T>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { /// Obtain a safe optional optional reference to the wrapped JS owned-value /// that cannot outlive the lifetime of this root. fn r(&self) -> Option<Option<&T>>; } impl<T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<T>>> { fn r(&self) -> Option<Option<&T>> { self.as_ref().map(|inner| inner.r()) } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { roots: UnsafeCell<Vec<*const Reflector>>, } /// A pointer to a RootCollection, for use in global variables. pub struct RootCollectionPtr(pub *const RootCollection); impl Copy for RootCollectionPtr {} impl Clone for RootCollectionPtr { fn clone(&self) -> RootCollectionPtr { *self } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { debug_assert!(task_state::get().is_script()); RootCollection { roots: UnsafeCell::new(vec![]),
fn root(&self, untracked_reflector: *const Reflector) { debug_assert!(task_state::get().is_script()); unsafe { let mut roots = &mut *self.roots.get(); roots.push(untracked_reflector); assert!(!(*untracked_reflector).get_jsobject().is_null()) } } /// Stop tracking a stack-based root, asserting if the reflector isn't found fn unroot<T: Reflectable>(&self, rooted: &Root<T>) { debug_assert!(task_state::get().is_script()); unsafe { let mut roots = &mut *self.roots.get(); let old_reflector = &*rooted.reflector(); match roots.iter().rposition(|r| *r == old_reflector) { Some(idx) => { roots.remove(idx); }, None => panic!("Can't remove a root that was never rooted!"), } } } } /// SM Callback that traces the rooted reflectors pub unsafe fn trace_roots(tracer: *mut JSTracer) { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); let collection = &*(*collection).roots.get(); for root in collection { trace_reflector(tracer, "reflector", &**root); } }); } /// A rooted reference to a DOM object. /// /// The JS value is pinned for the duration of this object's lifetime; roots /// are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated /// `RootCollection` object. #[allow_unrooted_interior] pub struct Root<T: Reflectable> { /// Reference to rooted value that must not outlive this container ptr: NonZero<*const T>, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl<T: Castable> Root<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: Root<T>) -> Root<U> where U: Castable, T: DerivedFrom<U> { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: Root<T>) -> Option<Root<U>> where U: DerivedFrom<T> { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) } else { None } } } impl<T: Reflectable> Root<T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it gives /// out references which cannot outlive this new `Root`. pub fn new(unrooted: NonZero<*const T>) -> Root<T> { debug_assert!(task_state::get().is_script()); STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { (*collection).root(&*(**unrooted).reflector()) } Root { ptr: unrooted, root_list: collection, } }) } /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> Root<T> { Root::new(unsafe { NonZero::new(&*unrooted) }) } /// Obtain a safe reference to the wrapped JS owned-value that cannot /// outlive the lifetime of this root. pub fn r(&self) -> &T { &**self } } impl<T: Reflectable> Deref for Root<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(task_state::get().is_script()); unsafe { &**self.ptr.deref() } } } impl<T: Reflectable> PartialEq for Root<T> { fn eq(&self, other: &Root<T>) -> bool { self.ptr == other.ptr } } impl<T: Reflectable> Drop for Root<T> { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self); } } }
} } /// Start tracking a stack-based root
random_line_split
utils.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use rustc::ast_map; use rustc::lint::Context; use rustc::middle::def; use syntax::ast; use syntax::ast::{TyPath, Path, AngleBracketedParameters, PathSegment, Ty}; use syntax::attr::mark_used; use syntax::ptr::P; /// Matches a type with a provided string, and returns its type parameters if successful /// /// Try not to use this for types defined in crates you own, use match_lang_ty instead (for lint passes) pub fn match_ty_unwrap<'a>(ty: &'a Ty, segments: &[&str]) -> Option<&'a [P<Ty>]> { match ty.node { TyPath(_, Path {segments: ref seg,..}) => { // So ast::Path isn't the full path, just the tokens that were provided. // I could muck around with the maps and find the full path // however the more efficient way is to simply reverse the iterators and zip them // which will compare them in reverse until one of them runs out of segments if seg.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b) { match seg.last() { Some(&PathSegment {parameters: AngleBracketedParameters(ref a),..}) => { Some(&a.types) } _ => None } } else { None } }, _ => None } } /// Checks if a type has a #[servo_lang = "str"] attribute pub fn match_lang_ty(cx: &Context, ty: &Ty, value: &str) -> bool { match ty.node { TyPath(..) => {}, _ => return false, } let def_id = match cx.tcx.def_map.borrow().get(&ty.id) { Some(&def::PathResolution { base_def: def::DefTy(def_id, _),.. }) => def_id, _ => return false, }; match_lang_did(cx, def_id, value) } pub fn
(cx: &Context, did: ast::DefId, value: &str) -> bool { cx.tcx.get_attrs(did).iter().any(|attr| { match attr.node.value.node { ast::MetaNameValue(ref name, ref val) if &**name == "servo_lang" => { match val.node { ast::LitStr(ref v, _) if &**v == value => { mark_used(attr); true }, _ => false, } } _ => false, } }) } // Determines if a block is in an unsafe context so that an unhelpful // lint can be aborted. pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool { match map.find(map.get_parent(id)) { Some(ast_map::NodeImplItem(itm)) => { match itm.node { ast::MethodImplItem(ref sig, _) => sig.unsafety == ast::Unsafety::Unsafe, _ => false } }, Some(ast_map::NodeItem(itm)) => { match itm.node { ast::ItemFn(_, style, _, _, _, _) => match style { ast::Unsafety::Unsafe => true, _ => false, }, _ => false, } } _ => false // There are probably a couple of other unsafe cases we don't care to lint, those will need // to be added. } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` pub fn match_def_path(cx: &Context, def_id: ast::DefId, path: &[&str]) -> bool { cx.tcx.with_path(def_id, |iter| iter.map(|elem| elem.name()) .zip(path.iter()).all(|(nm, p)| &nm.as_str() == p)) }
match_lang_did
identifier_name
utils.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use rustc::ast_map; use rustc::lint::Context; use rustc::middle::def; use syntax::ast; use syntax::ast::{TyPath, Path, AngleBracketedParameters, PathSegment, Ty}; use syntax::attr::mark_used; use syntax::ptr::P; /// Matches a type with a provided string, and returns its type parameters if successful /// /// Try not to use this for types defined in crates you own, use match_lang_ty instead (for lint passes) pub fn match_ty_unwrap<'a>(ty: &'a Ty, segments: &[&str]) -> Option<&'a [P<Ty>]> { match ty.node { TyPath(_, Path {segments: ref seg,..}) => { // So ast::Path isn't the full path, just the tokens that were provided. // I could muck around with the maps and find the full path // however the more efficient way is to simply reverse the iterators and zip them // which will compare them in reverse until one of them runs out of segments if seg.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b) { match seg.last() { Some(&PathSegment {parameters: AngleBracketedParameters(ref a),..}) => { Some(&a.types) } _ => None } } else { None
} /// Checks if a type has a #[servo_lang = "str"] attribute pub fn match_lang_ty(cx: &Context, ty: &Ty, value: &str) -> bool { match ty.node { TyPath(..) => {}, _ => return false, } let def_id = match cx.tcx.def_map.borrow().get(&ty.id) { Some(&def::PathResolution { base_def: def::DefTy(def_id, _),.. }) => def_id, _ => return false, }; match_lang_did(cx, def_id, value) } pub fn match_lang_did(cx: &Context, did: ast::DefId, value: &str) -> bool { cx.tcx.get_attrs(did).iter().any(|attr| { match attr.node.value.node { ast::MetaNameValue(ref name, ref val) if &**name == "servo_lang" => { match val.node { ast::LitStr(ref v, _) if &**v == value => { mark_used(attr); true }, _ => false, } } _ => false, } }) } // Determines if a block is in an unsafe context so that an unhelpful // lint can be aborted. pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool { match map.find(map.get_parent(id)) { Some(ast_map::NodeImplItem(itm)) => { match itm.node { ast::MethodImplItem(ref sig, _) => sig.unsafety == ast::Unsafety::Unsafe, _ => false } }, Some(ast_map::NodeItem(itm)) => { match itm.node { ast::ItemFn(_, style, _, _, _, _) => match style { ast::Unsafety::Unsafe => true, _ => false, }, _ => false, } } _ => false // There are probably a couple of other unsafe cases we don't care to lint, those will need // to be added. } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` pub fn match_def_path(cx: &Context, def_id: ast::DefId, path: &[&str]) -> bool { cx.tcx.with_path(def_id, |iter| iter.map(|elem| elem.name()) .zip(path.iter()).all(|(nm, p)| &nm.as_str() == p)) }
} }, _ => None }
random_line_split
utils.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use rustc::ast_map; use rustc::lint::Context; use rustc::middle::def; use syntax::ast; use syntax::ast::{TyPath, Path, AngleBracketedParameters, PathSegment, Ty}; use syntax::attr::mark_used; use syntax::ptr::P; /// Matches a type with a provided string, and returns its type parameters if successful /// /// Try not to use this for types defined in crates you own, use match_lang_ty instead (for lint passes) pub fn match_ty_unwrap<'a>(ty: &'a Ty, segments: &[&str]) -> Option<&'a [P<Ty>]>
} /// Checks if a type has a #[servo_lang = "str"] attribute pub fn match_lang_ty(cx: &Context, ty: &Ty, value: &str) -> bool { match ty.node { TyPath(..) => {}, _ => return false, } let def_id = match cx.tcx.def_map.borrow().get(&ty.id) { Some(&def::PathResolution { base_def: def::DefTy(def_id, _),.. }) => def_id, _ => return false, }; match_lang_did(cx, def_id, value) } pub fn match_lang_did(cx: &Context, did: ast::DefId, value: &str) -> bool { cx.tcx.get_attrs(did).iter().any(|attr| { match attr.node.value.node { ast::MetaNameValue(ref name, ref val) if &**name == "servo_lang" => { match val.node { ast::LitStr(ref v, _) if &**v == value => { mark_used(attr); true }, _ => false, } } _ => false, } }) } // Determines if a block is in an unsafe context so that an unhelpful // lint can be aborted. pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool { match map.find(map.get_parent(id)) { Some(ast_map::NodeImplItem(itm)) => { match itm.node { ast::MethodImplItem(ref sig, _) => sig.unsafety == ast::Unsafety::Unsafe, _ => false } }, Some(ast_map::NodeItem(itm)) => { match itm.node { ast::ItemFn(_, style, _, _, _, _) => match style { ast::Unsafety::Unsafe => true, _ => false, }, _ => false, } } _ => false // There are probably a couple of other unsafe cases we don't care to lint, those will need // to be added. } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` pub fn match_def_path(cx: &Context, def_id: ast::DefId, path: &[&str]) -> bool { cx.tcx.with_path(def_id, |iter| iter.map(|elem| elem.name()) .zip(path.iter()).all(|(nm, p)| &nm.as_str() == p)) }
{ match ty.node { TyPath(_, Path {segments: ref seg, ..}) => { // So ast::Path isn't the full path, just the tokens that were provided. // I could muck around with the maps and find the full path // however the more efficient way is to simply reverse the iterators and zip them // which will compare them in reverse until one of them runs out of segments if seg.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b) { match seg.last() { Some(&PathSegment {parameters: AngleBracketedParameters(ref a), ..}) => { Some(&a.types) } _ => None } } else { None } }, _ => None }
identifier_body
note_pitch.rs
// Copyright 2017 Google Inc. All rights reserved. // // 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. //! A simple module that just holds a note at a constant pitch. use module::{Module, Buffer};
pub struct NotePitch { value: f32, } impl NotePitch { pub fn new() -> NotePitch { NotePitch { value: 0.0 } } } impl Module for NotePitch { fn n_ctrl_out(&self) -> usize { 1 } fn handle_note(&mut self, midi_num: f32, _velocity: f32, on: bool) { if on { self.value = midi_num * (1.0 / 12.0) + (440f32.log2() - 69.0 / 12.0); } } fn process(&mut self, _control_in: &[f32], control_out: &mut [f32], _buf_in: &[&Buffer], _buf_out: &mut [Buffer]) { control_out[0] = self.value; } }
random_line_split
note_pitch.rs
// Copyright 2017 Google Inc. All rights reserved. // // 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. //! A simple module that just holds a note at a constant pitch. use module::{Module, Buffer}; pub struct NotePitch { value: f32, } impl NotePitch { pub fn new() -> NotePitch { NotePitch { value: 0.0 } } } impl Module for NotePitch { fn n_ctrl_out(&self) -> usize { 1 } fn handle_note(&mut self, midi_num: f32, _velocity: f32, on: bool) { if on
} fn process(&mut self, _control_in: &[f32], control_out: &mut [f32], _buf_in: &[&Buffer], _buf_out: &mut [Buffer]) { control_out[0] = self.value; } }
{ self.value = midi_num * (1.0 / 12.0) + (440f32.log2() - 69.0 / 12.0); }
conditional_block
note_pitch.rs
// Copyright 2017 Google Inc. All rights reserved. // // 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. //! A simple module that just holds a note at a constant pitch. use module::{Module, Buffer}; pub struct
{ value: f32, } impl NotePitch { pub fn new() -> NotePitch { NotePitch { value: 0.0 } } } impl Module for NotePitch { fn n_ctrl_out(&self) -> usize { 1 } fn handle_note(&mut self, midi_num: f32, _velocity: f32, on: bool) { if on { self.value = midi_num * (1.0 / 12.0) + (440f32.log2() - 69.0 / 12.0); } } fn process(&mut self, _control_in: &[f32], control_out: &mut [f32], _buf_in: &[&Buffer], _buf_out: &mut [Buffer]) { control_out[0] = self.value; } }
NotePitch
identifier_name
note_pitch.rs
// Copyright 2017 Google Inc. All rights reserved. // // 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. //! A simple module that just holds a note at a constant pitch. use module::{Module, Buffer}; pub struct NotePitch { value: f32, } impl NotePitch { pub fn new() -> NotePitch { NotePitch { value: 0.0 } } } impl Module for NotePitch { fn n_ctrl_out(&self) -> usize { 1 } fn handle_note(&mut self, midi_num: f32, _velocity: f32, on: bool)
fn process(&mut self, _control_in: &[f32], control_out: &mut [f32], _buf_in: &[&Buffer], _buf_out: &mut [Buffer]) { control_out[0] = self.value; } }
{ if on { self.value = midi_num * (1.0 / 12.0) + (440f32.log2() - 69.0 / 12.0); } }
identifier_body
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions use std::libc; use std::task; mod rustrt { use std::libc; #[link(name = "rustrt")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1u
else { count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) task::spawn(proc() { let result = count(12u); println!("result = {}", result); assert_eq!(result, 2048u); }); }
{ data }
conditional_block
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions
mod rustrt { use std::libc; #[link(name = "rustrt")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1u { data } else { count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) task::spawn(proc() { let result = count(12u); println!("result = {}", result); assert_eq!(result, 2048u); }); }
use std::libc; use std::task;
random_line_split
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions use std::libc; use std::task; mod rustrt { use std::libc; #[link(name = "rustrt")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1u { data } else { count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint
pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) task::spawn(proc() { let result = count(12u); println!("result = {}", result); assert_eq!(result, 2048u); }); }
{ unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } }
identifier_body
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions use std::libc; use std::task; mod rustrt { use std::libc; #[link(name = "rustrt")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn
(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1u { data } else { count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) task::spawn(proc() { let result = count(12u); println!("result = {}", result); assert_eq!(result, 2048u); }); }
cb
identifier_name
settings.rs
// The MIT License (MIT) // Copyright © 2014-2018 Miguel Peláez <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #[derive(Serialize, Deserialize, Debug)] pub struct WindowSettings { width: u32, height: u32, fullscreen: bool, maximized: bool, multisampling: u16, gui_scale: f64, } #[derive(Serialize, Deserialize, Debug)] pub struct GameplaySettings { fov: u8, vsync: bool, } #[derive(Serialize, Deserialize, Debug)] pub struct Settings { window: WindowSettings, gameplay: GameplaySettings, resourcepacks: Vec<String>, } impl Settings { /// Create settings with default values pub fn new() -> Settings { Settings::new_with_size(800, 600) } /// Create settings with width and height pub fn new_with_size(width: u32, height: u32) -> Settings { Settings { window: WindowSettings { width, height, fullscreen: false, maximized: true, multisampling: 0, gui_scale: 1.0, }, gameplay: GameplaySettings { fov: 90, vsync: true }, resourcepacks: Vec::new(), } } /// Get window width pub fn width(&self) -> u32 { self.window.width } /// Set window width pub fn set_width(&mut self, value: u32) { self.window.width = value } /// Get window height pub fn height(&self) -> u32 { self.window.height } /// Set window height pub fn set_height(&mut self, value: u32) { self.window.height = value } /// Get if user wants fullscreen pub fn fullscreen(&self) -> bool { self.window.fullscreen } /// Get if user wants maximized pub fn maximized(&self) -> bool { self.window.maximized } /// Get if user wants MSAA anti-aliasing pub fn multisampling(&self) -> u16 { self.window.multisampling } /// Get if user wants vsync pub fn vsync(&self) -> bool { self.gameplay.vsync } /// Get user FOV pub fn fov(&self) -> u8 { self.gameplay.fov } /// Get user GUI scale pub fn scale(&self) -> f64 { self.window.gui_scale } /// Get enabled resourcepacks by filename pub fn resourcepa
&Vec<String> { &self.resourcepacks } }
cks(&self) ->
identifier_name
settings.rs
// The MIT License (MIT) // Copyright © 2014-2018 Miguel Peláez <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #[derive(Serialize, Deserialize, Debug)] pub struct WindowSettings { width: u32, height: u32, fullscreen: bool, maximized: bool, multisampling: u16, gui_scale: f64, } #[derive(Serialize, Deserialize, Debug)] pub struct GameplaySettings { fov: u8, vsync: bool, } #[derive(Serialize, Deserialize, Debug)] pub struct Settings { window: WindowSettings, gameplay: GameplaySettings, resourcepacks: Vec<String>, } impl Settings { /// Create settings with default values pub fn new() -> Settings { Settings::new_with_size(800, 600) } /// Create settings with width and height pub fn new_with_size(width: u32, height: u32) -> Settings { Settings { window: WindowSettings { width, height,
gameplay: GameplaySettings { fov: 90, vsync: true }, resourcepacks: Vec::new(), } } /// Get window width pub fn width(&self) -> u32 { self.window.width } /// Set window width pub fn set_width(&mut self, value: u32) { self.window.width = value } /// Get window height pub fn height(&self) -> u32 { self.window.height } /// Set window height pub fn set_height(&mut self, value: u32) { self.window.height = value } /// Get if user wants fullscreen pub fn fullscreen(&self) -> bool { self.window.fullscreen } /// Get if user wants maximized pub fn maximized(&self) -> bool { self.window.maximized } /// Get if user wants MSAA anti-aliasing pub fn multisampling(&self) -> u16 { self.window.multisampling } /// Get if user wants vsync pub fn vsync(&self) -> bool { self.gameplay.vsync } /// Get user FOV pub fn fov(&self) -> u8 { self.gameplay.fov } /// Get user GUI scale pub fn scale(&self) -> f64 { self.window.gui_scale } /// Get enabled resourcepacks by filename pub fn resourcepacks(&self) -> &Vec<String> { &self.resourcepacks } }
fullscreen: false, maximized: true, multisampling: 0, gui_scale: 1.0, },
random_line_split
settings.rs
// The MIT License (MIT) // Copyright © 2014-2018 Miguel Peláez <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #[derive(Serialize, Deserialize, Debug)] pub struct WindowSettings { width: u32, height: u32, fullscreen: bool, maximized: bool, multisampling: u16, gui_scale: f64, } #[derive(Serialize, Deserialize, Debug)] pub struct GameplaySettings { fov: u8, vsync: bool, } #[derive(Serialize, Deserialize, Debug)] pub struct Settings { window: WindowSettings, gameplay: GameplaySettings, resourcepacks: Vec<String>, } impl Settings { /// Create settings with default values pub fn new() -> Settings { Settings::new_with_size(800, 600) } /// Create settings with width and height pub fn new_with_size(width: u32, height: u32) -> Settings { Settings { window: WindowSettings { width, height, fullscreen: false, maximized: true, multisampling: 0, gui_scale: 1.0, }, gameplay: GameplaySettings { fov: 90, vsync: true }, resourcepacks: Vec::new(), } } /// Get window width pub fn width(&self) -> u32 { self.window.width } /// Set window width pub fn set_width(&mut self, value: u32) { self.window.width = value } /// Get window height pub fn height(&self) -> u32 { self.window.height } /// Set window height pub fn set_height(&mut self, value: u32) { self.window.height = value } /// Get if user wants fullscreen pub fn fullscreen(&self) -> bool { self.window.fullscreen } /// Get if user wants maximized pub fn maximized(&self) -> bool { self.window.maximized } /// Get if user wants MSAA anti-aliasing pub fn multisampling(&self) -> u16 { self.window.multisampling } /// Get if user wants vsync pub fn vsync(&self) -> bool { self.gameplay.vsync } /// Get user FOV pub fn fov(&self) -> u8 { self.gam
Get user GUI scale pub fn scale(&self) -> f64 { self.window.gui_scale } /// Get enabled resourcepacks by filename pub fn resourcepacks(&self) -> &Vec<String> { &self.resourcepacks } }
eplay.fov } ///
identifier_body
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Common [values][values] used in CSS. //! //! [values]: https://drafts.csswg.org/css-values/ #![deny(missing_docs)]
use selectors::parser::SelectorParseErrorKind; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::fmt::{self, Debug}; use std::hash; use style_traits::{ToCss, ParseError, StyleParseErrorKind}; pub mod animated; pub mod computed; pub mod distance; pub mod generics; pub mod specified; /// A CSS float value. pub type CSSFloat = f32; /// A CSS integer value. pub type CSSInteger = i32; define_keyword_type!(None_, "none"); define_keyword_type!(Auto, "auto"); define_keyword_type!(Normal, "normal"); /// Serialize a normalized value into percentage. pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut W) -> fmt::Result where W: fmt::Write { (value * 100.).to_css(dest)?; dest.write_str("%") } /// Convenience void type to disable some properties and values through types. #[cfg_attr(feature = "servo", derive(Deserialize, MallocSizeOf, Serialize))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue, ToCss)] pub enum Impossible {} impl Parse for Impossible { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } /// A struct representing one of two kinds of values. #[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf)] #[derive(PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum Either<A, B> { /// The first value. First(A), /// The second kind of value. Second(B), } impl<A: Debug, B: Debug> Debug for Either<A, B> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Either::First(ref v) => v.fmt(f), Either::Second(ref v) => v.fmt(f), } } } impl<A: Parse, B: Parse> Parse for Either<A, B> { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Either<A, B>, ParseError<'i>> { if let Ok(v) = input.try(|i| A::parse(context, i)) { Ok(Either::First(v)) } else { B::parse(context, input).map(Either::Second) } } } /// <https://drafts.csswg.org/css-values-4/#custom-idents> #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToComputedValue)] pub struct CustomIdent(pub Atom); impl CustomIdent { /// Parse an already-tokenizer identifier pub fn from_ident<'i>(location: SourceLocation, ident: &CowRcStr<'i>, excluding: &[&str]) -> Result<Self, ParseError<'i>> { let valid = match_ignore_ascii_case! { ident, "initial" | "inherit" | "unset" | "default" => false, _ => true }; if!valid { return Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); } if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) { Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } else { Ok(CustomIdent(Atom::from(ident.as_ref()))) } } } impl ToCss for CustomIdent { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { serialize_identifier(&self.0.to_string(), dest) } } /// <https://drafts.csswg.org/css-animations/#typedef-keyframes-name> #[derive(Clone, Debug, MallocSizeOf, ToComputedValue)] pub enum KeyframesName { /// <custom-ident> Ident(CustomIdent), /// <string> QuotedString(Atom), } impl KeyframesName { /// <https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name> pub fn from_ident(value: &str) -> Self { let location = SourceLocation { line: 0, column: 0 }; let custom_ident = CustomIdent::from_ident(location, &value.into(), &["none"]).ok(); match custom_ident { Some(ident) => KeyframesName::Ident(ident), None => KeyframesName::QuotedString(value.into()), } } /// Create a new KeyframesName from Atom. #[cfg(feature = "gecko")] pub fn from_atom(atom: Atom) -> Self { debug_assert_ne!(atom, atom!("")); // FIXME: We might want to preserve <string>, but currently Gecko // stores both of <custom-ident> and <string> into nsAtom, so // we can't tell it. KeyframesName::Ident(CustomIdent(atom)) } /// The name as an Atom pub fn as_atom(&self) -> &Atom { match *self { KeyframesName::Ident(ref ident) => &ident.0, KeyframesName::QuotedString(ref atom) => atom, } } } impl Eq for KeyframesName {} impl PartialEq for KeyframesName { fn eq(&self, other: &Self) -> bool { self.as_atom() == other.as_atom() } } impl hash::Hash for KeyframesName { fn hash<H>(&self, state: &mut H) where H: hash::Hasher { self.as_atom().hash(state) } } impl Parse for KeyframesName { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); match input.next() { Ok(&Token::Ident(ref s)) => Ok(KeyframesName::Ident(CustomIdent::from_ident(location, s, &["none"])?)), Ok(&Token::QuotedString(ref s)) => Ok(KeyframesName::QuotedString(Atom::from(s.as_ref()))), Ok(t) => Err(location.new_unexpected_token_error(t.clone())), Err(e) => Err(e.into()), } } } impl ToCss for KeyframesName { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { KeyframesName::Ident(ref ident) => ident.to_css(dest), KeyframesName::QuotedString(ref atom) => atom.to_string().to_css(dest), } } } // A type for possible values for min- and max- flavors of width, // height, block-size, and inline-size. define_css_keyword_enum!(ExtremumLength: "-moz-max-content" => MaxContent, "-moz-min-content" => MinContent, "-moz-fit-content" => FitContent, "-moz-available" => FillAvailable);
use Atom; pub use cssparser::{RGBA, Token, Parser, serialize_identifier, CowRcStr, SourceLocation}; use parser::{Parse, ParserContext};
random_line_split
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Common [values][values] used in CSS. //! //! [values]: https://drafts.csswg.org/css-values/ #![deny(missing_docs)] use Atom; pub use cssparser::{RGBA, Token, Parser, serialize_identifier, CowRcStr, SourceLocation}; use parser::{Parse, ParserContext}; use selectors::parser::SelectorParseErrorKind; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::fmt::{self, Debug}; use std::hash; use style_traits::{ToCss, ParseError, StyleParseErrorKind}; pub mod animated; pub mod computed; pub mod distance; pub mod generics; pub mod specified; /// A CSS float value. pub type CSSFloat = f32; /// A CSS integer value. pub type CSSInteger = i32; define_keyword_type!(None_, "none"); define_keyword_type!(Auto, "auto"); define_keyword_type!(Normal, "normal"); /// Serialize a normalized value into percentage. pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut W) -> fmt::Result where W: fmt::Write { (value * 100.).to_css(dest)?; dest.write_str("%") } /// Convenience void type to disable some properties and values through types. #[cfg_attr(feature = "servo", derive(Deserialize, MallocSizeOf, Serialize))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue, ToCss)] pub enum Impossible {} impl Parse for Impossible { fn parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } /// A struct representing one of two kinds of values. #[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf)] #[derive(PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum Either<A, B> { /// The first value. First(A), /// The second kind of value. Second(B), } impl<A: Debug, B: Debug> Debug for Either<A, B> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Either::First(ref v) => v.fmt(f), Either::Second(ref v) => v.fmt(f), } } } impl<A: Parse, B: Parse> Parse for Either<A, B> { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Either<A, B>, ParseError<'i>> { if let Ok(v) = input.try(|i| A::parse(context, i)) { Ok(Either::First(v)) } else { B::parse(context, input).map(Either::Second) } } } /// <https://drafts.csswg.org/css-values-4/#custom-idents> #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToComputedValue)] pub struct CustomIdent(pub Atom); impl CustomIdent { /// Parse an already-tokenizer identifier pub fn from_ident<'i>(location: SourceLocation, ident: &CowRcStr<'i>, excluding: &[&str]) -> Result<Self, ParseError<'i>> { let valid = match_ignore_ascii_case! { ident, "initial" | "inherit" | "unset" | "default" => false, _ => true }; if!valid { return Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); } if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) { Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } else { Ok(CustomIdent(Atom::from(ident.as_ref()))) } } } impl ToCss for CustomIdent { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { serialize_identifier(&self.0.to_string(), dest) } } /// <https://drafts.csswg.org/css-animations/#typedef-keyframes-name> #[derive(Clone, Debug, MallocSizeOf, ToComputedValue)] pub enum KeyframesName { /// <custom-ident> Ident(CustomIdent), /// <string> QuotedString(Atom), } impl KeyframesName { /// <https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name> pub fn from_ident(value: &str) -> Self { let location = SourceLocation { line: 0, column: 0 }; let custom_ident = CustomIdent::from_ident(location, &value.into(), &["none"]).ok(); match custom_ident { Some(ident) => KeyframesName::Ident(ident), None => KeyframesName::QuotedString(value.into()), } } /// Create a new KeyframesName from Atom. #[cfg(feature = "gecko")] pub fn from_atom(atom: Atom) -> Self { debug_assert_ne!(atom, atom!("")); // FIXME: We might want to preserve <string>, but currently Gecko // stores both of <custom-ident> and <string> into nsAtom, so // we can't tell it. KeyframesName::Ident(CustomIdent(atom)) } /// The name as an Atom pub fn as_atom(&self) -> &Atom { match *self { KeyframesName::Ident(ref ident) => &ident.0, KeyframesName::QuotedString(ref atom) => atom, } } } impl Eq for KeyframesName {} impl PartialEq for KeyframesName { fn
(&self, other: &Self) -> bool { self.as_atom() == other.as_atom() } } impl hash::Hash for KeyframesName { fn hash<H>(&self, state: &mut H) where H: hash::Hasher { self.as_atom().hash(state) } } impl Parse for KeyframesName { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { let location = input.current_source_location(); match input.next() { Ok(&Token::Ident(ref s)) => Ok(KeyframesName::Ident(CustomIdent::from_ident(location, s, &["none"])?)), Ok(&Token::QuotedString(ref s)) => Ok(KeyframesName::QuotedString(Atom::from(s.as_ref()))), Ok(t) => Err(location.new_unexpected_token_error(t.clone())), Err(e) => Err(e.into()), } } } impl ToCss for KeyframesName { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { KeyframesName::Ident(ref ident) => ident.to_css(dest), KeyframesName::QuotedString(ref atom) => atom.to_string().to_css(dest), } } } // A type for possible values for min- and max- flavors of width, // height, block-size, and inline-size. define_css_keyword_enum!(ExtremumLength: "-moz-max-content" => MaxContent, "-moz-min-content" => MinContent, "-moz-fit-content" => FitContent, "-moz-available" => FillAvailable);
eq
identifier_name
main.rs
extern crate piston; extern crate piston_window; extern crate vecmath; extern crate camera_controllers; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate glfw_window; use std::cell::RefCell; use std::rc::Rc; use piston_window::*; use piston::event::*; use piston::window::{ AdvancedWindow, WindowSettings }; use camera_controllers::{ FirstPersonSettings, FirstPerson, CameraPerspective, model_view_projection }; use gfx::attrib::Floater; use gfx::traits::*; use glfw_window::{ GlfwWindow, OpenGL }; //---------------------------------------- // Cube associated data gfx_vertex!( Vertex { a_pos@ a_pos: [Floater<i8>; 3], a_tex_coord@ a_tex_coord: [Floater<u8>; 2], }); impl Vertex { fn new(pos: [i8; 3], tc: [u8; 2]) -> Vertex { Vertex { a_pos: Floater::cast3(pos), a_tex_coord: Floater::cast2(tc), } } } gfx_parameters!( Params/ParamsLink { u_model_view_proj@ u_model_view_proj: [[f32; 4]; 4], t_color@ t_color: gfx::shade::TextureParam<R>, }); //---------------------------------------- fn main()
Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), //right (1, 0, 0) Vertex::new([ 1, -1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([ 1, -1, 1], [0, 1]), //left (-1, 0, 0) Vertex::new([-1, 1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([-1, 1, -1], [0, 1]), //front (0, 1, 0) Vertex::new([-1, 1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //back (0, -1, 0) Vertex::new([ 1, -1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), ]; let mesh = events.canvas.borrow_mut().factory.create_mesh(&vertex_data); let index_data: &[u8] = &[ 0, 1, 2, 2, 3, 0, // top 4, 6, 5, 6, 4, 7, // bottom 8, 9, 10, 10, 11, 8, // right 12, 14, 13, 14, 12, 16, // left 16, 18, 17, 18, 16, 19, // front 20, 21, 22, 22, 23, 20, // back ]; let slice = events.canvas.borrow_mut().factory.create_buffer_index(index_data) .to_slice(gfx::PrimitiveType::TriangleList); let tinfo = gfx::tex::TextureInfo { width: 1, height: 1, depth: 1, levels: 1, kind: gfx::tex::TextureKind::Texture2D, format: gfx::tex::RGBA8, }; let img_info = tinfo.to_image_info(); let texture = events.canvas.borrow_mut().factory.create_texture(tinfo).unwrap(); events.canvas.borrow_mut().factory.update_texture( &texture, &img_info, &[0x20u8, 0xA0, 0xC0, 0x00], Some(gfx::tex::TextureKind::Texture2D) ).unwrap(); let sampler = events.canvas.borrow_mut().factory.create_sampler( gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Bilinear, gfx::tex::WrapMode::Clamp)); let program = { let canvas = &mut *events.canvas.borrow_mut(); let vertex = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslv")), glsl_150: Some(include_bytes!("cube_150.glslv")), .. gfx::ShaderSource::empty() }; let fragment = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslf")), glsl_150: Some(include_bytes!("cube_150.glslf")), .. gfx::ShaderSource::empty() }; canvas.factory.link_program_source(vertex, fragment, &canvas.device.get_capabilities()).unwrap() }; let mut data = Params { u_model_view_proj: vecmath::mat4_id(), t_color: (texture, Some(sampler)), _r: std::marker::PhantomData, }; let get_projection = |w: &PistonWindow<GlfwWindow>| { use piston::window::Window; let draw_size = w.window.borrow().draw_size(); CameraPerspective { fov: 90.0, near_clip: 0.1, far_clip: 1000.0, aspect_ratio: (draw_size.width as f32) / (draw_size.height as f32) }.projection() }; let model = vecmath::mat4_id(); let mut projection = get_projection(&events); let mut first_person = FirstPerson::new([0.5, 0.5, 4.0], FirstPersonSettings::keyboard_wasd()); let state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true); for e in events { first_person.event(&e); e.draw_3d(|canvas| { let args = e.render_args().unwrap(); canvas.renderer.clear( gfx::ClearData { color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0, }, gfx::COLOR | gfx::DEPTH, &canvas.output ); data.u_model_view_proj = model_view_projection( model, first_person.camera(args.ext_dt).orthogonal(), projection ); canvas.renderer.draw(&(&mesh, slice.clone(), &program, &data, &state), &canvas.output).unwrap(); }); if let Some(_) = e.resize_args() { projection = get_projection(&e); } } }
{ let (win_width, win_height) = (640, 480); let window = Rc::new(RefCell::new(GlfwWindow::new( OpenGL::_3_2, WindowSettings::new("piston-example-gfx_cube", [win_width, win_height]) .exit_on_esc(true) .samples(4) ).capture_cursor(true))); let events = PistonWindow::new(window, empty_app()); let vertex_data = vec![ //top (0, 0, 1) Vertex::new([-1, -1, 1], [0, 0]), Vertex::new([ 1, -1, 1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //bottom (0, 0, -1) Vertex::new([ 1, 1, -1], [0, 0]), Vertex::new([-1, 1, -1], [1, 0]),
identifier_body
main.rs
extern crate piston; extern crate piston_window; extern crate vecmath; extern crate camera_controllers; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate glfw_window; use std::cell::RefCell; use std::rc::Rc; use piston_window::*; use piston::event::*; use piston::window::{ AdvancedWindow, WindowSettings }; use camera_controllers::{ FirstPersonSettings, FirstPerson, CameraPerspective, model_view_projection }; use gfx::attrib::Floater; use gfx::traits::*; use glfw_window::{ GlfwWindow, OpenGL }; //---------------------------------------- // Cube associated data gfx_vertex!( Vertex { a_pos@ a_pos: [Floater<i8>; 3], a_tex_coord@ a_tex_coord: [Floater<u8>; 2], }); impl Vertex { fn new(pos: [i8; 3], tc: [u8; 2]) -> Vertex { Vertex { a_pos: Floater::cast3(pos), a_tex_coord: Floater::cast2(tc), } } } gfx_parameters!( Params/ParamsLink { u_model_view_proj@ u_model_view_proj: [[f32; 4]; 4], t_color@ t_color: gfx::shade::TextureParam<R>, }); //---------------------------------------- fn main() { let (win_width, win_height) = (640, 480); let window = Rc::new(RefCell::new(GlfwWindow::new( OpenGL::_3_2, WindowSettings::new("piston-example-gfx_cube", [win_width, win_height]) .exit_on_esc(true) .samples(4) ).capture_cursor(true))); let events = PistonWindow::new(window, empty_app()); let vertex_data = vec![ //top (0, 0, 1) Vertex::new([-1, -1, 1], [0, 0]), Vertex::new([ 1, -1, 1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //bottom (0, 0, -1) Vertex::new([ 1, 1, -1], [0, 0]), Vertex::new([-1, 1, -1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), //right (1, 0, 0) Vertex::new([ 1, -1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([ 1, -1, 1], [0, 1]), //left (-1, 0, 0) Vertex::new([-1, 1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([-1, 1, -1], [0, 1]), //front (0, 1, 0) Vertex::new([-1, 1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //back (0, -1, 0) Vertex::new([ 1, -1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), ]; let mesh = events.canvas.borrow_mut().factory.create_mesh(&vertex_data); let index_data: &[u8] = &[ 0, 1, 2, 2, 3, 0, // top 4, 6, 5, 6, 4, 7, // bottom 8, 9, 10, 10, 11, 8, // right 12, 14, 13, 14, 12, 16, // left 16, 18, 17, 18, 16, 19, // front 20, 21, 22, 22, 23, 20, // back ]; let slice = events.canvas.borrow_mut().factory.create_buffer_index(index_data) .to_slice(gfx::PrimitiveType::TriangleList); let tinfo = gfx::tex::TextureInfo { width: 1, height: 1, depth: 1, levels: 1, kind: gfx::tex::TextureKind::Texture2D, format: gfx::tex::RGBA8, }; let img_info = tinfo.to_image_info(); let texture = events.canvas.borrow_mut().factory.create_texture(tinfo).unwrap(); events.canvas.borrow_mut().factory.update_texture( &texture, &img_info, &[0x20u8, 0xA0, 0xC0, 0x00], Some(gfx::tex::TextureKind::Texture2D) ).unwrap(); let sampler = events.canvas.borrow_mut().factory.create_sampler( gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Bilinear, gfx::tex::WrapMode::Clamp)); let program = { let canvas = &mut *events.canvas.borrow_mut(); let vertex = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslv")), glsl_150: Some(include_bytes!("cube_150.glslv")), .. gfx::ShaderSource::empty() }; let fragment = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslf")), glsl_150: Some(include_bytes!("cube_150.glslf")), .. gfx::ShaderSource::empty() }; canvas.factory.link_program_source(vertex, fragment, &canvas.device.get_capabilities()).unwrap() }; let mut data = Params { u_model_view_proj: vecmath::mat4_id(), t_color: (texture, Some(sampler)), _r: std::marker::PhantomData, }; let get_projection = |w: &PistonWindow<GlfwWindow>| { use piston::window::Window; let draw_size = w.window.borrow().draw_size(); CameraPerspective { fov: 90.0, near_clip: 0.1, far_clip: 1000.0, aspect_ratio: (draw_size.width as f32) / (draw_size.height as f32) }.projection() }; let model = vecmath::mat4_id(); let mut projection = get_projection(&events); let mut first_person = FirstPerson::new([0.5, 0.5, 4.0], FirstPersonSettings::keyboard_wasd()); let state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true); for e in events { first_person.event(&e); e.draw_3d(|canvas| { let args = e.render_args().unwrap(); canvas.renderer.clear( gfx::ClearData { color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0, }, gfx::COLOR | gfx::DEPTH, &canvas.output ); data.u_model_view_proj = model_view_projection( model, first_person.camera(args.ext_dt).orthogonal(), projection ); canvas.renderer.draw(&(&mesh, slice.clone(), &program, &data, &state), &canvas.output).unwrap(); }); if let Some(_) = e.resize_args()
} }
{ projection = get_projection(&e); }
conditional_block
main.rs
extern crate piston; extern crate piston_window; extern crate vecmath; extern crate camera_controllers; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate glfw_window; use std::cell::RefCell; use std::rc::Rc; use piston_window::*; use piston::event::*; use piston::window::{ AdvancedWindow, WindowSettings }; use camera_controllers::{ FirstPersonSettings, FirstPerson, CameraPerspective, model_view_projection }; use gfx::attrib::Floater; use gfx::traits::*; use glfw_window::{ GlfwWindow, OpenGL }; //---------------------------------------- // Cube associated data gfx_vertex!( Vertex { a_pos@ a_pos: [Floater<i8>; 3], a_tex_coord@ a_tex_coord: [Floater<u8>; 2], }); impl Vertex { fn new(pos: [i8; 3], tc: [u8; 2]) -> Vertex { Vertex { a_pos: Floater::cast3(pos), a_tex_coord: Floater::cast2(tc), } } } gfx_parameters!( Params/ParamsLink { u_model_view_proj@ u_model_view_proj: [[f32; 4]; 4], t_color@ t_color: gfx::shade::TextureParam<R>, }); //---------------------------------------- fn
() { let (win_width, win_height) = (640, 480); let window = Rc::new(RefCell::new(GlfwWindow::new( OpenGL::_3_2, WindowSettings::new("piston-example-gfx_cube", [win_width, win_height]) .exit_on_esc(true) .samples(4) ).capture_cursor(true))); let events = PistonWindow::new(window, empty_app()); let vertex_data = vec![ //top (0, 0, 1) Vertex::new([-1, -1, 1], [0, 0]), Vertex::new([ 1, -1, 1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //bottom (0, 0, -1) Vertex::new([ 1, 1, -1], [0, 0]), Vertex::new([-1, 1, -1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), //right (1, 0, 0) Vertex::new([ 1, -1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([ 1, -1, 1], [0, 1]), //left (-1, 0, 0) Vertex::new([-1, 1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([-1, 1, -1], [0, 1]), //front (0, 1, 0) Vertex::new([-1, 1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //back (0, -1, 0) Vertex::new([ 1, -1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), ]; let mesh = events.canvas.borrow_mut().factory.create_mesh(&vertex_data); let index_data: &[u8] = &[ 0, 1, 2, 2, 3, 0, // top 4, 6, 5, 6, 4, 7, // bottom 8, 9, 10, 10, 11, 8, // right 12, 14, 13, 14, 12, 16, // left 16, 18, 17, 18, 16, 19, // front 20, 21, 22, 22, 23, 20, // back ]; let slice = events.canvas.borrow_mut().factory.create_buffer_index(index_data) .to_slice(gfx::PrimitiveType::TriangleList); let tinfo = gfx::tex::TextureInfo { width: 1, height: 1, depth: 1, levels: 1, kind: gfx::tex::TextureKind::Texture2D, format: gfx::tex::RGBA8, }; let img_info = tinfo.to_image_info(); let texture = events.canvas.borrow_mut().factory.create_texture(tinfo).unwrap(); events.canvas.borrow_mut().factory.update_texture( &texture, &img_info, &[0x20u8, 0xA0, 0xC0, 0x00], Some(gfx::tex::TextureKind::Texture2D) ).unwrap(); let sampler = events.canvas.borrow_mut().factory.create_sampler( gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Bilinear, gfx::tex::WrapMode::Clamp)); let program = { let canvas = &mut *events.canvas.borrow_mut(); let vertex = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslv")), glsl_150: Some(include_bytes!("cube_150.glslv")), .. gfx::ShaderSource::empty() }; let fragment = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslf")), glsl_150: Some(include_bytes!("cube_150.glslf")), .. gfx::ShaderSource::empty() }; canvas.factory.link_program_source(vertex, fragment, &canvas.device.get_capabilities()).unwrap() }; let mut data = Params { u_model_view_proj: vecmath::mat4_id(), t_color: (texture, Some(sampler)), _r: std::marker::PhantomData, }; let get_projection = |w: &PistonWindow<GlfwWindow>| { use piston::window::Window; let draw_size = w.window.borrow().draw_size(); CameraPerspective { fov: 90.0, near_clip: 0.1, far_clip: 1000.0, aspect_ratio: (draw_size.width as f32) / (draw_size.height as f32) }.projection() }; let model = vecmath::mat4_id(); let mut projection = get_projection(&events); let mut first_person = FirstPerson::new([0.5, 0.5, 4.0], FirstPersonSettings::keyboard_wasd()); let state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true); for e in events { first_person.event(&e); e.draw_3d(|canvas| { let args = e.render_args().unwrap(); canvas.renderer.clear( gfx::ClearData { color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0, }, gfx::COLOR | gfx::DEPTH, &canvas.output ); data.u_model_view_proj = model_view_projection( model, first_person.camera(args.ext_dt).orthogonal(), projection ); canvas.renderer.draw(&(&mesh, slice.clone(), &program, &data, &state), &canvas.output).unwrap(); }); if let Some(_) = e.resize_args() { projection = get_projection(&e); } } }
main
identifier_name
main.rs
extern crate piston; extern crate piston_window; extern crate vecmath; extern crate camera_controllers; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate glfw_window; use std::cell::RefCell; use std::rc::Rc; use piston_window::*; use piston::event::*; use piston::window::{ AdvancedWindow, WindowSettings }; use camera_controllers::{ FirstPersonSettings, FirstPerson, CameraPerspective, model_view_projection }; use gfx::attrib::Floater; use gfx::traits::*; use glfw_window::{ GlfwWindow, OpenGL }; //---------------------------------------- // Cube associated data gfx_vertex!( Vertex { a_pos@ a_pos: [Floater<i8>; 3], a_tex_coord@ a_tex_coord: [Floater<u8>; 2], }); impl Vertex { fn new(pos: [i8; 3], tc: [u8; 2]) -> Vertex { Vertex { a_pos: Floater::cast3(pos), a_tex_coord: Floater::cast2(tc), } } } gfx_parameters!( Params/ParamsLink { u_model_view_proj@ u_model_view_proj: [[f32; 4]; 4], t_color@ t_color: gfx::shade::TextureParam<R>, }); //---------------------------------------- fn main() { let (win_width, win_height) = (640, 480); let window = Rc::new(RefCell::new(GlfwWindow::new( OpenGL::_3_2, WindowSettings::new("piston-example-gfx_cube", [win_width, win_height]) .exit_on_esc(true) .samples(4) ).capture_cursor(true))); let events = PistonWindow::new(window, empty_app()); let vertex_data = vec![ //top (0, 0, 1) Vertex::new([-1, -1, 1], [0, 0]), Vertex::new([ 1, -1, 1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //bottom (0, 0, -1) Vertex::new([ 1, 1, -1], [0, 0]), Vertex::new([-1, 1, -1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), //right (1, 0, 0) Vertex::new([ 1, -1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([ 1, -1, 1], [0, 1]), //left (-1, 0, 0) Vertex::new([-1, 1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([-1, 1, -1], [0, 1]), //front (0, 1, 0) Vertex::new([-1, 1, -1], [0, 0]), Vertex::new([ 1, 1, -1], [1, 0]), Vertex::new([ 1, 1, 1], [1, 1]), Vertex::new([-1, 1, 1], [0, 1]), //back (0, -1, 0) Vertex::new([ 1, -1, 1], [0, 0]), Vertex::new([-1, -1, 1], [1, 0]), Vertex::new([-1, -1, -1], [1, 1]), Vertex::new([ 1, -1, -1], [0, 1]), ]; let mesh = events.canvas.borrow_mut().factory.create_mesh(&vertex_data); let index_data: &[u8] = &[ 0, 1, 2, 2, 3, 0, // top 4, 6, 5, 6, 4, 7, // bottom 8, 9, 10, 10, 11, 8, // right 12, 14, 13, 14, 12, 16, // left 16, 18, 17, 18, 16, 19, // front 20, 21, 22, 22, 23, 20, // back ]; let slice = events.canvas.borrow_mut().factory.create_buffer_index(index_data) .to_slice(gfx::PrimitiveType::TriangleList); let tinfo = gfx::tex::TextureInfo { width: 1, height: 1, depth: 1, levels: 1, kind: gfx::tex::TextureKind::Texture2D, format: gfx::tex::RGBA8, }; let img_info = tinfo.to_image_info(); let texture = events.canvas.borrow_mut().factory.create_texture(tinfo).unwrap(); events.canvas.borrow_mut().factory.update_texture( &texture, &img_info, &[0x20u8, 0xA0, 0xC0, 0x00], Some(gfx::tex::TextureKind::Texture2D) ).unwrap(); let sampler = events.canvas.borrow_mut().factory.create_sampler( gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Bilinear, gfx::tex::WrapMode::Clamp)); let program = { let canvas = &mut *events.canvas.borrow_mut(); let vertex = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslv")), glsl_150: Some(include_bytes!("cube_150.glslv")), .. gfx::ShaderSource::empty() }; let fragment = gfx::ShaderSource { glsl_120: Some(include_bytes!("cube_120.glslf")), glsl_150: Some(include_bytes!("cube_150.glslf")), .. gfx::ShaderSource::empty() }; canvas.factory.link_program_source(vertex, fragment, &canvas.device.get_capabilities()).unwrap() }; let mut data = Params { u_model_view_proj: vecmath::mat4_id(), t_color: (texture, Some(sampler)), _r: std::marker::PhantomData, };
use piston::window::Window; let draw_size = w.window.borrow().draw_size(); CameraPerspective { fov: 90.0, near_clip: 0.1, far_clip: 1000.0, aspect_ratio: (draw_size.width as f32) / (draw_size.height as f32) }.projection() }; let model = vecmath::mat4_id(); let mut projection = get_projection(&events); let mut first_person = FirstPerson::new([0.5, 0.5, 4.0], FirstPersonSettings::keyboard_wasd()); let state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true); for e in events { first_person.event(&e); e.draw_3d(|canvas| { let args = e.render_args().unwrap(); canvas.renderer.clear( gfx::ClearData { color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0, }, gfx::COLOR | gfx::DEPTH, &canvas.output ); data.u_model_view_proj = model_view_projection( model, first_person.camera(args.ext_dt).orthogonal(), projection ); canvas.renderer.draw(&(&mesh, slice.clone(), &program, &data, &state), &canvas.output).unwrap(); }); if let Some(_) = e.resize_args() { projection = get_projection(&e); } } }
let get_projection = |w: &PistonWindow<GlfwWindow>| {
random_line_split
oesvertexarrayobject.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::webgl::WebGLVersion; use dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::{self, OESVertexArrayObjectMethods}; use dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::OESVertexArrayObjectConstants; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot}; use dom::webglrenderingcontext::WebGLRenderingContext; use dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES; use dom_struct::dom_struct; use super::{WebGLExtension, WebGLExtensions, WebGLExtensionSpec}; #[dom_struct] pub struct OESVertexArrayObject { reflector_: Reflector, ctx: Dom<WebGLRenderingContext>, } impl OESVertexArrayObject { fn new_inherited(ctx: &WebGLRenderingContext) -> OESVertexArrayObject { Self { reflector_: Reflector::new(), ctx: Dom::from_ref(ctx), } } } impl OESVertexArrayObjectMethods for OESVertexArrayObject { // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn CreateVertexArrayOES(&self) -> Option<DomRoot<WebGLVertexArrayObjectOES>> { self.ctx.create_vertex_array() } // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn DeleteVertexArrayOES(&self, vao: Option<&WebGLVertexArrayObjectOES>) { self.ctx.delete_vertex_array(vao); } // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn IsVertexArrayOES(&self, vao: Option<&WebGLVertexArrayObjectOES>) -> bool { self.ctx.is_vertex_array(vao) } // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn BindVertexArrayOES(&self, vao: Option<&WebGLVertexArrayObjectOES>) { self.ctx.bind_vertex_array(vao); } }
fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESVertexArrayObject> { reflect_dom_object( Box::new(OESVertexArrayObject::new_inherited(ctx)), &*ctx.global(), OESVertexArrayObjectBinding::Wrap, ) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::Specific(WebGLVersion::WebGL1) } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&[ "GL_OES_vertex_array_object", "GL_ARB_vertex_array_object", "GL_APPLE_vertex_array_object", ]) } fn enable(ext: &WebGLExtensions) { ext.enable_get_parameter_name(OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES); } fn name() -> &'static str { "OES_vertex_array_object" } }
impl WebGLExtension for OESVertexArrayObject { type Extension = OESVertexArrayObject;
random_line_split
oesvertexarrayobject.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::webgl::WebGLVersion; use dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::{self, OESVertexArrayObjectMethods}; use dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::OESVertexArrayObjectConstants; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot}; use dom::webglrenderingcontext::WebGLRenderingContext; use dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES; use dom_struct::dom_struct; use super::{WebGLExtension, WebGLExtensions, WebGLExtensionSpec}; #[dom_struct] pub struct
{ reflector_: Reflector, ctx: Dom<WebGLRenderingContext>, } impl OESVertexArrayObject { fn new_inherited(ctx: &WebGLRenderingContext) -> OESVertexArrayObject { Self { reflector_: Reflector::new(), ctx: Dom::from_ref(ctx), } } } impl OESVertexArrayObjectMethods for OESVertexArrayObject { // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn CreateVertexArrayOES(&self) -> Option<DomRoot<WebGLVertexArrayObjectOES>> { self.ctx.create_vertex_array() } // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn DeleteVertexArrayOES(&self, vao: Option<&WebGLVertexArrayObjectOES>) { self.ctx.delete_vertex_array(vao); } // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn IsVertexArrayOES(&self, vao: Option<&WebGLVertexArrayObjectOES>) -> bool { self.ctx.is_vertex_array(vao) } // https://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ fn BindVertexArrayOES(&self, vao: Option<&WebGLVertexArrayObjectOES>) { self.ctx.bind_vertex_array(vao); } } impl WebGLExtension for OESVertexArrayObject { type Extension = OESVertexArrayObject; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESVertexArrayObject> { reflect_dom_object( Box::new(OESVertexArrayObject::new_inherited(ctx)), &*ctx.global(), OESVertexArrayObjectBinding::Wrap, ) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::Specific(WebGLVersion::WebGL1) } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&[ "GL_OES_vertex_array_object", "GL_ARB_vertex_array_object", "GL_APPLE_vertex_array_object", ]) } fn enable(ext: &WebGLExtensions) { ext.enable_get_parameter_name(OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES); } fn name() -> &'static str { "OES_vertex_array_object" } }
OESVertexArrayObject
identifier_name
entry.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use crate::types::*; use libimagstore::store::Entry; use toml_query::read::TomlValueReadExt; use toml_query::insert::TomlValueInsertExt; use toml_query::delete::TomlValueDeleteExt; use anyhow::Context; use anyhow::Result; use anyhow::Error; pub trait GPSEntry { fn set_coordinates(&mut self, c: Coordinates) -> Result<()>; fn get_coordinates(&self) -> Result<Option<Coordinates>>; /// Remove the coordinates from the entry /// /// # Returns /// /// The return type is a bit complicated, but that has a reason: /// /// The outer Result<_> is used for notifying a failure during the header read/write action. /// If the Option<_> is Some(_), the value was deleted. /// The inner Result<_> is used for parsing failures during the parsing of the deleted value. /// /// So: /// /// * Ok(Some(Ok(_))) if the coordinates were deleted, returning the deleted value /// * Ok(Some(Err(_))) if the coordinates were deleted, but the deleted value couldn't be parsed /// * Ok(None) if there were no coordinates to delete /// * Err(e) if the deleting failed /// fn remove_coordinates(&mut self) -> Result<Option<Result<Coordinates>>>; } impl GPSEntry for Entry { fn set_coordinates(&mut self, c: Coordinates) -> Result<()> { self.get_header_mut() .insert("gps.coordinates", c.into()) .map(|_| ()) .context(anyhow!("Error while inserting header 'gps.coordinates' in '{}'", self.get_location())) .map_err(Error::from) } fn get_coordinates(&self) -> Result<Option<Coordinates>> { match self .get_header() .read("gps.coordinates") .context(anyhow!("Error while reading header 'gps.coordinates' in '{}'", self.get_location()))? { Some(hdr) => Coordinates::from_value(hdr).map(Some), None => Ok(None), } } fn remove_coordinates(&mut self) -> Result<Option<Result<Coordinates>>>
.context("Error writing header")?; } match coordinates { Ok(None) => Ok(None), Ok(Some(some)) => Ok(Some(Ok(some))), Err(e) => Ok(Some(Err(e))), } } } #[cfg(test)] mod tests { use std::path::PathBuf; use libimagstore::store::Store; use crate::entry::*; fn setup_logging() { let _ = ::env_logger::try_init; } fn get_store() -> Store { Store::new_inmemory(PathBuf::from("/"), &None).unwrap() } #[test] fn test_set_gps() { setup_logging(); let store = get_store(); let mut entry = store.create(PathBuf::from("test_set_gps")).unwrap(); let coordinates = Coordinates { latitude: GPSValue::new(0, 0, 0), longitude: GPSValue::new(0, 0, 0), }; let res = entry.set_coordinates(coordinates); assert!(res.is_ok()); } #[test] fn test_setget_gps() { setup_logging(); let store = get_store(); let mut entry = store.create(PathBuf::from("test_setget_gps")).unwrap(); let coordinates = Coordinates { latitude: GPSValue::new(0, 0, 0), longitude: GPSValue::new(0, 0, 0), }; let res = entry.set_coordinates(coordinates); assert!(res.is_ok()); let coordinates = entry.get_coordinates(); assert!(coordinates.is_ok()); let coordinates = coordinates.unwrap(); assert!(coordinates.is_some()); let coordinates = coordinates.unwrap(); assert_eq!(0, coordinates.longitude.degree); assert_eq!(0, coordinates.longitude.minutes); assert_eq!(0, coordinates.longitude.seconds); assert_eq!(0, coordinates.latitude.degree); assert_eq!(0, coordinates.latitude.minutes); assert_eq!(0, coordinates.latitude.seconds); } }
{ let coordinates = self.get_coordinates(); let patterns = [ "gps.coordinates.latitude.degree", "gps.coordinates.latitude.minutes", "gps.coordinates.latitude.seconds", "gps.coordinates.longitude.degree", "gps.coordinates.longitude.minutes", "gps.coordinates.longitude.seconds", "gps.coordinates.latitude", "gps.coordinates.longitude", "gps.coordinates", "gps", ]; let hdr = self.get_header_mut(); for pattern in patterns.iter() { let _ = hdr.delete(pattern) .context(anyhow!("Error while deleting header '{}'", pattern))
identifier_body
entry.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use crate::types::*; use libimagstore::store::Entry; use toml_query::read::TomlValueReadExt; use toml_query::insert::TomlValueInsertExt; use toml_query::delete::TomlValueDeleteExt; use anyhow::Context; use anyhow::Result; use anyhow::Error; pub trait GPSEntry { fn set_coordinates(&mut self, c: Coordinates) -> Result<()>; fn get_coordinates(&self) -> Result<Option<Coordinates>>; /// Remove the coordinates from the entry /// /// # Returns /// /// The return type is a bit complicated, but that has a reason: /// /// The outer Result<_> is used for notifying a failure during the header read/write action. /// If the Option<_> is Some(_), the value was deleted. /// The inner Result<_> is used for parsing failures during the parsing of the deleted value. /// /// So: /// /// * Ok(Some(Ok(_))) if the coordinates were deleted, returning the deleted value /// * Ok(Some(Err(_))) if the coordinates were deleted, but the deleted value couldn't be parsed /// * Ok(None) if there were no coordinates to delete /// * Err(e) if the deleting failed /// fn remove_coordinates(&mut self) -> Result<Option<Result<Coordinates>>>; } impl GPSEntry for Entry { fn set_coordinates(&mut self, c: Coordinates) -> Result<()> { self.get_header_mut() .insert("gps.coordinates", c.into()) .map(|_| ()) .context(anyhow!("Error while inserting header 'gps.coordinates' in '{}'", self.get_location())) .map_err(Error::from) } fn get_coordinates(&self) -> Result<Option<Coordinates>> { match self .get_header() .read("gps.coordinates") .context(anyhow!("Error while reading header 'gps.coordinates' in '{}'", self.get_location()))? { Some(hdr) => Coordinates::from_value(hdr).map(Some), None => Ok(None), } } fn remove_coordinates(&mut self) -> Result<Option<Result<Coordinates>>> { let coordinates = self.get_coordinates(); let patterns = [ "gps.coordinates.latitude.degree", "gps.coordinates.latitude.minutes", "gps.coordinates.latitude.seconds", "gps.coordinates.longitude.degree", "gps.coordinates.longitude.minutes", "gps.coordinates.longitude.seconds", "gps.coordinates.latitude", "gps.coordinates.longitude", "gps.coordinates", "gps", ]; let hdr = self.get_header_mut(); for pattern in patterns.iter() { let _ = hdr.delete(pattern) .context(anyhow!("Error while deleting header '{}'", pattern)) .context("Error writing header")?; } match coordinates { Ok(None) => Ok(None), Ok(Some(some)) => Ok(Some(Ok(some))), Err(e) => Ok(Some(Err(e))), } } } #[cfg(test)] mod tests { use std::path::PathBuf; use libimagstore::store::Store; use crate::entry::*; fn setup_logging() { let _ = ::env_logger::try_init; } fn get_store() -> Store { Store::new_inmemory(PathBuf::from("/"), &None).unwrap() } #[test] fn test_set_gps() { setup_logging(); let store = get_store();
let coordinates = Coordinates { latitude: GPSValue::new(0, 0, 0), longitude: GPSValue::new(0, 0, 0), }; let res = entry.set_coordinates(coordinates); assert!(res.is_ok()); } #[test] fn test_setget_gps() { setup_logging(); let store = get_store(); let mut entry = store.create(PathBuf::from("test_setget_gps")).unwrap(); let coordinates = Coordinates { latitude: GPSValue::new(0, 0, 0), longitude: GPSValue::new(0, 0, 0), }; let res = entry.set_coordinates(coordinates); assert!(res.is_ok()); let coordinates = entry.get_coordinates(); assert!(coordinates.is_ok()); let coordinates = coordinates.unwrap(); assert!(coordinates.is_some()); let coordinates = coordinates.unwrap(); assert_eq!(0, coordinates.longitude.degree); assert_eq!(0, coordinates.longitude.minutes); assert_eq!(0, coordinates.longitude.seconds); assert_eq!(0, coordinates.latitude.degree); assert_eq!(0, coordinates.latitude.minutes); assert_eq!(0, coordinates.latitude.seconds); } }
let mut entry = store.create(PathBuf::from("test_set_gps")).unwrap();
random_line_split
entry.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use crate::types::*; use libimagstore::store::Entry; use toml_query::read::TomlValueReadExt; use toml_query::insert::TomlValueInsertExt; use toml_query::delete::TomlValueDeleteExt; use anyhow::Context; use anyhow::Result; use anyhow::Error; pub trait GPSEntry { fn set_coordinates(&mut self, c: Coordinates) -> Result<()>; fn get_coordinates(&self) -> Result<Option<Coordinates>>; /// Remove the coordinates from the entry /// /// # Returns /// /// The return type is a bit complicated, but that has a reason: /// /// The outer Result<_> is used for notifying a failure during the header read/write action. /// If the Option<_> is Some(_), the value was deleted. /// The inner Result<_> is used for parsing failures during the parsing of the deleted value. /// /// So: /// /// * Ok(Some(Ok(_))) if the coordinates were deleted, returning the deleted value /// * Ok(Some(Err(_))) if the coordinates were deleted, but the deleted value couldn't be parsed /// * Ok(None) if there were no coordinates to delete /// * Err(e) if the deleting failed /// fn remove_coordinates(&mut self) -> Result<Option<Result<Coordinates>>>; } impl GPSEntry for Entry { fn set_coordinates(&mut self, c: Coordinates) -> Result<()> { self.get_header_mut() .insert("gps.coordinates", c.into()) .map(|_| ()) .context(anyhow!("Error while inserting header 'gps.coordinates' in '{}'", self.get_location())) .map_err(Error::from) } fn get_coordinates(&self) -> Result<Option<Coordinates>> { match self .get_header() .read("gps.coordinates") .context(anyhow!("Error while reading header 'gps.coordinates' in '{}'", self.get_location()))? { Some(hdr) => Coordinates::from_value(hdr).map(Some), None => Ok(None), } } fn remove_coordinates(&mut self) -> Result<Option<Result<Coordinates>>> { let coordinates = self.get_coordinates(); let patterns = [ "gps.coordinates.latitude.degree", "gps.coordinates.latitude.minutes", "gps.coordinates.latitude.seconds", "gps.coordinates.longitude.degree", "gps.coordinates.longitude.minutes", "gps.coordinates.longitude.seconds", "gps.coordinates.latitude", "gps.coordinates.longitude", "gps.coordinates", "gps", ]; let hdr = self.get_header_mut(); for pattern in patterns.iter() { let _ = hdr.delete(pattern) .context(anyhow!("Error while deleting header '{}'", pattern)) .context("Error writing header")?; } match coordinates { Ok(None) => Ok(None), Ok(Some(some)) => Ok(Some(Ok(some))), Err(e) => Ok(Some(Err(e))), } } } #[cfg(test)] mod tests { use std::path::PathBuf; use libimagstore::store::Store; use crate::entry::*; fn setup_logging() { let _ = ::env_logger::try_init; } fn get_store() -> Store { Store::new_inmemory(PathBuf::from("/"), &None).unwrap() } #[test] fn test_set_gps() { setup_logging(); let store = get_store(); let mut entry = store.create(PathBuf::from("test_set_gps")).unwrap(); let coordinates = Coordinates { latitude: GPSValue::new(0, 0, 0), longitude: GPSValue::new(0, 0, 0), }; let res = entry.set_coordinates(coordinates); assert!(res.is_ok()); } #[test] fn
() { setup_logging(); let store = get_store(); let mut entry = store.create(PathBuf::from("test_setget_gps")).unwrap(); let coordinates = Coordinates { latitude: GPSValue::new(0, 0, 0), longitude: GPSValue::new(0, 0, 0), }; let res = entry.set_coordinates(coordinates); assert!(res.is_ok()); let coordinates = entry.get_coordinates(); assert!(coordinates.is_ok()); let coordinates = coordinates.unwrap(); assert!(coordinates.is_some()); let coordinates = coordinates.unwrap(); assert_eq!(0, coordinates.longitude.degree); assert_eq!(0, coordinates.longitude.minutes); assert_eq!(0, coordinates.longitude.seconds); assert_eq!(0, coordinates.latitude.degree); assert_eq!(0, coordinates.latitude.minutes); assert_eq!(0, coordinates.latitude.seconds); } }
test_setget_gps
identifier_name
group.rs
//! Fuctions and Structs for dealing with /etc/group use std::path::Path; use std::num::ParseIntError; use libc::gid_t; use entries::{Entries,Entry}; /// An entry from /etc/group #[derive(Debug, PartialEq, PartialOrd)] pub struct
{ /// Group Name pub name: String, /// Group Password pub passwd: String, /// Group ID pub gid: gid_t, /// Group Members pub members: Vec<String>, } impl Entry for GroupEntry { fn from_line(line: &str) -> Result<GroupEntry, ParseIntError> { let parts: Vec<&str> = line.split(":").map(|part| part.trim()).collect(); let members: Vec<String> = match parts[3].len() { 0 => Vec::new(), _ => parts[3] .split(",") .map(|member| member.trim()) .map(|member| member.to_string()) .collect() }; Ok(GroupEntry { name: parts[0].to_string(), passwd: parts[1].to_string(), gid: try!(parts[2].parse()), members: members, }) } } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `uid` and `&Path` pub fn get_entry_by_gid_from_path(path: &Path, gid: gid_t) -> Option<GroupEntry> { Entries::<GroupEntry>::new(path).find(|x| x.gid == gid) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `uid` from `/etc/group` pub fn get_entry_by_gid(gid: gid_t) -> Option<GroupEntry> { get_entry_by_gid_from_path(&Path::new("/etc/group"), gid) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `name` and `&Path` pub fn get_entry_by_name_from_path(path: &Path, name: &str) -> Option<GroupEntry> { Entries::<GroupEntry>::new(path).find(|x| x.name == name) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `name` from `/etc/group` pub fn get_entry_by_name(name: &str) -> Option<GroupEntry> { get_entry_by_name_from_path(&Path::new("/etc/group"), name) } /// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all /// [`GroupEntry`](struct.GroupEntry.html)'s for a given `&Path` pub fn get_all_entries_from_path(path: &Path) -> Vec<GroupEntry> { Entries::new(path).collect() } /// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all /// [`GroupEntry`](struct.GroupEntry.html)'s from `/etc/group` pub fn get_all_entries() -> Vec<GroupEntry> { get_all_entries_from_path(&Path::new("/etc/group")) }
GroupEntry
identifier_name
group.rs
//! Fuctions and Structs for dealing with /etc/group use std::path::Path; use std::num::ParseIntError; use libc::gid_t; use entries::{Entries,Entry}; /// An entry from /etc/group #[derive(Debug, PartialEq, PartialOrd)] pub struct GroupEntry { /// Group Name pub name: String, /// Group Password pub passwd: String, /// Group ID pub gid: gid_t, /// Group Members pub members: Vec<String>, } impl Entry for GroupEntry { fn from_line(line: &str) -> Result<GroupEntry, ParseIntError> { let parts: Vec<&str> = line.split(":").map(|part| part.trim()).collect(); let members: Vec<String> = match parts[3].len() { 0 => Vec::new(), _ => parts[3] .split(",") .map(|member| member.trim()) .map(|member| member.to_string()) .collect() }; Ok(GroupEntry { name: parts[0].to_string(), passwd: parts[1].to_string(), gid: try!(parts[2].parse()), members: members, }) } } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `uid` and `&Path` pub fn get_entry_by_gid_from_path(path: &Path, gid: gid_t) -> Option<GroupEntry> { Entries::<GroupEntry>::new(path).find(|x| x.gid == gid) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `uid` from `/etc/group` pub fn get_entry_by_gid(gid: gid_t) -> Option<GroupEntry> { get_entry_by_gid_from_path(&Path::new("/etc/group"), gid) } /// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `name` and `&Path` pub fn get_entry_by_name_from_path(path: &Path, name: &str) -> Option<GroupEntry> { Entries::<GroupEntry>::new(path).find(|x| x.name == name) }
get_entry_by_name_from_path(&Path::new("/etc/group"), name) } /// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all /// [`GroupEntry`](struct.GroupEntry.html)'s for a given `&Path` pub fn get_all_entries_from_path(path: &Path) -> Vec<GroupEntry> { Entries::new(path).collect() } /// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all /// [`GroupEntry`](struct.GroupEntry.html)'s from `/etc/group` pub fn get_all_entries() -> Vec<GroupEntry> { get_all_entries_from_path(&Path::new("/etc/group")) }
/// Return a [`GroupEntry`](struct.GroupEntry.html) /// for a given `name` from `/etc/group` pub fn get_entry_by_name(name: &str) -> Option<GroupEntry> {
random_line_split
simplify.rs
// 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. //! Simplification of where clauses and parameter bounds into a prettier and //! more canonical form. //! //! Currently all cross-crate-inlined function use `middle::ty` to reconstruct //! the AST (e.g. see all of `clean::inline`), but this is not always a //! non-lossy transformation. The current format of storage for where clauses //! for functions and such is simply a list of predicates. One example of this //! is that the AST predicate of: //! //! where T: Trait<Foo=Bar> //! //! is encoded as: //! //! where T: Trait, <T as Trait>::Foo = Bar //! //! This module attempts to reconstruct the original where and/or parameter //! bounds by special casing scenarios such as these. Fun! use std::mem; use std::collections::HashMap; use rustc::middle::subst; use rustc::middle::ty; use syntax::ast; use clean::PathParameters as PP; use clean::WherePredicate as WP; use clean::{self, Clean}; use core::DocContext; pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> { // First, partition the where clause into its separate components let mut params = HashMap::new(); let mut lifetimes = Vec::new(); let mut equalities = Vec::new(); let mut tybounds = Vec::new(); for clause in clauses { match clause { WP::BoundPredicate { ty, bounds } => { match ty { clean::Generic(s) => params.entry(s).or_insert(Vec::new()) .extend(bounds), t => tybounds.push((t, ty_bounds(bounds))), } } WP::RegionPredicate { lifetime, bounds } => { lifetimes.push((lifetime, bounds)); } WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)), } } // Simplify the type parameter bounds on all the generics let mut params = params.into_iter().map(|(k, v)| { (k, ty_bounds(v)) }).collect::<HashMap<_, _>>(); // Look for equality predicates on associated types that can be merged into // general bound predicates equalities.retain(|&(ref lhs, ref rhs)| { let (self_, trait_, name) = match *lhs { clean::QPath { ref self_type, ref trait_, ref name } => { (self_type, trait_, name) } _ => return true, }; let generic = match **self_ { clean::Generic(ref s) => s, _ => return true, }; let trait_did = match **trait_ { clean::ResolvedPath { did,.. } => did, _ => return true, }; let bounds = match params.get_mut(generic) { Some(bound) => bound, None => return true, }; !bounds.iter_mut().any(|b| { let trait_ref = match *b { clean::TraitBound(ref mut tr, _) => tr, clean::RegionBound(..) => return false, }; let (did, path) = match trait_ref.trait_ { clean::ResolvedPath { did, ref mut path,..} => (did, path), _ => return false, }; // If this QPath's trait `trait_did` is the same as, or a supertrait // of, the bound's trait `did` then we can keep going, otherwise // this is just a plain old equality bound. if!trait_is_same_or_supertrait(cx, did, trait_did) { return false } let last = path.segments.last_mut().unwrap(); match last.params { PP::AngleBracketed { ref mut bindings,.. } => { bindings.push(clean::TypeBinding { name: name.clone(), ty: rhs.clone(), }); } PP::Parenthesized { ref mut output,.. } => { assert!(output.is_none()); *output = Some(rhs.clone()); } }; true }) }); // And finally, let's reassemble everything let mut clauses = Vec::new(); clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| { WP::RegionPredicate { lifetime: lt, bounds: bounds } })); clauses.extend(params.into_iter().map(|(k, v)| { WP::BoundPredicate { ty: clean::Generic(k), bounds: v, } })); clauses.extend(tybounds.into_iter().map(|(ty, bounds)| { WP::BoundPredicate { ty: ty, bounds: bounds } })); clauses.extend(equalities.into_iter().map(|(lhs, rhs)| { WP::EqPredicate { lhs: lhs, rhs: rhs } })); clauses } pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> { for param in params.iter_mut() { param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new())); } return params; } fn
(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> { bounds } fn trait_is_same_or_supertrait(cx: &DocContext, child: ast::DefId, trait_: ast::DefId) -> bool { if child == trait_ { return true } let def = ty::lookup_trait_def(cx.tcx(), child); let predicates = ty::lookup_predicates(cx.tcx(), child); let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx); generics.where_predicates.iter().filter_map(|pred| { match *pred { clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds } if *s == "Self" => Some(bounds), _ => None, } }).flat_map(|bounds| bounds.iter()).any(|bound| { let poly_trait = match *bound { clean::TraitBound(ref t, _) => t, _ => return false, }; match poly_trait.trait_ { clean::ResolvedPath { did,.. } => { trait_is_same_or_supertrait(cx, did, trait_) } _ => false, } }) }
ty_bounds
identifier_name
simplify.rs
// 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. //! Simplification of where clauses and parameter bounds into a prettier and //! more canonical form. //! //! Currently all cross-crate-inlined function use `middle::ty` to reconstruct //! the AST (e.g. see all of `clean::inline`), but this is not always a //! non-lossy transformation. The current format of storage for where clauses //! for functions and such is simply a list of predicates. One example of this //! is that the AST predicate of: //! //! where T: Trait<Foo=Bar> //! //! is encoded as: //! //! where T: Trait, <T as Trait>::Foo = Bar //! //! This module attempts to reconstruct the original where and/or parameter //! bounds by special casing scenarios such as these. Fun! use std::mem; use std::collections::HashMap; use rustc::middle::subst; use rustc::middle::ty; use syntax::ast; use clean::PathParameters as PP; use clean::WherePredicate as WP; use clean::{self, Clean}; use core::DocContext; pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> { // First, partition the where clause into its separate components let mut params = HashMap::new(); let mut lifetimes = Vec::new(); let mut equalities = Vec::new(); let mut tybounds = Vec::new(); for clause in clauses { match clause { WP::BoundPredicate { ty, bounds } => { match ty { clean::Generic(s) => params.entry(s).or_insert(Vec::new()) .extend(bounds), t => tybounds.push((t, ty_bounds(bounds))), } } WP::RegionPredicate { lifetime, bounds } => { lifetimes.push((lifetime, bounds)); } WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)), } } // Simplify the type parameter bounds on all the generics let mut params = params.into_iter().map(|(k, v)| { (k, ty_bounds(v)) }).collect::<HashMap<_, _>>(); // Look for equality predicates on associated types that can be merged into // general bound predicates equalities.retain(|&(ref lhs, ref rhs)| { let (self_, trait_, name) = match *lhs { clean::QPath { ref self_type, ref trait_, ref name } => { (self_type, trait_, name) } _ => return true, }; let generic = match **self_ { clean::Generic(ref s) => s, _ => return true, }; let trait_did = match **trait_ { clean::ResolvedPath { did,.. } => did, _ => return true, }; let bounds = match params.get_mut(generic) { Some(bound) => bound, None => return true, }; !bounds.iter_mut().any(|b| { let trait_ref = match *b { clean::TraitBound(ref mut tr, _) => tr, clean::RegionBound(..) => return false, }; let (did, path) = match trait_ref.trait_ { clean::ResolvedPath { did, ref mut path,..} => (did, path), _ => return false, }; // If this QPath's trait `trait_did` is the same as, or a supertrait // of, the bound's trait `did` then we can keep going, otherwise // this is just a plain old equality bound. if!trait_is_same_or_supertrait(cx, did, trait_did) { return false } let last = path.segments.last_mut().unwrap(); match last.params { PP::AngleBracketed { ref mut bindings,.. } => { bindings.push(clean::TypeBinding { name: name.clone(), ty: rhs.clone(), }); } PP::Parenthesized { ref mut output,.. } => { assert!(output.is_none()); *output = Some(rhs.clone()); } }; true }) }); // And finally, let's reassemble everything let mut clauses = Vec::new(); clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| { WP::RegionPredicate { lifetime: lt, bounds: bounds } })); clauses.extend(params.into_iter().map(|(k, v)| { WP::BoundPredicate { ty: clean::Generic(k), bounds: v, } })); clauses.extend(tybounds.into_iter().map(|(ty, bounds)| { WP::BoundPredicate { ty: ty, bounds: bounds } })); clauses.extend(equalities.into_iter().map(|(lhs, rhs)| { WP::EqPredicate { lhs: lhs, rhs: rhs } })); clauses } pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> { for param in params.iter_mut() { param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new())); } return params; } fn ty_bounds(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> { bounds } fn trait_is_same_or_supertrait(cx: &DocContext, child: ast::DefId, trait_: ast::DefId) -> bool { if child == trait_ { return true } let def = ty::lookup_trait_def(cx.tcx(), child); let predicates = ty::lookup_predicates(cx.tcx(), child); let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx); generics.where_predicates.iter().filter_map(|pred| { match *pred { clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds } if *s == "Self" => Some(bounds), _ => None, } }).flat_map(|bounds| bounds.iter()).any(|bound| { let poly_trait = match *bound { clean::TraitBound(ref t, _) => t, _ => return false,
clean::ResolvedPath { did,.. } => { trait_is_same_or_supertrait(cx, did, trait_) } _ => false, } }) }
}; match poly_trait.trait_ {
random_line_split
simplify.rs
// 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. //! Simplification of where clauses and parameter bounds into a prettier and //! more canonical form. //! //! Currently all cross-crate-inlined function use `middle::ty` to reconstruct //! the AST (e.g. see all of `clean::inline`), but this is not always a //! non-lossy transformation. The current format of storage for where clauses //! for functions and such is simply a list of predicates. One example of this //! is that the AST predicate of: //! //! where T: Trait<Foo=Bar> //! //! is encoded as: //! //! where T: Trait, <T as Trait>::Foo = Bar //! //! This module attempts to reconstruct the original where and/or parameter //! bounds by special casing scenarios such as these. Fun! use std::mem; use std::collections::HashMap; use rustc::middle::subst; use rustc::middle::ty; use syntax::ast; use clean::PathParameters as PP; use clean::WherePredicate as WP; use clean::{self, Clean}; use core::DocContext; pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> { // First, partition the where clause into its separate components let mut params = HashMap::new(); let mut lifetimes = Vec::new(); let mut equalities = Vec::new(); let mut tybounds = Vec::new(); for clause in clauses { match clause { WP::BoundPredicate { ty, bounds } => { match ty { clean::Generic(s) => params.entry(s).or_insert(Vec::new()) .extend(bounds), t => tybounds.push((t, ty_bounds(bounds))), } } WP::RegionPredicate { lifetime, bounds } => { lifetimes.push((lifetime, bounds)); } WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)), } } // Simplify the type parameter bounds on all the generics let mut params = params.into_iter().map(|(k, v)| { (k, ty_bounds(v)) }).collect::<HashMap<_, _>>(); // Look for equality predicates on associated types that can be merged into // general bound predicates equalities.retain(|&(ref lhs, ref rhs)| { let (self_, trait_, name) = match *lhs { clean::QPath { ref self_type, ref trait_, ref name } => { (self_type, trait_, name) } _ => return true, }; let generic = match **self_ { clean::Generic(ref s) => s, _ => return true, }; let trait_did = match **trait_ { clean::ResolvedPath { did,.. } => did, _ => return true, }; let bounds = match params.get_mut(generic) { Some(bound) => bound, None => return true, }; !bounds.iter_mut().any(|b| { let trait_ref = match *b { clean::TraitBound(ref mut tr, _) => tr, clean::RegionBound(..) => return false, }; let (did, path) = match trait_ref.trait_ { clean::ResolvedPath { did, ref mut path,..} => (did, path), _ => return false, }; // If this QPath's trait `trait_did` is the same as, or a supertrait // of, the bound's trait `did` then we can keep going, otherwise // this is just a plain old equality bound. if!trait_is_same_or_supertrait(cx, did, trait_did) { return false } let last = path.segments.last_mut().unwrap(); match last.params { PP::AngleBracketed { ref mut bindings,.. } => { bindings.push(clean::TypeBinding { name: name.clone(), ty: rhs.clone(), }); } PP::Parenthesized { ref mut output,.. } =>
}; true }) }); // And finally, let's reassemble everything let mut clauses = Vec::new(); clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| { WP::RegionPredicate { lifetime: lt, bounds: bounds } })); clauses.extend(params.into_iter().map(|(k, v)| { WP::BoundPredicate { ty: clean::Generic(k), bounds: v, } })); clauses.extend(tybounds.into_iter().map(|(ty, bounds)| { WP::BoundPredicate { ty: ty, bounds: bounds } })); clauses.extend(equalities.into_iter().map(|(lhs, rhs)| { WP::EqPredicate { lhs: lhs, rhs: rhs } })); clauses } pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> { for param in params.iter_mut() { param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new())); } return params; } fn ty_bounds(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> { bounds } fn trait_is_same_or_supertrait(cx: &DocContext, child: ast::DefId, trait_: ast::DefId) -> bool { if child == trait_ { return true } let def = ty::lookup_trait_def(cx.tcx(), child); let predicates = ty::lookup_predicates(cx.tcx(), child); let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx); generics.where_predicates.iter().filter_map(|pred| { match *pred { clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds } if *s == "Self" => Some(bounds), _ => None, } }).flat_map(|bounds| bounds.iter()).any(|bound| { let poly_trait = match *bound { clean::TraitBound(ref t, _) => t, _ => return false, }; match poly_trait.trait_ { clean::ResolvedPath { did,.. } => { trait_is_same_or_supertrait(cx, did, trait_) } _ => false, } }) }
{ assert!(output.is_none()); *output = Some(rhs.clone()); }
conditional_block
simplify.rs
// 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. //! Simplification of where clauses and parameter bounds into a prettier and //! more canonical form. //! //! Currently all cross-crate-inlined function use `middle::ty` to reconstruct //! the AST (e.g. see all of `clean::inline`), but this is not always a //! non-lossy transformation. The current format of storage for where clauses //! for functions and such is simply a list of predicates. One example of this //! is that the AST predicate of: //! //! where T: Trait<Foo=Bar> //! //! is encoded as: //! //! where T: Trait, <T as Trait>::Foo = Bar //! //! This module attempts to reconstruct the original where and/or parameter //! bounds by special casing scenarios such as these. Fun! use std::mem; use std::collections::HashMap; use rustc::middle::subst; use rustc::middle::ty; use syntax::ast; use clean::PathParameters as PP; use clean::WherePredicate as WP; use clean::{self, Clean}; use core::DocContext; pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> { // First, partition the where clause into its separate components let mut params = HashMap::new(); let mut lifetimes = Vec::new(); let mut equalities = Vec::new(); let mut tybounds = Vec::new(); for clause in clauses { match clause { WP::BoundPredicate { ty, bounds } => { match ty { clean::Generic(s) => params.entry(s).or_insert(Vec::new()) .extend(bounds), t => tybounds.push((t, ty_bounds(bounds))), } } WP::RegionPredicate { lifetime, bounds } => { lifetimes.push((lifetime, bounds)); } WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)), } } // Simplify the type parameter bounds on all the generics let mut params = params.into_iter().map(|(k, v)| { (k, ty_bounds(v)) }).collect::<HashMap<_, _>>(); // Look for equality predicates on associated types that can be merged into // general bound predicates equalities.retain(|&(ref lhs, ref rhs)| { let (self_, trait_, name) = match *lhs { clean::QPath { ref self_type, ref trait_, ref name } => { (self_type, trait_, name) } _ => return true, }; let generic = match **self_ { clean::Generic(ref s) => s, _ => return true, }; let trait_did = match **trait_ { clean::ResolvedPath { did,.. } => did, _ => return true, }; let bounds = match params.get_mut(generic) { Some(bound) => bound, None => return true, }; !bounds.iter_mut().any(|b| { let trait_ref = match *b { clean::TraitBound(ref mut tr, _) => tr, clean::RegionBound(..) => return false, }; let (did, path) = match trait_ref.trait_ { clean::ResolvedPath { did, ref mut path,..} => (did, path), _ => return false, }; // If this QPath's trait `trait_did` is the same as, or a supertrait // of, the bound's trait `did` then we can keep going, otherwise // this is just a plain old equality bound. if!trait_is_same_or_supertrait(cx, did, trait_did) { return false } let last = path.segments.last_mut().unwrap(); match last.params { PP::AngleBracketed { ref mut bindings,.. } => { bindings.push(clean::TypeBinding { name: name.clone(), ty: rhs.clone(), }); } PP::Parenthesized { ref mut output,.. } => { assert!(output.is_none()); *output = Some(rhs.clone()); } }; true }) }); // And finally, let's reassemble everything let mut clauses = Vec::new(); clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| { WP::RegionPredicate { lifetime: lt, bounds: bounds } })); clauses.extend(params.into_iter().map(|(k, v)| { WP::BoundPredicate { ty: clean::Generic(k), bounds: v, } })); clauses.extend(tybounds.into_iter().map(|(ty, bounds)| { WP::BoundPredicate { ty: ty, bounds: bounds } })); clauses.extend(equalities.into_iter().map(|(lhs, rhs)| { WP::EqPredicate { lhs: lhs, rhs: rhs } })); clauses } pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> { for param in params.iter_mut() { param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new())); } return params; } fn ty_bounds(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound>
fn trait_is_same_or_supertrait(cx: &DocContext, child: ast::DefId, trait_: ast::DefId) -> bool { if child == trait_ { return true } let def = ty::lookup_trait_def(cx.tcx(), child); let predicates = ty::lookup_predicates(cx.tcx(), child); let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx); generics.where_predicates.iter().filter_map(|pred| { match *pred { clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds } if *s == "Self" => Some(bounds), _ => None, } }).flat_map(|bounds| bounds.iter()).any(|bound| { let poly_trait = match *bound { clean::TraitBound(ref t, _) => t, _ => return false, }; match poly_trait.trait_ { clean::ResolvedPath { did,.. } => { trait_is_same_or_supertrait(cx, did, trait_) } _ => false, } }) }
{ bounds }
identifier_body
problem_14.rs
fn collatz(num: u32) -> u32 { if num == 1 { return num; } if num % 2 == 0 { num / 2 } else { (num * 3) + 1 } } fn main() { let mut max_terms: u32 = 0; let mut max_terms_number: u32 = 0; for i in 2..1_000_001 { let mut current_terms: u32 = 0; let mut result: u32 = i; while result!= 1 { result = collatz(result);
current_terms += 1; if current_terms > max_terms { max_terms = current_terms; max_terms_number = i; } } // println!("collatz({}) -> {}", i, current_terms); } println!("Result: {}", max_terms_number); }
random_line_split
problem_14.rs
fn
(num: u32) -> u32 { if num == 1 { return num; } if num % 2 == 0 { num / 2 } else { (num * 3) + 1 } } fn main() { let mut max_terms: u32 = 0; let mut max_terms_number: u32 = 0; for i in 2..1_000_001 { let mut current_terms: u32 = 0; let mut result: u32 = i; while result!= 1 { result = collatz(result); current_terms += 1; if current_terms > max_terms { max_terms = current_terms; max_terms_number = i; } } // println!("collatz({}) -> {}", i, current_terms); } println!("Result: {}", max_terms_number); }
collatz
identifier_name
problem_14.rs
fn collatz(num: u32) -> u32 { if num == 1
if num % 2 == 0 { num / 2 } else { (num * 3) + 1 } } fn main() { let mut max_terms: u32 = 0; let mut max_terms_number: u32 = 0; for i in 2..1_000_001 { let mut current_terms: u32 = 0; let mut result: u32 = i; while result!= 1 { result = collatz(result); current_terms += 1; if current_terms > max_terms { max_terms = current_terms; max_terms_number = i; } } // println!("collatz({}) -> {}", i, current_terms); } println!("Result: {}", max_terms_number); }
{ return num; }
conditional_block
problem_14.rs
fn collatz(num: u32) -> u32 { if num == 1 { return num; } if num % 2 == 0 { num / 2 } else { (num * 3) + 1 } } fn main()
{ let mut max_terms: u32 = 0; let mut max_terms_number: u32 = 0; for i in 2..1_000_001 { let mut current_terms: u32 = 0; let mut result: u32 = i; while result != 1 { result = collatz(result); current_terms += 1; if current_terms > max_terms { max_terms = current_terms; max_terms_number = i; } } // println!("collatz({}) -> {}", i, current_terms); } println!("Result: {}", max_terms_number); }
identifier_body
client.rs
/* * Copyright 2015-2016 Torrie Fischer <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::BTreeMap; use std::collections::HashMap; use hyper; use rustc_serialize::json::Json; use rustc_serialize::json; use std::fmt; use std::result; use matrix::json as mjson; use matrix::events; use matrix::model; enum ApiVersion { R0, V1, V2Alpha } #[derive(Debug)] pub enum ClientError { Http(hyper::Error), UrlNotFound(hyper::Url), BadStatus(hyper::status::StatusCode), Json(json::ParserError) } pub type Result<T = ()> = result::Result<T, ClientError>; mod http { use rustc_serialize::json::Json; use hyper; use std::io::Read; use matrix::client::{Result,ClientError}; pub fn json(http: hyper::client::RequestBuilder) -> Result<Json> { let mut response = String::new(); http.send().map_err(|err|{ ClientError::Http(err) }).and_then(|mut res|{ match res.status { hyper::status::StatusCode::Ok => { res.read_to_string(&mut response).expect("Could not read response"); Json::from_str(&response).map_err(|err|{ ClientError::Json(err) }) }, hyper::status::StatusCode::NotFound => Err(ClientError::UrlNotFound(res.url.clone())), s => Err(ClientError::BadStatus(s)) } }) } } pub struct AsyncPoll { http: hyper::client::Client, url: hyper::Url } impl AsyncPoll { fn do_room_events(events: &mut Vec<events::Event>, json: &Vec<Json>, id: &String) { for ref evt in json { if cfg!(raw_logs) { trace!("<<< {}", evt); } let mut e = evt.as_object().unwrap().clone(); e.insert("room_id".to_string(), Json::String(id.clone())); // FIXME: It'd be nice to return to the previous // callback-based mechanism to avoid memory bloat events.push(events::Event::from_json(&Json::Object(e))); }; } pub fn send(self) -> Result<Vec<events::Event>> { http::json(self.http.get(self.url)).and_then(|json| { if cfg!(raw_logs) { trace!("Got JSON! {}", json.pretty()); } let mut ret: Vec<events::Event> = vec![]; let presence = mjson::path(&json, "presence.events").as_array().unwrap(); for ref p in presence { ret.push(events::Event::from_json(&Json::Object(p.as_object().unwrap().clone()))); }; let joined_rooms = mjson::path(&json, "rooms.join").as_object().unwrap(); for (id, r) in joined_rooms { AsyncPoll::do_room_events(&mut ret, mjson::array(r, "state.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "timeline.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "account_data.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "ephemeral.events"), id); }; let next_token = mjson::string(&json, "next_batch").to_string(); ret.push(events::Event { age: 0, data: events::EventData::EndOfSync(next_token), id: None }); Ok(ret) }) } } #[derive(Clone)] pub struct AccessToken { access: String, refresh: String } pub struct Client { http: hyper::Client, token: Option<AccessToken>, next_id: u32, baseurl: hyper::Url, pub uid: Option<model::UserID> } impl fmt::Debug for Client { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Client { pub fn new(baseurl: hyper::Url) -> Self { if!baseurl.scheme.starts_with("https") { warn!("YOU ARE CONNECTING TO A MATRIX SERVER WITHOUT SSL"); } let mut http = hyper::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); Client { http: http, token: None, next_id: 0, baseurl: baseurl, uid: None } } pub fn anon_login(&mut self) -> Result { let mut query_args = HashMap::new(); query_args.insert("kind", "guest"); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::R0, "register", &query_args))) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: String::new() }); self.uid = Some(model::UserID::from_str(obj.get("user_id").unwrap().as_string().unwrap())); Ok(()) }) } pub fn login(&mut self, username: &str, password: &str) -> Result { let mut d = BTreeMap::new(); d.insert("user".to_string(), Json::String(username.to_string())); d.insert("password".to_string(), Json::String(password.to_string())); d.insert("type".to_string(), Json::String("m.login.password".to_string())); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::V1, "login", &HashMap::new())) .body(&Json::Object(d).to_string())) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: obj.get("refresh_token").unwrap().as_string().unwrap().to_string() }); let domain = self.baseurl.host().unwrap().serialize(); self.uid = Some(model::UserID::from_str(&format!("@{}:{}", username, domain))); Ok(()) }) } fn url(&self, version: ApiVersion, endpoint: &str, args: &HashMap<&str, &str>) -> hyper::Url { let mut ret = self.baseurl.clone(); ret.path_mut().unwrap().append(&mut vec!["client".to_string()]); ret.path_mut().unwrap().append(&mut match version { ApiVersion::R0 => vec!["r0".to_string()], ApiVersion::V1 => vec!["api".to_string(), "v1".to_string()], ApiVersion::V2Alpha => vec!["v2_alpha".to_string()] }); ret.path_mut().unwrap().push(endpoint.to_string()); let args_with_auth = match self.token { None => args.clone(), Some(ref token) => { let mut a = args.clone(); a.insert("access_token", &*token.access); a } }; ret.set_query_from_pairs(args_with_auth); ret } pub fn
(&mut self, token: Option<&str>) -> AsyncPoll { let mut args = HashMap::new(); if let Some(next) = token { args.insert("since", next); args.insert("timeout", "5000"); } else { args.insert("full_state", "true"); } let url = self.url(ApiVersion::V2Alpha, "sync", &args); let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); AsyncPoll { http: http, url: url } } pub fn send(&mut self, evt: events::EventData) -> Result<model::EventID> { self.next_id += 1; match evt { events::EventData::Room(ref id, _) => { let url = self.url(ApiVersion::V1, &format!("rooms/{}/send/{}/{}", id, evt.type_str(), self.next_id), &HashMap::new()); trace!("Sending events to {:?}", url); // FIXME: This seems needed since hyper will pool HTTP client // connections for pipelining. Sometimes the server will close // the pooled connection and everything will catch on fire here. let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); http::json(http.put(url).body(&format!("{}", evt.to_json()))) }, _ => panic!("Don't know where to send {}", evt.to_json()) }.and_then(|response| { if cfg!(raw_logs) { trace!(">>> {} {:?}", evt.to_json(), response); } Ok(model::EventID::from_str(mjson::string(&response, "event_id"))) }) } }
sync
identifier_name
client.rs
/*
* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::BTreeMap; use std::collections::HashMap; use hyper; use rustc_serialize::json::Json; use rustc_serialize::json; use std::fmt; use std::result; use matrix::json as mjson; use matrix::events; use matrix::model; enum ApiVersion { R0, V1, V2Alpha } #[derive(Debug)] pub enum ClientError { Http(hyper::Error), UrlNotFound(hyper::Url), BadStatus(hyper::status::StatusCode), Json(json::ParserError) } pub type Result<T = ()> = result::Result<T, ClientError>; mod http { use rustc_serialize::json::Json; use hyper; use std::io::Read; use matrix::client::{Result,ClientError}; pub fn json(http: hyper::client::RequestBuilder) -> Result<Json> { let mut response = String::new(); http.send().map_err(|err|{ ClientError::Http(err) }).and_then(|mut res|{ match res.status { hyper::status::StatusCode::Ok => { res.read_to_string(&mut response).expect("Could not read response"); Json::from_str(&response).map_err(|err|{ ClientError::Json(err) }) }, hyper::status::StatusCode::NotFound => Err(ClientError::UrlNotFound(res.url.clone())), s => Err(ClientError::BadStatus(s)) } }) } } pub struct AsyncPoll { http: hyper::client::Client, url: hyper::Url } impl AsyncPoll { fn do_room_events(events: &mut Vec<events::Event>, json: &Vec<Json>, id: &String) { for ref evt in json { if cfg!(raw_logs) { trace!("<<< {}", evt); } let mut e = evt.as_object().unwrap().clone(); e.insert("room_id".to_string(), Json::String(id.clone())); // FIXME: It'd be nice to return to the previous // callback-based mechanism to avoid memory bloat events.push(events::Event::from_json(&Json::Object(e))); }; } pub fn send(self) -> Result<Vec<events::Event>> { http::json(self.http.get(self.url)).and_then(|json| { if cfg!(raw_logs) { trace!("Got JSON! {}", json.pretty()); } let mut ret: Vec<events::Event> = vec![]; let presence = mjson::path(&json, "presence.events").as_array().unwrap(); for ref p in presence { ret.push(events::Event::from_json(&Json::Object(p.as_object().unwrap().clone()))); }; let joined_rooms = mjson::path(&json, "rooms.join").as_object().unwrap(); for (id, r) in joined_rooms { AsyncPoll::do_room_events(&mut ret, mjson::array(r, "state.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "timeline.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "account_data.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "ephemeral.events"), id); }; let next_token = mjson::string(&json, "next_batch").to_string(); ret.push(events::Event { age: 0, data: events::EventData::EndOfSync(next_token), id: None }); Ok(ret) }) } } #[derive(Clone)] pub struct AccessToken { access: String, refresh: String } pub struct Client { http: hyper::Client, token: Option<AccessToken>, next_id: u32, baseurl: hyper::Url, pub uid: Option<model::UserID> } impl fmt::Debug for Client { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Client { pub fn new(baseurl: hyper::Url) -> Self { if!baseurl.scheme.starts_with("https") { warn!("YOU ARE CONNECTING TO A MATRIX SERVER WITHOUT SSL"); } let mut http = hyper::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); Client { http: http, token: None, next_id: 0, baseurl: baseurl, uid: None } } pub fn anon_login(&mut self) -> Result { let mut query_args = HashMap::new(); query_args.insert("kind", "guest"); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::R0, "register", &query_args))) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: String::new() }); self.uid = Some(model::UserID::from_str(obj.get("user_id").unwrap().as_string().unwrap())); Ok(()) }) } pub fn login(&mut self, username: &str, password: &str) -> Result { let mut d = BTreeMap::new(); d.insert("user".to_string(), Json::String(username.to_string())); d.insert("password".to_string(), Json::String(password.to_string())); d.insert("type".to_string(), Json::String("m.login.password".to_string())); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::V1, "login", &HashMap::new())) .body(&Json::Object(d).to_string())) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: obj.get("refresh_token").unwrap().as_string().unwrap().to_string() }); let domain = self.baseurl.host().unwrap().serialize(); self.uid = Some(model::UserID::from_str(&format!("@{}:{}", username, domain))); Ok(()) }) } fn url(&self, version: ApiVersion, endpoint: &str, args: &HashMap<&str, &str>) -> hyper::Url { let mut ret = self.baseurl.clone(); ret.path_mut().unwrap().append(&mut vec!["client".to_string()]); ret.path_mut().unwrap().append(&mut match version { ApiVersion::R0 => vec!["r0".to_string()], ApiVersion::V1 => vec!["api".to_string(), "v1".to_string()], ApiVersion::V2Alpha => vec!["v2_alpha".to_string()] }); ret.path_mut().unwrap().push(endpoint.to_string()); let args_with_auth = match self.token { None => args.clone(), Some(ref token) => { let mut a = args.clone(); a.insert("access_token", &*token.access); a } }; ret.set_query_from_pairs(args_with_auth); ret } pub fn sync(&mut self, token: Option<&str>) -> AsyncPoll { let mut args = HashMap::new(); if let Some(next) = token { args.insert("since", next); args.insert("timeout", "5000"); } else { args.insert("full_state", "true"); } let url = self.url(ApiVersion::V2Alpha, "sync", &args); let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); AsyncPoll { http: http, url: url } } pub fn send(&mut self, evt: events::EventData) -> Result<model::EventID> { self.next_id += 1; match evt { events::EventData::Room(ref id, _) => { let url = self.url(ApiVersion::V1, &format!("rooms/{}/send/{}/{}", id, evt.type_str(), self.next_id), &HashMap::new()); trace!("Sending events to {:?}", url); // FIXME: This seems needed since hyper will pool HTTP client // connections for pipelining. Sometimes the server will close // the pooled connection and everything will catch on fire here. let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); http::json(http.put(url).body(&format!("{}", evt.to_json()))) }, _ => panic!("Don't know where to send {}", evt.to_json()) }.and_then(|response| { if cfg!(raw_logs) { trace!(">>> {} {:?}", evt.to_json(), response); } Ok(model::EventID::from_str(mjson::string(&response, "event_id"))) }) } }
* Copyright 2015-2016 Torrie Fischer <[email protected]>
random_line_split
client.rs
/* * Copyright 2015-2016 Torrie Fischer <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::BTreeMap; use std::collections::HashMap; use hyper; use rustc_serialize::json::Json; use rustc_serialize::json; use std::fmt; use std::result; use matrix::json as mjson; use matrix::events; use matrix::model; enum ApiVersion { R0, V1, V2Alpha } #[derive(Debug)] pub enum ClientError { Http(hyper::Error), UrlNotFound(hyper::Url), BadStatus(hyper::status::StatusCode), Json(json::ParserError) } pub type Result<T = ()> = result::Result<T, ClientError>; mod http { use rustc_serialize::json::Json; use hyper; use std::io::Read; use matrix::client::{Result,ClientError}; pub fn json(http: hyper::client::RequestBuilder) -> Result<Json> { let mut response = String::new(); http.send().map_err(|err|{ ClientError::Http(err) }).and_then(|mut res|{ match res.status { hyper::status::StatusCode::Ok => { res.read_to_string(&mut response).expect("Could not read response"); Json::from_str(&response).map_err(|err|{ ClientError::Json(err) }) }, hyper::status::StatusCode::NotFound => Err(ClientError::UrlNotFound(res.url.clone())), s => Err(ClientError::BadStatus(s)) } }) } } pub struct AsyncPoll { http: hyper::client::Client, url: hyper::Url } impl AsyncPoll { fn do_room_events(events: &mut Vec<events::Event>, json: &Vec<Json>, id: &String) { for ref evt in json { if cfg!(raw_logs) { trace!("<<< {}", evt); } let mut e = evt.as_object().unwrap().clone(); e.insert("room_id".to_string(), Json::String(id.clone())); // FIXME: It'd be nice to return to the previous // callback-based mechanism to avoid memory bloat events.push(events::Event::from_json(&Json::Object(e))); }; } pub fn send(self) -> Result<Vec<events::Event>> { http::json(self.http.get(self.url)).and_then(|json| { if cfg!(raw_logs) { trace!("Got JSON! {}", json.pretty()); } let mut ret: Vec<events::Event> = vec![]; let presence = mjson::path(&json, "presence.events").as_array().unwrap(); for ref p in presence { ret.push(events::Event::from_json(&Json::Object(p.as_object().unwrap().clone()))); }; let joined_rooms = mjson::path(&json, "rooms.join").as_object().unwrap(); for (id, r) in joined_rooms { AsyncPoll::do_room_events(&mut ret, mjson::array(r, "state.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "timeline.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "account_data.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "ephemeral.events"), id); }; let next_token = mjson::string(&json, "next_batch").to_string(); ret.push(events::Event { age: 0, data: events::EventData::EndOfSync(next_token), id: None }); Ok(ret) }) } } #[derive(Clone)] pub struct AccessToken { access: String, refresh: String } pub struct Client { http: hyper::Client, token: Option<AccessToken>, next_id: u32, baseurl: hyper::Url, pub uid: Option<model::UserID> } impl fmt::Debug for Client { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Client { pub fn new(baseurl: hyper::Url) -> Self { if!baseurl.scheme.starts_with("https") { warn!("YOU ARE CONNECTING TO A MATRIX SERVER WITHOUT SSL"); } let mut http = hyper::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); Client { http: http, token: None, next_id: 0, baseurl: baseurl, uid: None } } pub fn anon_login(&mut self) -> Result { let mut query_args = HashMap::new(); query_args.insert("kind", "guest"); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::R0, "register", &query_args))) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: String::new() }); self.uid = Some(model::UserID::from_str(obj.get("user_id").unwrap().as_string().unwrap())); Ok(()) }) } pub fn login(&mut self, username: &str, password: &str) -> Result
fn url(&self, version: ApiVersion, endpoint: &str, args: &HashMap<&str, &str>) -> hyper::Url { let mut ret = self.baseurl.clone(); ret.path_mut().unwrap().append(&mut vec!["client".to_string()]); ret.path_mut().unwrap().append(&mut match version { ApiVersion::R0 => vec!["r0".to_string()], ApiVersion::V1 => vec!["api".to_string(), "v1".to_string()], ApiVersion::V2Alpha => vec!["v2_alpha".to_string()] }); ret.path_mut().unwrap().push(endpoint.to_string()); let args_with_auth = match self.token { None => args.clone(), Some(ref token) => { let mut a = args.clone(); a.insert("access_token", &*token.access); a } }; ret.set_query_from_pairs(args_with_auth); ret } pub fn sync(&mut self, token: Option<&str>) -> AsyncPoll { let mut args = HashMap::new(); if let Some(next) = token { args.insert("since", next); args.insert("timeout", "5000"); } else { args.insert("full_state", "true"); } let url = self.url(ApiVersion::V2Alpha, "sync", &args); let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); AsyncPoll { http: http, url: url } } pub fn send(&mut self, evt: events::EventData) -> Result<model::EventID> { self.next_id += 1; match evt { events::EventData::Room(ref id, _) => { let url = self.url(ApiVersion::V1, &format!("rooms/{}/send/{}/{}", id, evt.type_str(), self.next_id), &HashMap::new()); trace!("Sending events to {:?}", url); // FIXME: This seems needed since hyper will pool HTTP client // connections for pipelining. Sometimes the server will close // the pooled connection and everything will catch on fire here. let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); http::json(http.put(url).body(&format!("{}", evt.to_json()))) }, _ => panic!("Don't know where to send {}", evt.to_json()) }.and_then(|response| { if cfg!(raw_logs) { trace!(">>> {} {:?}", evt.to_json(), response); } Ok(model::EventID::from_str(mjson::string(&response, "event_id"))) }) } }
{ let mut d = BTreeMap::new(); d.insert("user".to_string(), Json::String(username.to_string())); d.insert("password".to_string(), Json::String(password.to_string())); d.insert("type".to_string(), Json::String("m.login.password".to_string())); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::V1, "login", &HashMap::new())) .body(&Json::Object(d).to_string())) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: obj.get("refresh_token").unwrap().as_string().unwrap().to_string() }); let domain = self.baseurl.host().unwrap().serialize(); self.uid = Some(model::UserID::from_str(&format!("@{}:{}", username, domain))); Ok(()) }) }
identifier_body
gather_moves.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Computes moves. use borrowck::*; use borrowck::gather_loans::move_error::MoveSpanAndPath; use borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector}; use borrowck::move_data::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::InteriorOffsetKind as Kind; use rustc::middle::ty; use std::rc::Rc; use syntax::ast; use syntax::codemap::Span; struct GatherMoveInfo<'tcx> { id: ast::NodeId, kind: MoveKind, cmt: mc::cmt<'tcx>, span_path_opt: Option<MoveSpanAndPath> } pub fn gather_decl<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, decl_id: ast::NodeId, _decl_span: Span, var_id: ast::NodeId) { let ty = bccx.tcx.node_id_to_type(var_id); let loan_path = Rc::new(LoanPath::new(LpVar(var_id), ty)); move_data.add_move(bccx.tcx, loan_path, decl_id, Declared); } pub fn gather_move_from_expr<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_expr_id: ast::NodeId, cmt: mc::cmt<'tcx>, move_reason: euv::MoveReason) { let kind = match move_reason { euv::DirectRefMove | euv::PatBindingMove => MoveExpr, euv::CaptureMove => Captured }; let move_info = GatherMoveInfo { id: move_expr_id, kind: kind, cmt: cmt, span_path_opt: None, }; gather_move(bccx, move_data, move_error_collector, move_info); } pub fn gather_match_variant<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, _move_error_collector: &MoveErrorCollector<'tcx>, move_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { let tcx = bccx.tcx; debug!("gather_match_variant(move_pat={}, cmt={:?}, mode={:?})", move_pat.id, cmt, mode); let opt_lp = opt_loan_path(&cmt); match opt_lp { Some(lp) => { match lp.kind { LpDowncast(ref base_lp, _) => move_data.add_variant_match( tcx, lp.clone(), move_pat.id, base_lp.clone(), mode), _ => panic!("should only call gather_match_variant \ for cat_downcast cmt"), } } None => { // We get None when input to match is non-path (e.g. // temporary result like a function call). Since no // loan-path is being matched, no need to record a // downcast. return; } } } pub fn gather_move_from_pat<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_pat: &ast::Pat, cmt: mc::cmt<'tcx>) { let pat_span_path_opt = match move_pat.node { ast::PatIdent(_, ref path1, _) => { Some(MoveSpanAndPath{span: move_pat.span, ident: path1.node}) }, _ => None, }; let move_info = GatherMoveInfo { id: move_pat.id, kind: MovePat, cmt: cmt, span_path_opt: pat_span_path_opt, }; gather_move(bccx, move_data, move_error_collector, move_info); } fn gather_move<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_info: GatherMoveInfo<'tcx>) { debug!("gather_move(move_id={}, cmt={:?})", move_info.id, move_info.cmt); let potentially_illegal_move = check_and_get_illegal_move_origin(bccx, &move_info.cmt); match potentially_illegal_move { Some(illegal_move_origin) => { debug!("illegal_move_origin={:?}", illegal_move_origin); let error = MoveError::with_move_info(illegal_move_origin, move_info.span_path_opt); move_error_collector.add_error(error); return } None => () } match opt_loan_path(&move_info.cmt) { Some(loan_path) => { move_data.add_move(bccx.tcx, loan_path, move_info.id, move_info.kind); } None => { // move from rvalue or raw pointer, hence ok } } } pub fn gather_assignment<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, assignment_id: ast::NodeId, assignment_span: Span, assignee_loan_path: Rc<LoanPath<'tcx>>, assignee_id: ast::NodeId,
assignment_id, assignment_span, assignee_id, mode); } // (keep in sync with move_error::report_cannot_move_out_of ) fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, cmt: &mc::cmt<'tcx>) -> Option<mc::cmt<'tcx>> { match cmt.cat { mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_static_item => { Some(cmt.clone()) } mc::cat_rvalue(..) | mc::cat_local(..) | mc::cat_upvar(..) => { None } mc::cat_downcast(ref b, _) | mc::cat_interior(ref b, mc::InteriorField(_)) | mc::cat_interior(ref b, mc::InteriorElement(Kind::Pattern, _)) => { match b.ty.sty { ty::TyStruct(def, _) | ty::TyEnum(def, _) => { if def.has_dtor(bccx.tcx) { Some(cmt.clone()) } else { check_and_get_illegal_move_origin(bccx, b) } } _ => { check_and_get_illegal_move_origin(bccx, b) } } } mc::cat_interior(_, mc::InteriorElement(Kind::Index, _)) => { // Forbid move of arr[i] for arr: [T; 3]; see RFC 533. Some(cmt.clone()) } mc::cat_deref(ref b, _, mc::Unique) => { check_and_get_illegal_move_origin(bccx, b) } } }
mode: euv::MutateMode) { move_data.add_assignment(bccx.tcx, assignee_loan_path,
random_line_split
gather_moves.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Computes moves. use borrowck::*; use borrowck::gather_loans::move_error::MoveSpanAndPath; use borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector}; use borrowck::move_data::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::InteriorOffsetKind as Kind; use rustc::middle::ty; use std::rc::Rc; use syntax::ast; use syntax::codemap::Span; struct GatherMoveInfo<'tcx> { id: ast::NodeId, kind: MoveKind, cmt: mc::cmt<'tcx>, span_path_opt: Option<MoveSpanAndPath> } pub fn gather_decl<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, decl_id: ast::NodeId, _decl_span: Span, var_id: ast::NodeId) { let ty = bccx.tcx.node_id_to_type(var_id); let loan_path = Rc::new(LoanPath::new(LpVar(var_id), ty)); move_data.add_move(bccx.tcx, loan_path, decl_id, Declared); } pub fn gather_move_from_expr<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_expr_id: ast::NodeId, cmt: mc::cmt<'tcx>, move_reason: euv::MoveReason)
pub fn gather_match_variant<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, _move_error_collector: &MoveErrorCollector<'tcx>, move_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { let tcx = bccx.tcx; debug!("gather_match_variant(move_pat={}, cmt={:?}, mode={:?})", move_pat.id, cmt, mode); let opt_lp = opt_loan_path(&cmt); match opt_lp { Some(lp) => { match lp.kind { LpDowncast(ref base_lp, _) => move_data.add_variant_match( tcx, lp.clone(), move_pat.id, base_lp.clone(), mode), _ => panic!("should only call gather_match_variant \ for cat_downcast cmt"), } } None => { // We get None when input to match is non-path (e.g. // temporary result like a function call). Since no // loan-path is being matched, no need to record a // downcast. return; } } } pub fn gather_move_from_pat<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_pat: &ast::Pat, cmt: mc::cmt<'tcx>) { let pat_span_path_opt = match move_pat.node { ast::PatIdent(_, ref path1, _) => { Some(MoveSpanAndPath{span: move_pat.span, ident: path1.node}) }, _ => None, }; let move_info = GatherMoveInfo { id: move_pat.id, kind: MovePat, cmt: cmt, span_path_opt: pat_span_path_opt, }; gather_move(bccx, move_data, move_error_collector, move_info); } fn gather_move<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_info: GatherMoveInfo<'tcx>) { debug!("gather_move(move_id={}, cmt={:?})", move_info.id, move_info.cmt); let potentially_illegal_move = check_and_get_illegal_move_origin(bccx, &move_info.cmt); match potentially_illegal_move { Some(illegal_move_origin) => { debug!("illegal_move_origin={:?}", illegal_move_origin); let error = MoveError::with_move_info(illegal_move_origin, move_info.span_path_opt); move_error_collector.add_error(error); return } None => () } match opt_loan_path(&move_info.cmt) { Some(loan_path) => { move_data.add_move(bccx.tcx, loan_path, move_info.id, move_info.kind); } None => { // move from rvalue or raw pointer, hence ok } } } pub fn gather_assignment<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, assignment_id: ast::NodeId, assignment_span: Span, assignee_loan_path: Rc<LoanPath<'tcx>>, assignee_id: ast::NodeId, mode: euv::MutateMode) { move_data.add_assignment(bccx.tcx, assignee_loan_path, assignment_id, assignment_span, assignee_id, mode); } // (keep in sync with move_error::report_cannot_move_out_of ) fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, cmt: &mc::cmt<'tcx>) -> Option<mc::cmt<'tcx>> { match cmt.cat { mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_static_item => { Some(cmt.clone()) } mc::cat_rvalue(..) | mc::cat_local(..) | mc::cat_upvar(..) => { None } mc::cat_downcast(ref b, _) | mc::cat_interior(ref b, mc::InteriorField(_)) | mc::cat_interior(ref b, mc::InteriorElement(Kind::Pattern, _)) => { match b.ty.sty { ty::TyStruct(def, _) | ty::TyEnum(def, _) => { if def.has_dtor(bccx.tcx) { Some(cmt.clone()) } else { check_and_get_illegal_move_origin(bccx, b) } } _ => { check_and_get_illegal_move_origin(bccx, b) } } } mc::cat_interior(_, mc::InteriorElement(Kind::Index, _)) => { // Forbid move of arr[i] for arr: [T; 3]; see RFC 533. Some(cmt.clone()) } mc::cat_deref(ref b, _, mc::Unique) => { check_and_get_illegal_move_origin(bccx, b) } } }
{ let kind = match move_reason { euv::DirectRefMove | euv::PatBindingMove => MoveExpr, euv::CaptureMove => Captured }; let move_info = GatherMoveInfo { id: move_expr_id, kind: kind, cmt: cmt, span_path_opt: None, }; gather_move(bccx, move_data, move_error_collector, move_info); }
identifier_body
gather_moves.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Computes moves. use borrowck::*; use borrowck::gather_loans::move_error::MoveSpanAndPath; use borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector}; use borrowck::move_data::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::InteriorOffsetKind as Kind; use rustc::middle::ty; use std::rc::Rc; use syntax::ast; use syntax::codemap::Span; struct GatherMoveInfo<'tcx> { id: ast::NodeId, kind: MoveKind, cmt: mc::cmt<'tcx>, span_path_opt: Option<MoveSpanAndPath> } pub fn gather_decl<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, decl_id: ast::NodeId, _decl_span: Span, var_id: ast::NodeId) { let ty = bccx.tcx.node_id_to_type(var_id); let loan_path = Rc::new(LoanPath::new(LpVar(var_id), ty)); move_data.add_move(bccx.tcx, loan_path, decl_id, Declared); } pub fn gather_move_from_expr<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_expr_id: ast::NodeId, cmt: mc::cmt<'tcx>, move_reason: euv::MoveReason) { let kind = match move_reason { euv::DirectRefMove | euv::PatBindingMove => MoveExpr, euv::CaptureMove => Captured }; let move_info = GatherMoveInfo { id: move_expr_id, kind: kind, cmt: cmt, span_path_opt: None, }; gather_move(bccx, move_data, move_error_collector, move_info); } pub fn gather_match_variant<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, _move_error_collector: &MoveErrorCollector<'tcx>, move_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { let tcx = bccx.tcx; debug!("gather_match_variant(move_pat={}, cmt={:?}, mode={:?})", move_pat.id, cmt, mode); let opt_lp = opt_loan_path(&cmt); match opt_lp { Some(lp) => { match lp.kind { LpDowncast(ref base_lp, _) => move_data.add_variant_match( tcx, lp.clone(), move_pat.id, base_lp.clone(), mode), _ => panic!("should only call gather_match_variant \ for cat_downcast cmt"), } } None => { // We get None when input to match is non-path (e.g. // temporary result like a function call). Since no // loan-path is being matched, no need to record a // downcast. return; } } } pub fn
<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_pat: &ast::Pat, cmt: mc::cmt<'tcx>) { let pat_span_path_opt = match move_pat.node { ast::PatIdent(_, ref path1, _) => { Some(MoveSpanAndPath{span: move_pat.span, ident: path1.node}) }, _ => None, }; let move_info = GatherMoveInfo { id: move_pat.id, kind: MovePat, cmt: cmt, span_path_opt: pat_span_path_opt, }; gather_move(bccx, move_data, move_error_collector, move_info); } fn gather_move<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, move_error_collector: &MoveErrorCollector<'tcx>, move_info: GatherMoveInfo<'tcx>) { debug!("gather_move(move_id={}, cmt={:?})", move_info.id, move_info.cmt); let potentially_illegal_move = check_and_get_illegal_move_origin(bccx, &move_info.cmt); match potentially_illegal_move { Some(illegal_move_origin) => { debug!("illegal_move_origin={:?}", illegal_move_origin); let error = MoveError::with_move_info(illegal_move_origin, move_info.span_path_opt); move_error_collector.add_error(error); return } None => () } match opt_loan_path(&move_info.cmt) { Some(loan_path) => { move_data.add_move(bccx.tcx, loan_path, move_info.id, move_info.kind); } None => { // move from rvalue or raw pointer, hence ok } } } pub fn gather_assignment<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_data: &MoveData<'tcx>, assignment_id: ast::NodeId, assignment_span: Span, assignee_loan_path: Rc<LoanPath<'tcx>>, assignee_id: ast::NodeId, mode: euv::MutateMode) { move_data.add_assignment(bccx.tcx, assignee_loan_path, assignment_id, assignment_span, assignee_id, mode); } // (keep in sync with move_error::report_cannot_move_out_of ) fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, cmt: &mc::cmt<'tcx>) -> Option<mc::cmt<'tcx>> { match cmt.cat { mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_static_item => { Some(cmt.clone()) } mc::cat_rvalue(..) | mc::cat_local(..) | mc::cat_upvar(..) => { None } mc::cat_downcast(ref b, _) | mc::cat_interior(ref b, mc::InteriorField(_)) | mc::cat_interior(ref b, mc::InteriorElement(Kind::Pattern, _)) => { match b.ty.sty { ty::TyStruct(def, _) | ty::TyEnum(def, _) => { if def.has_dtor(bccx.tcx) { Some(cmt.clone()) } else { check_and_get_illegal_move_origin(bccx, b) } } _ => { check_and_get_illegal_move_origin(bccx, b) } } } mc::cat_interior(_, mc::InteriorElement(Kind::Index, _)) => { // Forbid move of arr[i] for arr: [T; 3]; see RFC 533. Some(cmt.clone()) } mc::cat_deref(ref b, _, mc::Unique) => { check_and_get_illegal_move_origin(bccx, b) } } }
gather_move_from_pat
identifier_name
issue-36082.rs
// 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 borrowck=mir // FIXME(#49821) -- No tip about using a let binding use std::cell::RefCell; fn
() { let mut r = 0; let s = 0; let x = RefCell::new((&mut r,s)); let val: &_ = x.borrow().0; //[ast]~^ ERROR borrowed value does not live long enough [E0597] //[ast]~| NOTE temporary value dropped here while still borrowed //[ast]~| NOTE temporary value does not live long enough //[ast]~| NOTE consider using a `let` binding to increase its lifetime //[mir]~^^^^^ ERROR temporary value dropped while borrowed [E0716] //[mir]~| NOTE temporary value is freed at the end of this statement //[mir]~| NOTE creates a temporary which is freed while still in use //[mir]~| NOTE consider using a `let` binding to create a longer lived value println!("{}", val); //[mir]~^ borrow later used here } //[ast]~^ NOTE temporary value needs to live until here
main
identifier_name
issue-36082.rs
// 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 borrowck=mir // FIXME(#49821) -- No tip about using a let binding use std::cell::RefCell; fn main() { let mut r = 0; let s = 0; let x = RefCell::new((&mut r,s)); let val: &_ = x.borrow().0; //[ast]~^ ERROR borrowed value does not live long enough [E0597] //[ast]~| NOTE temporary value dropped here while still borrowed //[ast]~| NOTE temporary value does not live long enough //[ast]~| NOTE consider using a `let` binding to increase its lifetime //[mir]~^^^^^ ERROR temporary value dropped while borrowed [E0716] //[mir]~| NOTE temporary value is freed at the end of this statement //[mir]~| NOTE creates a temporary which is freed while still in use //[mir]~| NOTE consider using a `let` binding to create a longer lived value println!("{}", val); //[mir]~^ borrow later used here } //[ast]~^ NOTE temporary value needs to live until here
random_line_split
issue-36082.rs
// 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 borrowck=mir // FIXME(#49821) -- No tip about using a let binding use std::cell::RefCell; fn main()
//[ast]~^ NOTE temporary value needs to live until here
{ let mut r = 0; let s = 0; let x = RefCell::new((&mut r,s)); let val: &_ = x.borrow().0; //[ast]~^ ERROR borrowed value does not live long enough [E0597] //[ast]~| NOTE temporary value dropped here while still borrowed //[ast]~| NOTE temporary value does not live long enough //[ast]~| NOTE consider using a `let` binding to increase its lifetime //[mir]~^^^^^ ERROR temporary value dropped while borrowed [E0716] //[mir]~| NOTE temporary value is freed at the end of this statement //[mir]~| NOTE creates a temporary which is freed while still in use //[mir]~| NOTE consider using a `let` binding to create a longer lived value println!("{}", val); //[mir]~^ borrow later used here }
identifier_body
mock_store.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; #[derive(Debug, PartialEq)] pub struct MockStoreStats { pub sets: usize, pub gets: usize, pub hits: usize, pub misses: usize, } #[derive(Clone, Debug)] pub struct MockStore<T> { data: Arc<Mutex<HashMap<String, T>>>, pub(crate) set_count: Arc<AtomicUsize>, pub(crate) get_count: Arc<AtomicUsize>, pub(crate) hit_count: Arc<AtomicUsize>, pub(crate) miss_count: Arc<AtomicUsize>, } impl<T> MockStore<T> { pub(crate) fn new() -> Self { Self { data: Arc::new(Mutex::new(HashMap::new())), set_count: Arc::new(AtomicUsize::new(0)), get_count: Arc::new(AtomicUsize::new(0)), hit_count: Arc::new(AtomicUsize::new(0)), miss_count: Arc::new(AtomicUsize::new(0)), } } pub fn
(&self) -> MockStoreStats { MockStoreStats { sets: self.set_count.load(Ordering::SeqCst), gets: self.get_count.load(Ordering::SeqCst), misses: self.miss_count.load(Ordering::SeqCst), hits: self.hit_count.load(Ordering::SeqCst), } } } impl<T: Clone> MockStore<T> { pub fn get(&self, key: &String) -> Option<T> { self.get_count.fetch_add(1, Ordering::SeqCst); let value = self.data.lock().expect("poisoned lock").get(key).cloned(); match &value { Some(..) => self.hit_count.fetch_add(1, Ordering::SeqCst), None => self.miss_count.fetch_add(1, Ordering::SeqCst), }; value } pub fn set(&self, key: &String, value: T) { self.set_count.fetch_add(1, Ordering::SeqCst); self.data .lock() .expect("poisoned lock") .insert(key.clone(), value); } #[cfg(test)] pub(crate) fn data(&self) -> HashMap<String, T> { self.data.lock().expect("poisoned lock").clone() } } #[cfg(test)] mod test { use super::*; #[test] fn test_counts() { let store = MockStore::new(); assert_eq!( store.stats(), MockStoreStats { sets: 0, gets: 0, misses: 0, hits: 0 } ); store.set(&"foo".to_string(), &()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 0, misses: 0, hits: 0 } ); store.get(&"foo".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 1, misses: 0, hits: 1 } ); store.get(&"bar".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 2, misses: 1, hits: 1 } ); } }
stats
identifier_name
mock_store.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; #[derive(Debug, PartialEq)] pub struct MockStoreStats { pub sets: usize, pub gets: usize, pub hits: usize, pub misses: usize, } #[derive(Clone, Debug)] pub struct MockStore<T> { data: Arc<Mutex<HashMap<String, T>>>, pub(crate) set_count: Arc<AtomicUsize>, pub(crate) get_count: Arc<AtomicUsize>, pub(crate) hit_count: Arc<AtomicUsize>, pub(crate) miss_count: Arc<AtomicUsize>, } impl<T> MockStore<T> { pub(crate) fn new() -> Self { Self { data: Arc::new(Mutex::new(HashMap::new())), set_count: Arc::new(AtomicUsize::new(0)), get_count: Arc::new(AtomicUsize::new(0)), hit_count: Arc::new(AtomicUsize::new(0)), miss_count: Arc::new(AtomicUsize::new(0)), } } pub fn stats(&self) -> MockStoreStats { MockStoreStats { sets: self.set_count.load(Ordering::SeqCst), gets: self.get_count.load(Ordering::SeqCst), misses: self.miss_count.load(Ordering::SeqCst), hits: self.hit_count.load(Ordering::SeqCst), } } } impl<T: Clone> MockStore<T> { pub fn get(&self, key: &String) -> Option<T> { self.get_count.fetch_add(1, Ordering::SeqCst); let value = self.data.lock().expect("poisoned lock").get(key).cloned(); match &value { Some(..) => self.hit_count.fetch_add(1, Ordering::SeqCst), None => self.miss_count.fetch_add(1, Ordering::SeqCst), }; value } pub fn set(&self, key: &String, value: T) { self.set_count.fetch_add(1, Ordering::SeqCst); self.data .lock() .expect("poisoned lock") .insert(key.clone(), value); } #[cfg(test)] pub(crate) fn data(&self) -> HashMap<String, T> { self.data.lock().expect("poisoned lock").clone() } } #[cfg(test)] mod test { use super::*; #[test] fn test_counts() { let store = MockStore::new(); assert_eq!( store.stats(), MockStoreStats { sets: 0, gets: 0, misses: 0, hits: 0 } ); store.set(&"foo".to_string(), &()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 0, misses: 0, hits: 0 } ); store.get(&"foo".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 1, misses: 0, hits: 1 } ); store.get(&"bar".to_string()); assert_eq!(
gets: 2, misses: 1, hits: 1 } ); } }
store.stats(), MockStoreStats { sets: 1,
random_line_split
mock_store.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; #[derive(Debug, PartialEq)] pub struct MockStoreStats { pub sets: usize, pub gets: usize, pub hits: usize, pub misses: usize, } #[derive(Clone, Debug)] pub struct MockStore<T> { data: Arc<Mutex<HashMap<String, T>>>, pub(crate) set_count: Arc<AtomicUsize>, pub(crate) get_count: Arc<AtomicUsize>, pub(crate) hit_count: Arc<AtomicUsize>, pub(crate) miss_count: Arc<AtomicUsize>, } impl<T> MockStore<T> { pub(crate) fn new() -> Self { Self { data: Arc::new(Mutex::new(HashMap::new())), set_count: Arc::new(AtomicUsize::new(0)), get_count: Arc::new(AtomicUsize::new(0)), hit_count: Arc::new(AtomicUsize::new(0)), miss_count: Arc::new(AtomicUsize::new(0)), } } pub fn stats(&self) -> MockStoreStats { MockStoreStats { sets: self.set_count.load(Ordering::SeqCst), gets: self.get_count.load(Ordering::SeqCst), misses: self.miss_count.load(Ordering::SeqCst), hits: self.hit_count.load(Ordering::SeqCst), } } } impl<T: Clone> MockStore<T> { pub fn get(&self, key: &String) -> Option<T> { self.get_count.fetch_add(1, Ordering::SeqCst); let value = self.data.lock().expect("poisoned lock").get(key).cloned(); match &value { Some(..) => self.hit_count.fetch_add(1, Ordering::SeqCst), None => self.miss_count.fetch_add(1, Ordering::SeqCst), }; value } pub fn set(&self, key: &String, value: T) { self.set_count.fetch_add(1, Ordering::SeqCst); self.data .lock() .expect("poisoned lock") .insert(key.clone(), value); } #[cfg(test)] pub(crate) fn data(&self) -> HashMap<String, T>
} #[cfg(test)] mod test { use super::*; #[test] fn test_counts() { let store = MockStore::new(); assert_eq!( store.stats(), MockStoreStats { sets: 0, gets: 0, misses: 0, hits: 0 } ); store.set(&"foo".to_string(), &()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 0, misses: 0, hits: 0 } ); store.get(&"foo".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 1, misses: 0, hits: 1 } ); store.get(&"bar".to_string()); assert_eq!( store.stats(), MockStoreStats { sets: 1, gets: 2, misses: 1, hits: 1 } ); } }
{ self.data.lock().expect("poisoned lock").clone() }
identifier_body