<commit_before>use rustc_hir::Mutability;
use rustc_index::bit_set::HybridBitSet;
use rustc_middle::mir::visit::{MutVisitor, NonUseContext, PlaceContext, Visitor};
use rustc_middle::mir::{self, BasicBlock, Local, Location};
use rustc_middle::ty::TyCtxt;

use crate::transform::MirPass;

/// This pass looks for MIR that always copies the same local into the return place and eliminates
/// the copy by renaming all uses of that local to `_0`.
///
/// This allows LLVM to perform an optimization similar to the named return value optimization
/// (NRVO) that is guaranteed in C++. This avoids a stack allocation and `memcpy` for the
/// relatively common pattern of allocating a buffer on the stack, mutating it, and returning it by
/// value like so:
///
/// ```rust
/// fn foo(init: fn(&mut [u8; 1024])) -> [u8; 1024] {
///     let mut buf = [0; 1024];
///     init(&mut buf);
///     buf
/// }
/// ```
///
/// For now, this pass is very simple and only capable of eliminating a single copy. A more general
/// version of copy propagation, such as the one based on non-overlapping live ranges in [#47954] and
/// [#71003], could yield even more benefits.
///
/// [#47954]: https://github.com/rust-lang/rust/pull/47954
/// [#71003]: https://github.com/rust-lang/rust/pull/71003
pub struct RenameReturnPlace;

impl<'tcx> MirPass<'tcx> for RenameReturnPlace {
    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) {
        if tcx.sess.opts.debugging_opts.mir_opt_level == 0 {
            return;
        }

        let returned_local = match local_eligible_for_nrvo(body) {
            Some(l) => l,
            None => {
                debug!("`{:?}` was ineligible for NRVO", body.source.def_id());
                return;
            }
        };

        debug!(
            "`{:?}` was eligible for NRVO, making {:?} the return place",
            body.source.def_id(),
            returned_local
        );

        RenameToReturnPlace { tcx, to_rename: returned_local }.visit_body(body);

        // Clean up the `NOP`s we inserted for statements made useless by our renaming.
        for block_data in body.basic_blocks_mut() {
            block_data.statements.retain(|stmt| stmt.kind != mir::StatementKind::Nop);
        }

        // Overwrite the debuginfo of `_0` with that of the renamed local.
        let (renamed_decl, ret_decl) =
            body.local_decls.pick2_mut(returned_local, mir::RETURN_PLACE);

        // Sometimes, the return place is assigned a local of a different but coercable type, for
        // example `&mut T` instead of `&T`. Overwriting the `LocalInfo` for the return place means
        // its type may no longer match the return type of its function. This doesn't cause a
        // problem in codegen because these two types are layout-compatible, but may be unexpected.
        debug!("_0: {:?} = {:?}: {:?}", ret_decl.ty, returned_local, renamed_decl.ty);
        ret_decl.clone_from(renamed_decl);

        // The return place is always mutable.
        ret_decl.mutability = Mutability::Mut;
    }
}

/// MIR that is eligible for the NRVO must fulfill two conditions:
///   1. The return place must not be read prior to the `Return` terminator.
///   2. A simple assignment of a whole local to the return place (e.g., `_0 = _1`) must be the
///      only definition of the return place reaching the `Return` terminator.
///
/// If the MIR fulfills both these conditions, this function returns the `Local` that is assigned
/// to the return place along all possible paths through the control-flow graph.
fn local_eligible_for_nrvo(body: &mut mir::Body<'_>) -> Option<Local> {
    if IsReturnPlaceRead::run(body) {
        return None;
    }

    let mut copied_to_return_place = None;
    for block in body.basic_blocks().indices() {
        // Look for blocks with a `Return` terminator.
        if !matches!(body[block].terminator().kind, mir::TerminatorKind::Return) {
            continue;
        }

        // Look for an assignment of a single local to the return place prior to the `Return`.
        let returned_local = find_local_assigned_to_return_place(block, body)?;
        match body.local_kind(returned_local) {
            // FIXME: Can we do this for arguments as well?
            mir::LocalKind::Arg => return None,

            mir::LocalKind::ReturnPointer => bug!("Return place was assigned to itself?"),
            mir::LocalKind::Var | mir::LocalKind::Temp => {}
        }

        // If multiple different locals are copied to the return place. We can't pick a
        // single one to rename.
        if copied_to_return_place.map_or(false, |old| old != returned_local) {
            return None;
        }

        copied_to_return_place = Some(returned_local);
    }

    copied_to_return_place
}

fn find_local_assigned_to_return_place(
    start: BasicBlock,
    body: &mut mir::Body<'_>,
) -> Option<Local> {
    let mut block = start;
    let mut seen = HybridBitSet::new_empty(body.basic_blocks().len());

    // Iterate as long as `block` has exactly one predecessor that we have not yet visited.
    while seen.insert(block) {
        trace!("Looking for assignments to `_0` in {:?}", block);

        let local = body[block].statements.iter().rev().find_map(as_local_assigned_to_return_place);
        if local.is_some() {
            return local;
        }

        match body.predecessors()[block].as_slice() {
            &[pred] => block = pred,
            _ => return None,
        }
    }

    None
}

// If this statement is an assignment of an unprojected local to the return place,
// return that local.
fn as_local_assigned_to_return_place(stmt: &mir::Statement<'_>) -> Option<Local> {
    if let mir::StatementKind::Assign(box (lhs, rhs)) = &stmt.kind {
        if lhs.as_local() == Some(mir::RETURN_PLACE) {
            if let mir::Rvalue::Use(mir::Operand::Copy(rhs) | mir::Operand::Move(rhs)) = rhs {
                return rhs.as_local();
            }
        }
    }

    None
}

struct RenameToReturnPlace<'tcx> {
    to_rename: Local,
    tcx: TyCtxt<'tcx>,
}

/// Replaces all uses of `self.to_rename` with `_0`.
impl MutVisitor<'tcx> for RenameToReturnPlace<'tcx> {
    fn tcx(&self) -> TyCtxt<'tcx> {
        self.tcx
    }

    fn visit_statement(&mut self, stmt: &mut mir::Statement<'tcx>, loc: Location) {
        // Remove assignments of the local being replaced to the return place, since it is now the
        // return place:
        //     _0 = _1
        if as_local_assigned_to_return_place(stmt) == Some(self.to_rename) {
            stmt.kind = mir::StatementKind::Nop;
            return;
        }

        // Remove storage annotations for the local being replaced:
        //     StorageLive(_1)
        if let mir::StatementKind::StorageLive(local) | mir::StatementKind::StorageDead(local) =
            stmt.kind
        {
            if local == self.to_rename {
                stmt.kind = mir::StatementKind::Nop;
                return;
            }
        }

        self.super_statement(stmt, loc)
    }

    fn visit_terminator(&mut self, terminator: &mut mir::Terminator<'tcx>, loc: Location) {
        // Ignore the implicit "use" of the return place in a `Return` statement.
        if let mir::TerminatorKind::Return = terminator.kind {
            return;
        }

        self.super_terminator(terminator, loc);
    }

    fn visit_local(&mut self, l: &mut Local, ctxt: PlaceContext, _: Location) {
        if *l == mir::RETURN_PLACE {
            assert_eq!(ctxt, PlaceContext::NonUse(NonUseContext::VarDebugInfo));
        } else if *l == self.to_rename {
            *l = mir::RETURN_PLACE;
        }
    }
}

struct IsReturnPlaceRead(bool);

impl IsReturnPlaceRead {
    fn run(body: &mir::Body<'_>) -> bool {
        let mut vis = IsReturnPlaceRead(false);
        vis.visit_body(body);
        vis.0
    }
}

impl Visitor<'tcx> for IsReturnPlaceRead {
    fn visit_local(&mut self, &l: &Local, ctxt: PlaceContext, _: Location) {
        if l == mir::RETURN_PLACE && ctxt.is_use() && !ctxt.is_place_assignment() {
            self.0 = true;
        }
    }

    fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, loc: Location) {
        // Ignore the implicit "use" of the return place in a `Return` statement.
        if let mir::TerminatorKind::Return = terminator.kind {
            return;
        }

        self.super_terminator(terminator, loc);
    }
}
<commit_msg>Link to pass docs from NRVO module docs<commit_after>//! See the docs for [`RenameReturnPlace`].

use rustc_hir::Mutability;
use rustc_index::bit_set::HybridBitSet;
use rustc_middle::mir::visit::{MutVisitor, NonUseContext, PlaceContext, Visitor};
use rustc_middle::mir::{self, BasicBlock, Local, Location};
use rustc_middle::ty::TyCtxt;

use crate::transform::MirPass;

/// This pass looks for MIR that always copies the same local into the return place and eliminates
/// the copy by renaming all uses of that local to `_0`.
///
/// This allows LLVM to perform an optimization similar to the named return value optimization
/// (NRVO) that is guaranteed in C++. This avoids a stack allocation and `memcpy` for the
/// relatively common pattern of allocating a buffer on the stack, mutating it, and returning it by
/// value like so:
///
/// ```rust
/// fn foo(init: fn(&mut [u8; 1024])) -> [u8; 1024] {
///     let mut buf = [0; 1024];
///     init(&mut buf);
///     buf
/// }
/// ```
///
/// For now, this pass is very simple and only capable of eliminating a single copy. A more general
/// version of copy propagation, such as the one based on non-overlapping live ranges in [#47954] and
/// [#71003], could yield even more benefits.
///
/// [#47954]: https://github.com/rust-lang/rust/pull/47954
/// [#71003]: https://github.com/rust-lang/rust/pull/71003
pub struct RenameReturnPlace;

impl<'tcx> MirPass<'tcx> for RenameReturnPlace {
    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) {
        if tcx.sess.opts.debugging_opts.mir_opt_level == 0 {
            return;
        }

        let returned_local = match local_eligible_for_nrvo(body) {
            Some(l) => l,
            None => {
                debug!("`{:?}` was ineligible for NRVO", body.source.def_id());
                return;
            }
        };

        debug!(
            "`{:?}` was eligible for NRVO, making {:?} the return place",
            body.source.def_id(),
            returned_local
        );

        RenameToReturnPlace { tcx, to_rename: returned_local }.visit_body(body);

        // Clean up the `NOP`s we inserted for statements made useless by our renaming.
        for block_data in body.basic_blocks_mut() {
            block_data.statements.retain(|stmt| stmt.kind != mir::StatementKind::Nop);
        }

        // Overwrite the debuginfo of `_0` with that of the renamed local.
        let (renamed_decl, ret_decl) =
            body.local_decls.pick2_mut(returned_local, mir::RETURN_PLACE);

        // Sometimes, the return place is assigned a local of a different but coercable type, for
        // example `&mut T` instead of `&T`. Overwriting the `LocalInfo` for the return place means
        // its type may no longer match the return type of its function. This doesn't cause a
        // problem in codegen because these two types are layout-compatible, but may be unexpected.
        debug!("_0: {:?} = {:?}: {:?}", ret_decl.ty, returned_local, renamed_decl.ty);
        ret_decl.clone_from(renamed_decl);

        // The return place is always mutable.
        ret_decl.mutability = Mutability::Mut;
    }
}

/// MIR that is eligible for the NRVO must fulfill two conditions:
///   1. The return place must not be read prior to the `Return` terminator.
///   2. A simple assignment of a whole local to the return place (e.g., `_0 = _1`) must be the
///      only definition of the return place reaching the `Return` terminator.
///
/// If the MIR fulfills both these conditions, this function returns the `Local` that is assigned
/// to the return place along all possible paths through the control-flow graph.
fn local_eligible_for_nrvo(body: &mut mir::Body<'_>) -> Option<Local> {
    if IsReturnPlaceRead::run(body) {
        return None;
    }

    let mut copied_to_return_place = None;
    for block in body.basic_blocks().indices() {
        // Look for blocks with a `Return` terminator.
        if !matches!(body[block].terminator().kind, mir::TerminatorKind::Return) {
            continue;
        }

        // Look for an assignment of a single local to the return place prior to the `Return`.
        let returned_local = find_local_assigned_to_return_place(block, body)?;
        match body.local_kind(returned_local) {
            // FIXME: Can we do this for arguments as well?
            mir::LocalKind::Arg => return None,

            mir::LocalKind::ReturnPointer => bug!("Return place was assigned to itself?"),
            mir::LocalKind::Var | mir::LocalKind::Temp => {}
        }

        // If multiple different locals are copied to the return place. We can't pick a
        // single one to rename.
        if copied_to_return_place.map_or(false, |old| old != returned_local) {
            return None;
        }

        copied_to_return_place = Some(returned_local);
    }

    copied_to_return_place
}

fn find_local_assigned_to_return_place(
    start: BasicBlock,
    body: &mut mir::Body<'_>,
) -> Option<Local> {
    let mut block = start;
    let mut seen = HybridBitSet::new_empty(body.basic_blocks().len());

    // Iterate as long as `block` has exactly one predecessor that we have not yet visited.
    while seen.insert(block) {
        trace!("Looking for assignments to `_0` in {:?}", block);

        let local = body[block].statements.iter().rev().find_map(as_local_assigned_to_return_place);
        if local.is_some() {
            return local;
        }

        match body.predecessors()[block].as_slice() {
            &[pred] => block = pred,
            _ => return None,
        }
    }

    None
}

// If this statement is an assignment of an unprojected local to the return place,
// return that local.
fn as_local_assigned_to_return_place(stmt: &mir::Statement<'_>) -> Option<Local> {
    if let mir::StatementKind::Assign(box (lhs, rhs)) = &stmt.kind {
        if lhs.as_local() == Some(mir::RETURN_PLACE) {
            if let mir::Rvalue::Use(mir::Operand::Copy(rhs) | mir::Operand::Move(rhs)) = rhs {
                return rhs.as_local();
            }
        }
    }

    None
}

struct RenameToReturnPlace<'tcx> {
    to_rename: Local,
    tcx: TyCtxt<'tcx>,
}

/// Replaces all uses of `self.to_rename` with `_0`.
impl MutVisitor<'tcx> for RenameToReturnPlace<'tcx> {
    fn tcx(&self) -> TyCtxt<'tcx> {
        self.tcx
    }

    fn visit_statement(&mut self, stmt: &mut mir::Statement<'tcx>, loc: Location) {
        // Remove assignments of the local being replaced to the return place, since it is now the
        // return place:
        //     _0 = _1
        if as_local_assigned_to_return_place(stmt) == Some(self.to_rename) {
            stmt.kind = mir::StatementKind::Nop;
            return;
        }

        // Remove storage annotations for the local being replaced:
        //     StorageLive(_1)
        if let mir::StatementKind::StorageLive(local) | mir::StatementKind::StorageDead(local) =
            stmt.kind
        {
            if local == self.to_rename {
                stmt.kind = mir::StatementKind::Nop;
                return;
            }
        }

        self.super_statement(stmt, loc)
    }

    fn visit_terminator(&mut self, terminator: &mut mir::Terminator<'tcx>, loc: Location) {
        // Ignore the implicit "use" of the return place in a `Return` statement.
        if let mir::TerminatorKind::Return = terminator.kind {
            return;
        }

        self.super_terminator(terminator, loc);
    }

    fn visit_local(&mut self, l: &mut Local, ctxt: PlaceContext, _: Location) {
        if *l == mir::RETURN_PLACE {
            assert_eq!(ctxt, PlaceContext::NonUse(NonUseContext::VarDebugInfo));
        } else if *l == self.to_rename {
            *l = mir::RETURN_PLACE;
        }
    }
}

struct IsReturnPlaceRead(bool);

impl IsReturnPlaceRead {
    fn run(body: &mir::Body<'_>) -> bool {
        let mut vis = IsReturnPlaceRead(false);
        vis.visit_body(body);
        vis.0
    }
}

impl Visitor<'tcx> for IsReturnPlaceRead {
    fn visit_local(&mut self, &l: &Local, ctxt: PlaceContext, _: Location) {
        if l == mir::RETURN_PLACE && ctxt.is_use() && !ctxt.is_place_assignment() {
            self.0 = true;
        }
    }

    fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, loc: Location) {
        // Ignore the implicit "use" of the return place in a `Return` statement.
        if let mir::TerminatorKind::Return = terminator.kind {
            return;
        }

        self.super_terminator(terminator, loc);
    }
}
<|endoftext|>


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

//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.

use dom::bindings::conversions::FromJSValConvertible;
use dom::bindings::js::{JS, JSRef, Root};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window;
use script_task::ScriptChan;

use servo_net::resource_task::ResourceTask;

use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use js::jsval::ObjectOrNullValue;
use url::Url;

use std::ptr;

/// A freely-copyable reference to a rooted global object.
#[deriving(Copy)]
pub enum GlobalRef<'a> {
    Window(JSRef<'a, window::Window>),
    Worker(JSRef<'a, WorkerGlobalScope>),
}

/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
    Window(Root<window::Window>),
    Worker(Root<WorkerGlobalScope>),
}

/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
    Window(JS<window::Window>),
    Worker(JS<WorkerGlobalScope>),
}

impl<'a> GlobalRef<'a> {
    /// Get the `JSContext` for the `JSRuntime` associated with the thread
    /// this global object is on.
    pub fn get_cx(&self) -> *mut JSContext {
        match *self {
            GlobalRef::Window(ref window) => window.get_cx(),
            GlobalRef::Worker(ref worker) => worker.get_cx(),
        }
    }

    /// Extract a `Window`, causing task failure if the global object is not
    /// a `Window`.
    pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
        match *self {
            GlobalRef::Window(window) => window,
            GlobalRef::Worker(_) => panic!("expected a Window scope"),
        }
    }

    pub fn resource_task(&self) -> ResourceTask {
        match *self {
            GlobalRef::Window(ref window) => window.page().resource_task.clone(),
            GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
        }
    }

    pub fn get_url(&self) -> Url {
        match *self {
            GlobalRef::Window(ref window) => window.get_url(),
            GlobalRef::Worker(ref worker) => worker.get_url().clone(),
        }
    }

    /// `ScriptChan` used to send messages to the event loop of this global's
    /// thread.
    pub fn script_chan(&self) -> Box<ScriptChan+Send> {
        match *self {
            GlobalRef::Window(ref window) => window.script_chan(),
            GlobalRef::Worker(ref worker) => worker.script_chan(),
        }
    }
}

impl<'a> Reflectable for GlobalRef<'a> {
    fn reflector<'b>(&'b self) -> &'b Reflector {
        match *self {
            GlobalRef::Window(ref window) => window.reflector(),
            GlobalRef::Worker(ref worker) => worker.reflector(),
        }
    }
}

impl GlobalRoot {
    /// Obtain a safe reference to the global object that cannot outlive the
    /// lifetime of this root.
    pub fn r<'c>(&'c self) -> GlobalRef<'c> {
        match *self {
            GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
            GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
        }
    }
}

impl GlobalField {
    /// Create a new `GlobalField` from a rooted reference.
    pub fn from_rooted(global: &GlobalRef) -> GlobalField {
        match *global {
            GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
            GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
        }
    }

    /// Create a stack-bounded root for this reference.
    pub fn root(&self) -> GlobalRoot {
        match *self {
            GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
            GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
        }
    }
}

/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalField {
    unsafe {
        let global = GetGlobalForObjectCrossCompartment(obj);
        let clasp = JS_GetClass(global);
        assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
        match FromJSValConvertible::from_jsval(ptr::null_mut(), ObjectOrNullValue(global), ()) {
            Ok(window) => return GlobalField::Window(window),
            Err(_) => (),
        }

        match FromJSValConvertible::from_jsval(ptr::null_mut(), ObjectOrNullValue(global), ()) {
            Ok(worker) => return GlobalField::Worker(worker),
            Err(_) => (),
        }

        panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
    }
}
<commit_msg>Document global.rs.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.

#[deny(missing_docs)]

use dom::bindings::conversions::FromJSValConvertible;
use dom::bindings::js::{JS, JSRef, Root};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window;
use script_task::ScriptChan;

use servo_net::resource_task::ResourceTask;

use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use js::jsval::ObjectOrNullValue;
use url::Url;

use std::ptr;

/// A freely-copyable reference to a rooted global object.
#[deriving(Copy)]
pub enum GlobalRef<'a> {
    /// A reference to a `Window` object.
    Window(JSRef<'a, window::Window>),
    /// A reference to a `WorkerGlobalScope` object.
    Worker(JSRef<'a, WorkerGlobalScope>),
}

/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
    /// A root for a `Window` object.
    Window(Root<window::Window>),
    /// A root for a `WorkerGlobalScope` object.
    Worker(Root<WorkerGlobalScope>),
}

/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
    /// A field for a `Window` object.
    Window(JS<window::Window>),
    /// A field for a `WorkerGlobalScope` object.
    Worker(JS<WorkerGlobalScope>),
}

impl<'a> GlobalRef<'a> {
    /// Get the `JSContext` for the `JSRuntime` associated with the thread
    /// this global object is on.
    pub fn get_cx(&self) -> *mut JSContext {
        match *self {
            GlobalRef::Window(ref window) => window.get_cx(),
            GlobalRef::Worker(ref worker) => worker.get_cx(),
        }
    }

    /// Extract a `Window`, causing task failure if the global object is not
    /// a `Window`.
    pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
        match *self {
            GlobalRef::Window(window) => window,
            GlobalRef::Worker(_) => panic!("expected a Window scope"),
        }
    }

    /// Get the `ResourceTask` for this global scope.
    pub fn resource_task(&self) -> ResourceTask {
        match *self {
            GlobalRef::Window(ref window) => window.page().resource_task.clone(),
            GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
        }
    }

    /// Get the URL for this global scope.
    pub fn get_url(&self) -> Url {
        match *self {
            GlobalRef::Window(ref window) => window.get_url(),
            GlobalRef::Worker(ref worker) => worker.get_url().clone(),
        }
    }

    /// `ScriptChan` used to send messages to the event loop of this global's
    /// thread.
    pub fn script_chan(&self) -> Box<ScriptChan+Send> {
        match *self {
            GlobalRef::Window(ref window) => window.script_chan(),
            GlobalRef::Worker(ref worker) => worker.script_chan(),
        }
    }
}

impl<'a> Reflectable for GlobalRef<'a> {
    fn reflector<'b>(&'b self) -> &'b Reflector {
        match *self {
            GlobalRef::Window(ref window) => window.reflector(),
            GlobalRef::Worker(ref worker) => worker.reflector(),
        }
    }
}

impl GlobalRoot {
    /// Obtain a safe reference to the global object that cannot outlive the
    /// lifetime of this root.
    pub fn r<'c>(&'c self) -> GlobalRef<'c> {
        match *self {
            GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
            GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
        }
    }
}

impl GlobalField {
    /// Create a new `GlobalField` from a rooted reference.
    pub fn from_rooted(global: &GlobalRef) -> GlobalField {
        match *global {
            GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
            GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
        }
    }

    /// Create a stack-bounded root for this reference.
    pub fn root(&self) -> GlobalRoot {
        match *self {
            GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
            GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
        }
    }
}

/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalField {
    unsafe {
        let global = GetGlobalForObjectCrossCompartment(obj);
        let clasp = JS_GetClass(global);
        assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
        match FromJSValConvertible::from_jsval(ptr::null_mut(), ObjectOrNullValue(global), ()) {
            Ok(window) => return GlobalField::Window(window),
            Err(_) => (),
        }

        match FromJSValConvertible::from_jsval(ptr::null_mut(), ObjectOrNullValue(global), ()) {
            Ok(worker) => return GlobalField::Worker(worker),
            Err(_) => (),
        }

        panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
    }
}
<|endoftext|>


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

//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.

use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;

include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));

impl ::selectors::parser::PseudoElement for PseudoElement {
    type Impl = SelectorImpl;

    fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
        if !self.supports_user_action_state() {
            return false;
        }

        return pseudo_class.is_safe_user_action_state();
    }
}

impl PseudoElement {
    /// Returns the kind of cascade type that a given pseudo is going to use.
    ///
    /// In Gecko we only compute ::before and ::after eagerly. We save the rules
    /// for anonymous boxes separately, so we resolve them as precomputed
    /// pseudos.
    ///
    /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
    pub fn cascade_type(&self) -> PseudoElementCascadeType {
        if self.is_eager() {
            debug_assert!(!self.is_anon_box());
            return PseudoElementCascadeType::Eager
        }

        if self.is_precomputed() {
            return PseudoElementCascadeType::Precomputed
        }

        PseudoElementCascadeType::Lazy
    }

    /// Whether the pseudo-element should inherit from the default computed
    /// values instead of from the parent element.
    ///
    /// This is not the common thing, but there are some pseudos (namely:
    /// ::backdrop), that shouldn't inherit from the parent element.
    pub fn inherits_from_default_values(&self) -> bool {
        matches!(*self, PseudoElement::Backdrop)
    }

    /// Gets the canonical index of this eagerly-cascaded pseudo-element.
    #[inline]
    pub fn eager_index(&self) -> usize {
        EAGER_PSEUDOS.iter().position(|p| p == self)
            .expect("Not an eager pseudo")
    }

    /// Creates a pseudo-element from an eager index.
    #[inline]
    pub fn from_eager_index(i: usize) -> Self {
        EAGER_PSEUDOS[i].clone()
    }

    /// Whether the current pseudo element is ::before or ::after.
    #[inline]
    pub fn is_before_or_after(&self) -> bool {
        self.is_before() || self.is_after()
    }

    /// Whether this pseudo-element is the ::before pseudo.
    #[inline]
    pub fn is_before(&self) -> bool {
        *self == PseudoElement::Before
    }

    /// Whether this pseudo-element is the ::after pseudo.
    #[inline]
    pub fn is_after(&self) -> bool {
        *self == PseudoElement::After
    }

    /// Whether this pseudo-element is ::first-letter.
    #[inline]
    pub fn is_first_letter(&self) -> bool {
        *self == PseudoElement::FirstLetter
    }

    /// Whether this pseudo-element is ::first-line.
    #[inline]
    pub fn is_first_line(&self) -> bool {
        *self == PseudoElement::FirstLine
    }

    /// Whether this pseudo-element is ::-moz-fieldset-content.
    #[inline]
    pub fn is_fieldset_content(&self) -> bool {
        *self == PseudoElement::FieldsetContent
    }

    /// Whether this pseudo-element is lazily-cascaded.
    #[inline]
    pub fn is_lazy(&self) -> bool {
        !self.is_eager() && !self.is_precomputed()
    }

    /// Whether this pseudo-element is web-exposed.
    pub fn exposed_in_non_ua_sheets(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
    }

    /// Whether this pseudo-element supports user action selectors.
    pub fn supports_user_action_state(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
    }

    /// Whether this pseudo-element skips flex/grid container display-based
    /// fixup.
    #[inline]
    pub fn skip_item_based_display_fixup(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
    }

    /// Whether this pseudo-element is precomputed.
    #[inline]
    pub fn is_precomputed(&self) -> bool {
        self.is_anon_box() && !self.is_tree_pseudo_element()
    }

    /// Covert non-canonical pseudo-element to canonical one, and keep a
    /// canonical one as it is.
    pub fn canonical(&self) -> PseudoElement {
        match *self {
            PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
            _ => self.clone(),
        }
    }

    /// Property flag that properties must have to apply to this pseudo-element.
    #[inline]
    pub fn property_restriction(&self) -> Option<PropertyFlags> {
        match *self {
            PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
            PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
            PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
            _ => None,
        }
    }

    /// Whether this pseudo-element should actually exist if it has
    /// the given styles.
    pub fn should_exist(&self, style: &ComputedValues) -> bool
    {
        let display = style.get_box().clone_display();
        if display == display::T::none {
            return false;
        }
        if self.is_before_or_after() && style.ineffective_content_property() {
            return false;
        }

        true
    }
}
<commit_msg>style: Tidy up PseudoElement::should_exist.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.

use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;

include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));

impl ::selectors::parser::PseudoElement for PseudoElement {
    type Impl = SelectorImpl;

    fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
        if !self.supports_user_action_state() {
            return false;
        }

        return pseudo_class.is_safe_user_action_state();
    }
}

impl PseudoElement {
    /// Returns the kind of cascade type that a given pseudo is going to use.
    ///
    /// In Gecko we only compute ::before and ::after eagerly. We save the rules
    /// for anonymous boxes separately, so we resolve them as precomputed
    /// pseudos.
    ///
    /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
    pub fn cascade_type(&self) -> PseudoElementCascadeType {
        if self.is_eager() {
            debug_assert!(!self.is_anon_box());
            return PseudoElementCascadeType::Eager
        }

        if self.is_precomputed() {
            return PseudoElementCascadeType::Precomputed
        }

        PseudoElementCascadeType::Lazy
    }

    /// Whether the pseudo-element should inherit from the default computed
    /// values instead of from the parent element.
    ///
    /// This is not the common thing, but there are some pseudos (namely:
    /// ::backdrop), that shouldn't inherit from the parent element.
    pub fn inherits_from_default_values(&self) -> bool {
        matches!(*self, PseudoElement::Backdrop)
    }

    /// Gets the canonical index of this eagerly-cascaded pseudo-element.
    #[inline]
    pub fn eager_index(&self) -> usize {
        EAGER_PSEUDOS.iter().position(|p| p == self)
            .expect("Not an eager pseudo")
    }

    /// Creates a pseudo-element from an eager index.
    #[inline]
    pub fn from_eager_index(i: usize) -> Self {
        EAGER_PSEUDOS[i].clone()
    }

    /// Whether the current pseudo element is ::before or ::after.
    #[inline]
    pub fn is_before_or_after(&self) -> bool {
        self.is_before() || self.is_after()
    }

    /// Whether this pseudo-element is the ::before pseudo.
    #[inline]
    pub fn is_before(&self) -> bool {
        *self == PseudoElement::Before
    }

    /// Whether this pseudo-element is the ::after pseudo.
    #[inline]
    pub fn is_after(&self) -> bool {
        *self == PseudoElement::After
    }

    /// Whether this pseudo-element is ::first-letter.
    #[inline]
    pub fn is_first_letter(&self) -> bool {
        *self == PseudoElement::FirstLetter
    }

    /// Whether this pseudo-element is ::first-line.
    #[inline]
    pub fn is_first_line(&self) -> bool {
        *self == PseudoElement::FirstLine
    }

    /// Whether this pseudo-element is ::-moz-fieldset-content.
    #[inline]
    pub fn is_fieldset_content(&self) -> bool {
        *self == PseudoElement::FieldsetContent
    }

    /// Whether this pseudo-element is lazily-cascaded.
    #[inline]
    pub fn is_lazy(&self) -> bool {
        !self.is_eager() && !self.is_precomputed()
    }

    /// Whether this pseudo-element is web-exposed.
    pub fn exposed_in_non_ua_sheets(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
    }

    /// Whether this pseudo-element supports user action selectors.
    pub fn supports_user_action_state(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
    }

    /// Whether this pseudo-element skips flex/grid container display-based
    /// fixup.
    #[inline]
    pub fn skip_item_based_display_fixup(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
    }

    /// Whether this pseudo-element is precomputed.
    #[inline]
    pub fn is_precomputed(&self) -> bool {
        self.is_anon_box() && !self.is_tree_pseudo_element()
    }

    /// Covert non-canonical pseudo-element to canonical one, and keep a
    /// canonical one as it is.
    pub fn canonical(&self) -> PseudoElement {
        match *self {
            PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
            _ => self.clone(),
        }
    }

    /// Property flag that properties must have to apply to this pseudo-element.
    #[inline]
    pub fn property_restriction(&self) -> Option<PropertyFlags> {
        match *self {
            PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
            PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
            PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
            _ => None,
        }
    }

    /// Whether this pseudo-element should actually exist if it has
    /// the given styles.
    pub fn should_exist(&self, style: &ComputedValues) -> bool {
        if style.get_box().clone_display() == display::T::none {
            return false;
        }

        if self.is_before_or_after() && style.ineffective_content_property() {
            return false;
        }

        true
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.

use crate::gecko_bindings::structs::{self, PseudoStyleType};
use crate::properties::longhands::display::computed_value::T as Display;
use crate::properties::{ComputedValues, PropertyFlags};
use crate::selector_parser::{PseudoElementCascadeType, SelectorImpl};
use crate::str::{starts_with_ignore_ascii_case, string_as_ascii_lowercase};
use crate::string_cache::Atom;
use crate::values::serialize_atom_identifier;
use cssparser::ToCss;
use std::fmt;
use thin_slice::ThinBoxedSlice;

include!(concat!(
    env!("OUT_DIR"),
    "/gecko/pseudo_element_definition.rs"
));

impl ::selectors::parser::PseudoElement for PseudoElement {
    type Impl = SelectorImpl;

    // ::slotted() should support all tree-abiding pseudo-elements, see
    // https://drafts.csswg.org/css-scoping/#slotted-pseudo
    // https://drafts.csswg.org/css-pseudo-4/#treelike
    #[inline]
    fn valid_after_slotted(&self) -> bool {
        matches!(
            *self,
            PseudoElement::Before |
                PseudoElement::After |
                PseudoElement::Marker |
                PseudoElement::Placeholder
        )
    }

    #[inline]
    fn accepts_state_pseudo_classes(&self) -> bool {
        self.supports_user_action_state()
    }
}

impl PseudoElement {
    /// Returns the kind of cascade type that a given pseudo is going to use.
    ///
    /// In Gecko we only compute ::before and ::after eagerly. We save the rules
    /// for anonymous boxes separately, so we resolve them as precomputed
    /// pseudos.
    ///
    /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
    pub fn cascade_type(&self) -> PseudoElementCascadeType {
        if self.is_eager() {
            debug_assert!(!self.is_anon_box());
            return PseudoElementCascadeType::Eager;
        }

        if self.is_precomputed() {
            return PseudoElementCascadeType::Precomputed;
        }

        PseudoElementCascadeType::Lazy
    }

    /// Whether the pseudo-element should inherit from the default computed
    /// values instead of from the parent element.
    ///
    /// This is not the common thing, but there are some pseudos (namely:
    /// ::backdrop), that shouldn't inherit from the parent element.
    pub fn inherits_from_default_values(&self) -> bool {
        matches!(*self, PseudoElement::Backdrop)
    }

    /// Gets the canonical index of this eagerly-cascaded pseudo-element.
    #[inline]
    pub fn eager_index(&self) -> usize {
        EAGER_PSEUDOS
            .iter()
            .position(|p| p == self)
            .expect("Not an eager pseudo")
    }

    /// Creates a pseudo-element from an eager index.
    #[inline]
    pub fn from_eager_index(i: usize) -> Self {
        EAGER_PSEUDOS[i].clone()
    }

    /// Whether the current pseudo element is animatable.
    #[inline]
    pub fn is_animatable(&self) -> bool {
        matches!(*self, Self::Before | Self::After | Self::Marker)
    }

    /// Whether the current pseudo element is ::before or ::after.
    #[inline]
    pub fn is_before_or_after(&self) -> bool {
        self.is_before() || self.is_after()
    }

    /// Whether this pseudo-element is the ::before pseudo.
    #[inline]
    pub fn is_before(&self) -> bool {
        *self == PseudoElement::Before
    }

    /// Whether this pseudo-element is the ::after pseudo.
    #[inline]
    pub fn is_after(&self) -> bool {
        *self == PseudoElement::After
    }

    /// Whether this pseudo-element is the ::marker pseudo.
    #[inline]
    pub fn is_marker(&self) -> bool {
        *self == PseudoElement::Marker
    }

    /// Whether this pseudo-element is the ::selection pseudo.
    #[inline]
    pub fn is_selection(&self) -> bool {
        *self == PseudoElement::Selection
    }

    /// Whether this pseudo-element is ::first-letter.
    #[inline]
    pub fn is_first_letter(&self) -> bool {
        *self == PseudoElement::FirstLetter
    }

    /// Whether this pseudo-element is ::first-line.
    #[inline]
    pub fn is_first_line(&self) -> bool {
        *self == PseudoElement::FirstLine
    }

    /// Whether this pseudo-element is the ::-moz-color-swatch pseudo.
    #[inline]
    pub fn is_color_swatch(&self) -> bool {
        *self == PseudoElement::MozColorSwatch
    }

    /// Whether this pseudo-element is lazily-cascaded.
    #[inline]
    pub fn is_lazy(&self) -> bool {
        !self.is_eager() && !self.is_precomputed()
    }

    /// Whether this pseudo-element supports user action selectors.
    pub fn supports_user_action_state(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
    }

    /// Whether this pseudo-element is enabled for all content.
    pub fn enabled_in_content(&self) -> bool {
        if (self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME) != 0 {
            return false;
        }
        match *self {
            PseudoElement::MozFocusOuter => static_prefs::pref!("layout.css.moz-focus-outer.enabled"),
            _ => true,
        }
    }

    /// Whether this pseudo is enabled explicitly in UA sheets.
    pub fn enabled_in_ua_sheets(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS) != 0
    }

    /// Whether this pseudo is enabled explicitly in chrome sheets.
    pub fn enabled_in_chrome(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_CHROME) != 0
    }

    /// Whether this pseudo-element skips flex/grid container display-based
    /// fixup.
    #[inline]
    pub fn skip_item_display_fixup(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
    }

    /// Whether this pseudo-element is precomputed.
    #[inline]
    pub fn is_precomputed(&self) -> bool {
        self.is_anon_box() && !self.is_tree_pseudo_element()
    }

    /// Property flag that properties must have to apply to this pseudo-element.
    #[inline]
    pub fn property_restriction(&self) -> Option<PropertyFlags> {
        Some(match *self {
            PseudoElement::FirstLetter => PropertyFlags::APPLIES_TO_FIRST_LETTER,
            PseudoElement::FirstLine => PropertyFlags::APPLIES_TO_FIRST_LINE,
            PseudoElement::Placeholder => PropertyFlags::APPLIES_TO_PLACEHOLDER,
            PseudoElement::Cue => PropertyFlags::APPLIES_TO_CUE,
            PseudoElement::Marker if static_prefs::pref!("layout.css.marker.restricted") => {
                PropertyFlags::APPLIES_TO_MARKER
            },
            _ => return None,
        })
    }

    /// Whether this pseudo-element should actually exist if it has
    /// the given styles.
    pub fn should_exist(&self, style: &ComputedValues) -> bool {
        debug_assert!(self.is_eager());

        if style.get_box().clone_display() == Display::None {
            return false;
        }

        if self.is_before_or_after() && style.ineffective_content_property() {
            return false;
        }

        true
    }
}
<commit_msg>style: Implement the ::file-chooser-button pseudo-element.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.

use crate::gecko_bindings::structs::{self, PseudoStyleType};
use crate::properties::longhands::display::computed_value::T as Display;
use crate::properties::{ComputedValues, PropertyFlags};
use crate::selector_parser::{PseudoElementCascadeType, SelectorImpl};
use crate::str::{starts_with_ignore_ascii_case, string_as_ascii_lowercase};
use crate::string_cache::Atom;
use crate::values::serialize_atom_identifier;
use cssparser::ToCss;
use std::fmt;
use thin_slice::ThinBoxedSlice;

include!(concat!(
    env!("OUT_DIR"),
    "/gecko/pseudo_element_definition.rs"
));

impl ::selectors::parser::PseudoElement for PseudoElement {
    type Impl = SelectorImpl;

    // ::slotted() should support all tree-abiding pseudo-elements, see
    // https://drafts.csswg.org/css-scoping/#slotted-pseudo
    // https://drafts.csswg.org/css-pseudo-4/#treelike
    #[inline]
    fn valid_after_slotted(&self) -> bool {
        matches!(
            *self,
            PseudoElement::Before |
                PseudoElement::After |
                PseudoElement::Marker |
                PseudoElement::Placeholder |
                PseudoElement::FileChooserButton
        )
    }

    #[inline]
    fn accepts_state_pseudo_classes(&self) -> bool {
        self.supports_user_action_state()
    }
}

impl PseudoElement {
    /// Returns the kind of cascade type that a given pseudo is going to use.
    ///
    /// In Gecko we only compute ::before and ::after eagerly. We save the rules
    /// for anonymous boxes separately, so we resolve them as precomputed
    /// pseudos.
    ///
    /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
    pub fn cascade_type(&self) -> PseudoElementCascadeType {
        if self.is_eager() {
            debug_assert!(!self.is_anon_box());
            return PseudoElementCascadeType::Eager;
        }

        if self.is_precomputed() {
            return PseudoElementCascadeType::Precomputed;
        }

        PseudoElementCascadeType::Lazy
    }

    /// Whether the pseudo-element should inherit from the default computed
    /// values instead of from the parent element.
    ///
    /// This is not the common thing, but there are some pseudos (namely:
    /// ::backdrop), that shouldn't inherit from the parent element.
    pub fn inherits_from_default_values(&self) -> bool {
        matches!(*self, PseudoElement::Backdrop)
    }

    /// Gets the canonical index of this eagerly-cascaded pseudo-element.
    #[inline]
    pub fn eager_index(&self) -> usize {
        EAGER_PSEUDOS
            .iter()
            .position(|p| p == self)
            .expect("Not an eager pseudo")
    }

    /// Creates a pseudo-element from an eager index.
    #[inline]
    pub fn from_eager_index(i: usize) -> Self {
        EAGER_PSEUDOS[i].clone()
    }

    /// Whether the current pseudo element is animatable.
    #[inline]
    pub fn is_animatable(&self) -> bool {
        matches!(*self, Self::Before | Self::After | Self::Marker)
    }

    /// Whether the current pseudo element is ::before or ::after.
    #[inline]
    pub fn is_before_or_after(&self) -> bool {
        self.is_before() || self.is_after()
    }

    /// Whether this pseudo-element is the ::before pseudo.
    #[inline]
    pub fn is_before(&self) -> bool {
        *self == PseudoElement::Before
    }

    /// Whether this pseudo-element is the ::after pseudo.
    #[inline]
    pub fn is_after(&self) -> bool {
        *self == PseudoElement::After
    }

    /// Whether this pseudo-element is the ::marker pseudo.
    #[inline]
    pub fn is_marker(&self) -> bool {
        *self == PseudoElement::Marker
    }

    /// Whether this pseudo-element is the ::selection pseudo.
    #[inline]
    pub fn is_selection(&self) -> bool {
        *self == PseudoElement::Selection
    }

    /// Whether this pseudo-element is ::first-letter.
    #[inline]
    pub fn is_first_letter(&self) -> bool {
        *self == PseudoElement::FirstLetter
    }

    /// Whether this pseudo-element is ::first-line.
    #[inline]
    pub fn is_first_line(&self) -> bool {
        *self == PseudoElement::FirstLine
    }

    /// Whether this pseudo-element is the ::-moz-color-swatch pseudo.
    #[inline]
    pub fn is_color_swatch(&self) -> bool {
        *self == PseudoElement::MozColorSwatch
    }

    /// Whether this pseudo-element is lazily-cascaded.
    #[inline]
    pub fn is_lazy(&self) -> bool {
        !self.is_eager() && !self.is_precomputed()
    }

    /// Whether this pseudo-element supports user action selectors.
    pub fn supports_user_action_state(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
    }

    /// Whether this pseudo-element is enabled for all content.
    pub fn enabled_in_content(&self) -> bool {
        match *self {
            PseudoElement::MozFocusOuter => static_prefs::pref!("layout.css.moz-focus-outer.enabled"),
            PseudoElement::FileChooserButton => static_prefs::pref!("layout.css.file-chooser-button.enabled"),
            _ => {
                (self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME) == 0
            }
        }
    }

    /// Whether this pseudo is enabled explicitly in UA sheets.
    pub fn enabled_in_ua_sheets(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS) != 0
    }

    /// Whether this pseudo is enabled explicitly in chrome sheets.
    pub fn enabled_in_chrome(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_CHROME) != 0
    }

    /// Whether this pseudo-element skips flex/grid container display-based
    /// fixup.
    #[inline]
    pub fn skip_item_display_fixup(&self) -> bool {
        (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
    }

    /// Whether this pseudo-element is precomputed.
    #[inline]
    pub fn is_precomputed(&self) -> bool {
        self.is_anon_box() && !self.is_tree_pseudo_element()
    }

    /// Property flag that properties must have to apply to this pseudo-element.
    #[inline]
    pub fn property_restriction(&self) -> Option<PropertyFlags> {
        Some(match *self {
            PseudoElement::FirstLetter => PropertyFlags::APPLIES_TO_FIRST_LETTER,
            PseudoElement::FirstLine => PropertyFlags::APPLIES_TO_FIRST_LINE,
            PseudoElement::Placeholder => PropertyFlags::APPLIES_TO_PLACEHOLDER,
            PseudoElement::Cue => PropertyFlags::APPLIES_TO_CUE,
            PseudoElement::Marker if static_prefs::pref!("layout.css.marker.restricted") => {
                PropertyFlags::APPLIES_TO_MARKER
            },
            _ => return None,
        })
    }

    /// Whether this pseudo-element should actually exist if it has
    /// the given styles.
    pub fn should_exist(&self, style: &ComputedValues) -> bool {
        debug_assert!(self.is_eager());

        if style.get_box().clone_display() == Display::None {
            return false;
        }

        if self.is_before_or_after() && style.ineffective_content_property() {
            return false;
        }

        true
    }
}
<|endoftext|>


<commit_before>use std::any::Any;

use rotor::{Machine, Response, EventSet, PollOpt, Evented};
use rotor::{Scope, GenericScope, Void};
use rotor::mio::{TryAccept};

use {StreamSocket, Accept};

/// Trait which must be implemented for a state machine to accept connection
///
/// This basically provides alternative constructor for the state machine.
pub trait Accepted<S: StreamSocket>: Machine {
    type Seed;
    /// The constructor of the state machine from the accepted connection
    fn accepted(sock: S, seed: <Self as Accepted<S>>::Seed,
        scope: &mut Scope<Self::Context>)
        -> Response<Self, Void>;
}

impl<M, A> Accept<M, A>
    where A: TryAccept + Evented + Any,
          A::Output: StreamSocket,
          M: Accepted<A::Output>,
          <M as Accepted<A::Output>>::Seed: Clone,
{
    pub fn new<S: GenericScope>(sock: A,
        seed: <M as Accepted<A::Output>>::Seed, scope: &mut S)
        -> Response<Self, Void>
    {
        match scope.register(&sock, EventSet::readable(), PollOpt::edge()) {
            Ok(()) => {}
            Err(e) => return Response::error(Box::new(e)),
        }
        Response::ok(Accept::Server(sock, seed))
    }
}

impl<M, A> Machine for Accept<M, A>
    where A: TryAccept + Evented + Any,
          A::Output: StreamSocket,
          M: Accepted<A::Output>,
          <M as Accepted<A::Output>>::Seed: Clone,
{
    type Context = M::Context;
    type Seed = (A::Output, <M as Accepted<A::Output>>::Seed);
    fn create((sock, seed): Self::Seed, scope: &mut Scope<Self::Context>)
        -> Response<Self, Void>
    {
        M::accepted(sock, seed, scope).wrap(Accept::Connection)
    }

    fn ready(self, events: EventSet, scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            Accept::Server(a, s) => {
                match a.accept() {
                    Ok(Some(sock)) => {
                        let seed = (sock, s.clone());
                        Response::spawn(Accept::Server(a, s), seed)
                    }
                    Ok(None) =>  {
                        Response::ok(Accept::Server(a, s))
                    }
                    Err(_) => {
                        // TODO(tailhook) maybe log the error
                        Response::ok(Accept::Server(a, s))
                    }
                }
            }
            Accept::Connection(m) => {
                m.ready(events, scope)
                    .map(Accept::Connection, |_| unreachable!())
            }
        }
    }

    fn spawned(self, _scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            Accept::Server(a, s) => {
                match a.accept() {
                    Ok(Some(sock)) => {
                        let seed = (sock, s.clone());
                        Response::spawn(Accept::Server(a, s), seed)
                    }
                    Ok(None) =>  {
                        Response::ok(Accept::Server(a, s))
                    }
                    Err(_) => {
                        // TODO(tailhook) maybe log the error
                        Response::ok(Accept::Server(a, s))
                    }
                }
            }
            Accept::Connection(_) => {
                unreachable!();
            }
        }
    }

    fn timeout(self, scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            Accept::Server(..) => unreachable!(),
            Accept::Connection(m) => {
                m.timeout(scope).map(Accept::Connection, |_| unreachable!())
            }
        }
    }

    fn wakeup(self, scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            me @ Accept::Server(..) => Response::ok(me),
            Accept::Connection(m) => {
                m.wakeup(scope).map(Accept::Connection, |_| unreachable!())
            }
        }
    }
}
<commit_msg>Simplified type constraints a bit<commit_after>use std::any::Any;

use rotor::{Machine, Response, EventSet, PollOpt, Evented};
use rotor::{Scope, GenericScope, Void};
use rotor::mio::{TryAccept};

use {StreamSocket, Accept};

/// Trait which must be implemented for a state machine to accept connection
///
/// This basically provides alternative constructor for the state machine.
pub trait Accepted<S: StreamSocket>: Machine {
    type Seed: Clone;
    /// The constructor of the state machine from the accepted connection
    fn accepted(sock: S, seed: <Self as Accepted<S>>::Seed,
        scope: &mut Scope<Self::Context>)
        -> Response<Self, Void>;
}

impl<M, A> Accept<M, A>
    where A: TryAccept + Evented + Any,
          A::Output: StreamSocket,
          M: Accepted<A::Output>,
{
    pub fn new<S: GenericScope>(sock: A,
        seed: <M as Accepted<A::Output>>::Seed, scope: &mut S)
        -> Response<Self, Void>
    {
        match scope.register(&sock, EventSet::readable(), PollOpt::edge()) {
            Ok(()) => {}
            Err(e) => return Response::error(Box::new(e)),
        }
        Response::ok(Accept::Server(sock, seed))
    }
}

impl<M, A> Machine for Accept<M, A>
    where A: TryAccept + Evented + Any,
          A::Output: StreamSocket,
          M: Accepted<A::Output>,
{
    type Context = M::Context;
    type Seed = (A::Output, <M as Accepted<A::Output>>::Seed);
    fn create((sock, seed): Self::Seed, scope: &mut Scope<Self::Context>)
        -> Response<Self, Void>
    {
        M::accepted(sock, seed, scope).wrap(Accept::Connection)
    }

    fn ready(self, events: EventSet, scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            Accept::Server(a, s) => {
                match a.accept() {
                    Ok(Some(sock)) => {
                        let seed = (sock, s.clone());
                        Response::spawn(Accept::Server(a, s), seed)
                    }
                    Ok(None) =>  {
                        Response::ok(Accept::Server(a, s))
                    }
                    Err(_) => {
                        // TODO(tailhook) maybe log the error
                        Response::ok(Accept::Server(a, s))
                    }
                }
            }
            Accept::Connection(m) => {
                m.ready(events, scope)
                    .map(Accept::Connection, |_| unreachable!())
            }
        }
    }

    fn spawned(self, _scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            Accept::Server(a, s) => {
                match a.accept() {
                    Ok(Some(sock)) => {
                        let seed = (sock, s.clone());
                        Response::spawn(Accept::Server(a, s), seed)
                    }
                    Ok(None) =>  {
                        Response::ok(Accept::Server(a, s))
                    }
                    Err(_) => {
                        // TODO(tailhook) maybe log the error
                        Response::ok(Accept::Server(a, s))
                    }
                }
            }
            Accept::Connection(_) => {
                unreachable!();
            }
        }
    }

    fn timeout(self, scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            Accept::Server(..) => unreachable!(),
            Accept::Connection(m) => {
                m.timeout(scope).map(Accept::Connection, |_| unreachable!())
            }
        }
    }

    fn wakeup(self, scope: &mut Scope<Self::Context>)
        -> Response<Self, Self::Seed>
    {
        match self {
            me @ Accept::Server(..) => Response::ok(me),
            Accept::Connection(m) => {
                m.wakeup(scope).map(Accept::Connection, |_| unreachable!())
            }
        }
    }
}
<|endoftext|>


<commit_before>#![doc = r#"Activation literal type and helpers.

For an explanation of what activation literal are, see
[the discussion below][why actlits].

**NB**: while `rmst2`'s actlit API declares some constant symbols in the
underlying solver, these will not appear in the result of
[`get_model`](get_model) queries.

# Relevant functions on solvers

- [`get_actlit`](../trait.Solver.html#method.get_actlit)
- [`get_sactlit`](../trait.Solver.html#method.get_sactlit)
- [`de_actlit`](../trait.Solver.html#method.de_actlit)
- [`set_actlit`](../trait.Solver.html#method.set_actlit)
- [`assert_act`](../trait.Solver.html#method.assert_act)
- [`assert_act_u`](../trait.Solver.html#method.assert_act_u)
- [`print_check_sat_act`](../trait.Solver.html#method.print_check_sat_act)
- [`check_sat_act`](../trait.Solver.html#method.check_sat_act)
- [`check_sat_act_or_unknown`](../trait.Solver.html#method.check_sat_act_or_unknown)

# Usage

First, note that one can create activation literals by hand, and use them in
`check-sat`s with [`check_sat_assuming`][check sat ass]:

```
use rsmt2::* ;

let mut kid = match Kid::default() {
  Ok(kid) => kid,
  Err(e) => panic!("Could not spawn solver kid: {:?}", e)
} ;

{
  let mut solver = solver(& mut kid, ()).unwrap() ;
  solver.declare_const_u("x", "Int").unwrap() ;

  solver.declare_const_u("actlit", "Bool").unwrap() ;
  solver.assert_u("\
    (=> actlit \
        (and (> x 0) (< x 3) (= (mod x 3) 0))\
    )\
  ").unwrap() ;
  assert!{
    ! solver.check_sat_assuming_u( Some("actlit") ).unwrap()
  }
  solver.assert_u("(not actlit)").unwrap() ;

  solver.declare_const_u("other_actlit", "Bool").unwrap() ;
  solver.assert_u("\
    (=> other_actlit \
        (and (> x 7) (= (mod x 2) 0))\
    )\
  ").unwrap() ;
  assert!{
    solver.check_sat_assuming_u( Some("other_actlit") ).unwrap()
  }
  solver.assert_u("(not other_actlit)").unwrap() ;
}

kid.kill().unwrap()
```

The activation literal API makes this process more straightforward:

```
use rsmt2::* ;

let mut kid = match Kid::default() {
  Ok(kid) => kid,
  Err(e) => panic!("Could not spawn solver kid: {:?}", e)
} ;

{
  let mut solver = solver(& mut kid, ()).unwrap() ;
  solver.declare_const_u("x", "Int").unwrap() ;

  let actlit = solver.get_actlit().unwrap() ;
  solver.assert_act_u(& actlit, "(> x 0)").unwrap() ;
  solver.assert_act_u(& actlit, "(< x 3)").unwrap() ;
  solver.assert_act_u(& actlit, "(= (mod x 3) 0)").unwrap() ;

  assert!{
    ! solver.check_sat_act( Some(& actlit) ).unwrap()
  }
  solver.de_actlit(actlit).unwrap() ;
  // At this point `actlit` has been consumed. So it's a bit safer than the
  // version above, since use-after-deactivate is not possible.

  let actlit = solver.get_actlit().unwrap() ;
  solver.assert_act_u(& actlit, "(> x 7)").unwrap() ;
  solver.assert_act_u(& actlit, "(= (mod x 2) 0)").unwrap() ;
  assert!{
    solver.check_sat_act( Some(& actlit) ).unwrap()
  }
  solver.de_actlit(actlit).unwrap()
}

kid.kill().unwrap()
```

**NB**: under the hood, `rmst2` declares a constant boolean symbol for each
actlit. Hence, there is a (very low) risk of collision with the user's symbol.
The internal actlits are named `"|rsmt2 actlit <uid>|"`. Any symbol starting
with `"|rsmt2 actlit "` is assumed to be a `rsmt2` actlit. In particular, such
symbols will be pruned out of `get_model` queries (if at least one actlit was
requested since the last reset).

```
use rsmt2::* ;

let mut kid = match Kid::default() {
  Ok(kid) => kid,
  Err(e) => panic!("Could not spawn solver kid: {:?}", e)
} ;

struct Parser ;
impl<'a> IdentParser<'a, String, (), & 'a str> for Parser {
  fn parse_ident(self, s: & 'a str) -> SmtRes<String> {
    Ok(s.to_string())
  }
  fn parse_type(self, s: & 'a str) -> SmtRes<()> {
    bail!("type parsing is unimplemented")
  }
}
impl<'a> ValueParser<'a , String, & 'a str> for

{
  let mut solver = solver(& mut kid, ()).unwrap() ;
  solver.declare_const_u("x", "Int").unwrap() ;

  let actlit = solver.get_actlit().unwrap() ;
  let mut buf: Vec<u8> = vec![] ;
  actlit.write(& mut buf).unwrap() ;
  assert_eq!{
    "|rsmt2 actlit 0|",
    ::std::str::from_utf8(& buf).unwrap()
  }

  solver.assert_act_u(& actlit, "(> x 7)").unwrap() ;
  solver.assert_act_u(& actlit, "(= (mod x 2) 0)").unwrap() ;
  assert!{
    solver.check_sat_act( Some(& actlit) ).unwrap()
  }

  solver.de_actlit(actlit).unwrap()
}

kid.kill().unwrap()
```

# Discussion on activation literals

The activation literal technique is a much more efficient alternative to the
`push`/`pop` SMT-LIB commands. When a `pop` command is issued, solvers usually
reset themselves and re-declare/assert whatever was before the last push.

Activation literals are boolean nullary symbols controlling the activation of
some assertions.

For instance

```smt
(declare-fun x () Int)

(push 1)
  (assert (> x 0))
  (assert (< x 3))
  (assert (= (mod x 3) 0))
  (check-sat)
  ; unsat
(pop 1)

(push 1)
  (assert (> x 7))
  (assert (= (mod x 2) 0))
  (check-sat)
  (get-value (x))
(pop 1)
```

can be encoded with activation literals as

```smt
(declare-fun x () Int)

(declare-fun actlit_1 () Bool)
(declare-fun actlit_2 () Bool)

(assert (=> actlit_1 (> x 0)) )
(assert (=> actlit_2 (< x 3)) )
(assert (=> actlit_2 (= (mod x 3) 0)) )
(check-sat actlit_1 actlit_2) ; <--- Conditional check-sat
                              ;      usually called "check-sat-assuming"
; unsat

(assert (not actlit_2)) ; <--- Actlit deactivation
                        ;      all its assertions basically disappear

(declare-fun actlit_3 () Bool)

(assert (=> actlit_3 (> x 7)) )
(assert (=> actlit_3 (= (mod x 2) 0)) )
(check-sat actlit_1 actlit_3)
; sat
(get-value (x))
```

This is much more efficient than `push`/`pop`: the conditional `check-sat`s
basically force the activation literals directly in the SAT part of the SMT
solver. Long story short, this means everything the solver learns during the
checks is still valid afterwards. Conversely, after a `pop` solvers are
usually unable to decide what to keep from the checks before the `pop`, and
thus drop everything.

[why actlits]: #discussion-on-activation-literals (Activation literals, why?)
[SActlit]: struct.SActlit.html (SActlit documentation)
[Actlit]: struct.Actlit.html (Actlit documentation)
[phantom]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html (PhantomData documentation)
[check sat ass]: ../trait.Solver.html#method.check_sat_assuming (check_sat_assuming function)
[get_model]: ../trait.Solver.html#method.get_model (get_model function)

"#]

pub use solver::Actlit ;<commit_msg>fixed doc tests<commit_after>#![doc = r#"Activation literal type and helpers.

For an explanation of what activation literal are, see
[the discussion below][why actlits].

**NB**: while `rmst2`'s actlit API declares some constant symbols in the
underlying solver, these will not appear in the result of
[`get_model`](get_model) queries.

# Relevant functions on solvers

- [`get_actlit`](../trait.Solver.html#method.get_actlit)
- [`get_sactlit`](../trait.Solver.html#method.get_sactlit)
- [`de_actlit`](../trait.Solver.html#method.de_actlit)
- [`set_actlit`](../trait.Solver.html#method.set_actlit)
- [`assert_act`](../trait.Solver.html#method.assert_act)
- [`assert_act_u`](../trait.Solver.html#method.assert_act_u)
- [`print_check_sat_act`](../trait.Solver.html#method.print_check_sat_act)
- [`check_sat_act`](../trait.Solver.html#method.check_sat_act)
- [`check_sat_act_or_unknown`](../trait.Solver.html#method.check_sat_act_or_unknown)

# Usage

First, note that one can create activation literals by hand, and use them in
`check-sat`s with [`check_sat_assuming`][check sat ass]:

```
use rsmt2::* ;

let mut kid = match Kid::default() {
  Ok(kid) => kid,
  Err(e) => panic!("Could not spawn solver kid: {:?}", e)
} ;

{
  let mut solver = solver(& mut kid, ()).unwrap() ;
  solver.declare_const_u("x", "Int").unwrap() ;

  solver.declare_const_u("actlit", "Bool").unwrap() ;
  solver.assert_u("\
    (=> actlit \
        (and (> x 0) (< x 3) (= (mod x 3) 0))\
    )\
  ").unwrap() ;
  assert!{
    ! solver.check_sat_assuming_u( Some("actlit") ).unwrap()
  }
  solver.assert_u("(not actlit)").unwrap() ;

  solver.declare_const_u("other_actlit", "Bool").unwrap() ;
  solver.assert_u("\
    (=> other_actlit \
        (and (> x 7) (= (mod x 2) 0))\
    )\
  ").unwrap() ;
  assert!{
    solver.check_sat_assuming_u( Some("other_actlit") ).unwrap()
  }
  solver.assert_u("(not other_actlit)").unwrap() ;
}

kid.kill().unwrap()
```

The activation literal API makes this process more straightforward:

```
use rsmt2::* ;

let mut kid = match Kid::default() {
  Ok(kid) => kid,
  Err(e) => panic!("Could not spawn solver kid: {:?}", e)
} ;

{
  let mut solver = solver(& mut kid, ()).unwrap() ;
  solver.declare_const_u("x", "Int").unwrap() ;

  let actlit = solver.get_actlit().unwrap() ;
  solver.assert_act_u(& actlit, "(> x 0)").unwrap() ;
  solver.assert_act_u(& actlit, "(< x 3)").unwrap() ;
  solver.assert_act_u(& actlit, "(= (mod x 3) 0)").unwrap() ;

  assert!{
    ! solver.check_sat_act( Some(& actlit) ).unwrap()
  }
  solver.de_actlit(actlit).unwrap() ;
  // At this point `actlit` has been consumed. So it's a bit safer than the
  // version above, since use-after-deactivate is not possible.

  let actlit = solver.get_actlit().unwrap() ;
  solver.assert_act_u(& actlit, "(> x 7)").unwrap() ;
  solver.assert_act_u(& actlit, "(= (mod x 2) 0)").unwrap() ;
  assert!{
    solver.check_sat_act( Some(& actlit) ).unwrap()
  }
  solver.de_actlit(actlit).unwrap()
}

kid.kill().unwrap()
```

**NB**: under the hood, `rmst2` declares a constant boolean symbol for each
actlit. Hence, there is a (very low) risk of collision with the user's symbol.
The internal actlits are named `"|rsmt2 actlit <uid>|"`. Any symbol starting
with `"|rsmt2 actlit "` is assumed to be a `rsmt2` actlit. In particular, such
symbols will be pruned out of `get_model` queries (if at least one actlit was
requested since the last reset).

```
use rsmt2::* ;
use rsmt2::parse::* ;

let mut kid = match Kid::default() {
  Ok(kid) => kid,
  Err(e) => panic!("Could not spawn solver kid: {:?}", e)
} ;

struct Parser ;
impl<'a, 'b> IdentParser<'a, String, String, & 'a str> for & 'b Parser {
  fn parse_ident(self, s: & 'a str) -> SmtRes<String> {
    Ok(s.to_string())
  }
  fn parse_type(self, s: & 'a str) -> SmtRes<String> {
    Ok(s.to_string())
  }
}
impl<'a, 'b> ValueParser<'a , String, & 'a str> for & 'b Parser {
  fn parse_value(self, s: & 'a str) -> SmtRes<String> {
    Ok(s.to_string())
  }
}

{
  let mut solver = solver(& mut kid, & Parser).unwrap() ;
  solver.declare_const_u("x", "Int").unwrap() ;

  let actlit = solver.get_actlit().unwrap() ;
  let mut buf: Vec<u8> = vec![] ;
  actlit.write(& mut buf).unwrap() ;
  assert_eq!{
    "|rsmt2 actlit 0|",
    ::std::str::from_utf8(& buf).unwrap()
  }

  solver.assert_act_u(& actlit, "(> x 7)").unwrap() ;
  solver.assert_act_u(& actlit, "(= (mod x 2) 0)").unwrap() ;
  assert!{
    solver.check_sat_act( Some(& actlit) ).unwrap()
  }

  let model = solver.get_model_const().unwrap() ;
  let mut model = model.into_iter() ;
  if let Some((x, int, n)) = model.next() {
    assert_eq!{ x, "x" }
    assert_eq!{ int, "Int" }
    use std::str::FromStr ;
    let n = i64::from_str(& n).unwrap() ;
    println!("{}", n) ;
    assert!{ n > 7 }
    assert!{ n % 2 == 0 }
  } else {
    panic!("expected the model for `x`")
  }
  assert_eq!{
    model.next(), None
  }

  solver.de_actlit(actlit).unwrap()
}

kid.kill().unwrap()
```

# Discussion on activation literals

The activation literal technique is a much more efficient alternative to the
`push`/`pop` SMT-LIB commands. When a `pop` command is issued, solvers usually
reset themselves and re-declare/assert whatever was before the last push.

Activation literals are boolean nullary symbols controlling the activation of
some assertions.

For instance

```smt
(declare-fun x () Int)

(push 1)
  (assert (> x 0))
  (assert (< x 3))
  (assert (= (mod x 3) 0))
  (check-sat)
  ; unsat
(pop 1)

(push 1)
  (assert (> x 7))
  (assert (= (mod x 2) 0))
  (check-sat)
  (get-value (x))
(pop 1)
```

can be encoded with activation literals as

```smt
(declare-fun x () Int)

(declare-fun actlit_1 () Bool)
(declare-fun actlit_2 () Bool)

(assert (=> actlit_1 (> x 0)) )
(assert (=> actlit_2 (< x 3)) )
(assert (=> actlit_2 (= (mod x 3) 0)) )
(check-sat actlit_1 actlit_2) ; <--- Conditional check-sat
                              ;      usually called "check-sat-assuming"
; unsat

(assert (not actlit_2)) ; <--- Actlit deactivation
                        ;      all its assertions basically disappear

(declare-fun actlit_3 () Bool)

(assert (=> actlit_3 (> x 7)) )
(assert (=> actlit_3 (= (mod x 2) 0)) )
(check-sat actlit_1 actlit_3)
; sat
(get-value (x))
```

This is much more efficient than `push`/`pop`: the conditional `check-sat`s
basically force the activation literals directly in the SAT part of the SMT
solver. Long story short, this means everything the solver learns during the
checks is still valid afterwards. Conversely, after a `pop` solvers are
usually unable to decide what to keep from the checks before the `pop`, and
thus drop everything.

[why actlits]: #discussion-on-activation-literals (Activation literals, why?)
[SActlit]: struct.SActlit.html (SActlit documentation)
[Actlit]: struct.Actlit.html (Actlit documentation)
[phantom]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html (PhantomData documentation)
[check sat ass]: ../trait.Solver.html#method.check_sat_assuming (check_sat_assuming function)
[get_model]: ../trait.Solver.html#method.get_model (get_model function)

"#]

pub use solver::Actlit ;<|endoftext|>