<commit_before>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * hir_typeck/impl_ref.cpp
 * - Reference to a trait implementation (either a bound or a impl block)
 */
#include "impl_ref.hpp"
#include <hir/hir.hpp>
#include "static.hpp"   // for monomorphise_type_with

bool ImplRef::more_specific_than(const ImplRef& other) const
{
    TU_MATCH(Data, (this->m_data), (te),
    (TraitImpl,
        if( te.impl == nullptr ) {
            return false;
        }
        TU_MATCH(Data, (other.m_data), (oe),
        (TraitImpl,
            if( oe.impl == nullptr ) {
                return true;
            }
            return te.impl->more_specific_than( *oe.impl );
            ),
        (BoundedPtr,
            return false;
            ),
        (Bounded,
            return false;
            )
        )
        ),
    (BoundedPtr,
        if( !other.m_data.is_BoundedPtr() )
            return false;
        const auto& oe = other.m_data.as_BoundedPtr();
        assert( *te.type == *oe.type );
        assert( *te.trait_args == *oe.trait_args );
        if( te.assoc->size() > oe.assoc->size() )
            return true;
        return false;
        ),
    (Bounded,
        if( !other.m_data.is_Bounded() )
            return false;
        const auto& oe = other.m_data.as_Bounded();
        assert( te.type == oe.type );
        assert( te.trait_args == oe.trait_args );
        if( te.assoc.size() > oe.assoc.size() )
            return true;
        return false;
        )
    )
    throw "";
}
bool ImplRef::overlaps_with(const ::HIR::Crate& crate, const ImplRef& other) const
{
    if( this->m_data.tag() != other.m_data.tag() )
        return false;
    TU_MATCH(Data, (this->m_data, other.m_data), (te, oe),
    (TraitImpl,
        if( te.impl != nullptr && oe.impl != nullptr )
            return te.impl->overlaps_with( crate, *oe.impl );
        ),
    (BoundedPtr,
        // TODO: Bounded and BoundedPtr are compatible
        if( *te.type != *oe.type )
            return false;
        if( *te.trait_args != *oe.trait_args )
            return false;
        // Don't check associated types
        return true;
        ),
    (Bounded,
        if( te.type != oe.type )
            return false;
        if( te.trait_args != oe.trait_args )
            return false;
        // Don't check associated types
        return true;
        )
    )
    return false;
}
bool ImplRef::has_magic_params() const
{
    if(const auto* e = m_data.opt_TraitImpl())
    {
        for(const auto& t : e->impl_params.m_types)
            if( visit_ty_with(t, [](const ::HIR::TypeRef& t){ return t.data().is_Generic() && (t.data().as_Generic().binding >> 8) == 2; }) )
                return true;
    }
    return false;
}
bool ImplRef::type_is_specialisable(const char* name) const
{
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            // No impl yet? This type is specialisable.
            return true;
        }
        //TODO(Span(), "type_is_specializable - Impl = " << *this << ", Type = " << name);
        auto it = e.impl->m_types.find(name);
        if( it == e.impl->m_types.end() ) {
            TODO(Span(), "Handle missing type in " << *this << ", name = " << name);
            return false;
        }
        return it->second.is_specialisable;
        ),
    (BoundedPtr,
        return false;
        ),
    (Bounded,
        return false;
        )
    )
    throw "";
}

// Returns a closure to monomorphise including placeholders (if present)
ImplRef::Monomorph ImplRef::get_cb_monomorph_traitimpl(const Span& sp) const
{
    const auto& e = this->m_data.as_TraitImpl();
    return Monomorph(e);
}

::HIR::TypeRef ImplRef::Monomorph::get_type(const Span& sp, const ::HIR::GenericRef& ge) const /*override*/
{
    if( ge.is_self() )
    {
        // Store (or cache) a monomorphisation of Self, and error if this recurses
        if( this->ti.self_cache == ::HIR::TypeRef() ) {
            this->ti.self_cache = ::HIR::TypeRef::new_diverge();
            this->ti.self_cache = this->monomorph_type(sp, this->ti.impl->m_type);
        }
        else if( this->ti.self_cache == ::HIR::TypeRef::new_diverge() ) {
            // BUG!
            BUG(sp, "Use of `Self` in expansion of `Self`");
        }
        else {
        }
        return this->ti.self_cache.clone();
    }
    ASSERT_BUG(sp, ge.binding < 256, "Binding in " << ge << " out of range (>=256)");
    ASSERT_BUG(sp, ge.binding < this->ti.impl_params.m_types.size(), "Binding in " << ge << " out of range (>= " << this->ti.impl_params.m_types.size() << ")");
    return this->ti.impl_params.m_types.at(ge.binding).clone();
}
::HIR::ConstGeneric ImplRef::Monomorph::get_value(const Span& sp, const ::HIR::GenericRef& val) const /*override*/
{
    ASSERT_BUG(sp, val.binding < 256, "Generic value binding in " << val << " out of range (>=256)");
    ASSERT_BUG(sp, val.binding < this->ti.impl_params.m_values.size(), "Generic value binding in " << val << " out of range (>= " << this->ti.impl_params.m_values.size() << ")");
    return this->ti.impl_params.m_values.at(val.binding).clone();
}

::HIR::TypeRef ImplRef::get_impl_type() const
{
    Span    sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            BUG(Span(), "nullptr");
        }
        return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_type);
        ),
    (BoundedPtr,
        return e.type->clone();
        ),
    (Bounded,
        return e.type.clone();
        )
    )
    throw "";
}
::HIR::PathParams ImplRef::get_trait_params() const
{
    Span    sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            BUG(Span(), "nullptr");
        }

        return this->get_cb_monomorph_traitimpl(sp).monomorph_path_params(sp, e.impl->m_trait_args, true);
        ),
    (BoundedPtr,
        return e.trait_args->clone();
        ),
    (Bounded,
        return e.trait_args.clone();
        )
    )
    throw "";
}
::HIR::TypeRef ImplRef::get_trait_ty_param(unsigned int idx) const
{
    Span    sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            BUG(Span(), "nullptr");
        }
        if( idx >= e.impl->m_trait_args.m_types.size() )
            return ::HIR::TypeRef();
        return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_trait_args.m_types[idx]);
        ),
    (BoundedPtr,
        if( idx >= e.trait_args->m_types.size() )
            return ::HIR::TypeRef();
        return e.trait_args->m_types.at(idx).clone();
        ),
    (Bounded,
        if( idx >= e.trait_args.m_types.size() )
            return ::HIR::TypeRef();
        return e.trait_args.m_types.at(idx).clone();
        )
    )
    throw "";
    TODO(Span(), "");
}

::HIR::TypeRef ImplRef::get_type(const char* name) const
{
    if( !name[0] )
        return ::HIR::TypeRef();
    static Span  sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        auto it = e.impl->m_types.find(name);
        if( it == e.impl->m_types.end() )
            return ::HIR::TypeRef();
        const ::HIR::TypeRef& tpl_ty = it->second.data;
        DEBUG("name=" << name << " tpl_ty=" << tpl_ty << " " << *this);
        if( monomorphise_type_needed(tpl_ty) ) {
            return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, tpl_ty);
        }
        else {
            return tpl_ty.clone();
        }
        ),
    (BoundedPtr,
        auto it = e.assoc->find(name);
        if(it == e.assoc->end())
            return ::HIR::TypeRef();
        return it->second.type.clone();
        ),
    (Bounded,
        auto it = e.assoc.find(name);
        if(it == e.assoc.end())
            return ::HIR::TypeRef();
        return it->second.type.clone();
        )
    )
    return ::HIR::TypeRef();
}

::std::ostream& operator<<(::std::ostream& os, const ImplRef& x)
{
    TU_MATCH_HDR( (x.m_data), { )
    TU_ARM(x.m_data, TraitImpl, e) {
        if( e.impl == nullptr ) {
            os << "none";
        }
        else {
            os << "impl";
            os << "(" << e.impl << ")";
            if( e.impl->m_params.m_types.size() )
            {
                os << "<";
                for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )
                {
                    const auto& ty_d = e.impl->m_params.m_types[i];
                    os << ty_d.m_name;
                    os << ",";
                }
                os << ">";
            }
            os << " " << *e.trait_path << e.impl->m_trait_args << " for " << e.impl->m_type << e.impl->m_params.fmt_bounds();
            os << " {";
            for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )
            {
                const auto& ty_d = e.impl->m_params.m_types[i];
                os << ty_d.m_name << " = ";
                if( e.impl_params.m_types[i] != HIR::TypeRef() ) {
                    os << e.impl_params.m_types[i];
                }
                else {
                    os << "?";
                }
                os << ",";
            }
            for(const auto& aty : e.impl->m_types)
            {
                os << "Self::" << aty.first << " = " << aty.second.data << ",";
            }
            os << "}";
        }
        }
    TU_ARM(x.m_data, BoundedPtr, e) {
        assert(e.type);
        assert(e.trait_args);
        assert(e.assoc);
        os << "bound (ptr) " << *e.type << " : ?" << *e.trait_args << " + {" << *e.assoc << "}";
        }
    TU_ARM(x.m_data, Bounded, e) {
        os << "bound " << e.type << " : ?" << e.trait_args << " + {"<<e.assoc<<"}";
        }
    }
    return os;
}
<commit_msg>HIR Typecheck - Tweak logic for `type_is_specialisable`<commit_after>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * hir_typeck/impl_ref.cpp
 * - Reference to a trait implementation (either a bound or a impl block)
 */
#include "impl_ref.hpp"
#include <hir/hir.hpp>
#include "static.hpp"   // for monomorphise_type_with

bool ImplRef::more_specific_than(const ImplRef& other) const
{
    TU_MATCH(Data, (this->m_data), (te),
    (TraitImpl,
        if( te.impl == nullptr ) {
            return false;
        }
        TU_MATCH(Data, (other.m_data), (oe),
        (TraitImpl,
            if( oe.impl == nullptr ) {
                return true;
            }
            return te.impl->more_specific_than( *oe.impl );
            ),
        (BoundedPtr,
            return false;
            ),
        (Bounded,
            return false;
            )
        )
        ),
    (BoundedPtr,
        if( !other.m_data.is_BoundedPtr() )
            return false;
        const auto& oe = other.m_data.as_BoundedPtr();
        assert( *te.type == *oe.type );
        assert( *te.trait_args == *oe.trait_args );
        if( te.assoc->size() > oe.assoc->size() )
            return true;
        return false;
        ),
    (Bounded,
        if( !other.m_data.is_Bounded() )
            return false;
        const auto& oe = other.m_data.as_Bounded();
        assert( te.type == oe.type );
        assert( te.trait_args == oe.trait_args );
        if( te.assoc.size() > oe.assoc.size() )
            return true;
        return false;
        )
    )
    throw "";
}
bool ImplRef::overlaps_with(const ::HIR::Crate& crate, const ImplRef& other) const
{
    if( this->m_data.tag() != other.m_data.tag() )
        return false;
    TU_MATCH(Data, (this->m_data, other.m_data), (te, oe),
    (TraitImpl,
        if( te.impl != nullptr && oe.impl != nullptr )
            return te.impl->overlaps_with( crate, *oe.impl );
        ),
    (BoundedPtr,
        // TODO: Bounded and BoundedPtr are compatible
        if( *te.type != *oe.type )
            return false;
        if( *te.trait_args != *oe.trait_args )
            return false;
        // Don't check associated types
        return true;
        ),
    (Bounded,
        if( te.type != oe.type )
            return false;
        if( te.trait_args != oe.trait_args )
            return false;
        // Don't check associated types
        return true;
        )
    )
    return false;
}
bool ImplRef::has_magic_params() const
{
    if(const auto* e = m_data.opt_TraitImpl())
    {
        for(const auto& t : e->impl_params.m_types)
            if( visit_ty_with(t, [](const ::HIR::TypeRef& t){ return t.data().is_Generic() && (t.data().as_Generic().binding >> 8) == 2; }) )
                return true;
    }
    return false;
}
bool ImplRef::type_is_specialisable(const char* name) const
{
    TU_MATCH_HDRA( (this->m_data), {)
    TU_ARMA(TraitImpl, e) {
        if( e.impl == nullptr ) {
            // No impl yet? This type is specialisable.
            return true;
        }
        auto it = e.impl->m_types.find(name);
        if( it == e.impl->m_types.end() ) {
            // If not present (which might happen during UFCS resolution), assume that it's specialisable
            return true;
        }
        return it->second.is_specialisable;
        }
    TU_ARMA(BoundedPtr, e) {
        return false;
        }
    TU_ARMA(Bounded, E) {
        return false;
        }
    }
    throw "";
}

// Returns a closure to monomorphise including placeholders (if present)
ImplRef::Monomorph ImplRef::get_cb_monomorph_traitimpl(const Span& sp) const
{
    const auto& e = this->m_data.as_TraitImpl();
    return Monomorph(e);
}

::HIR::TypeRef ImplRef::Monomorph::get_type(const Span& sp, const ::HIR::GenericRef& ge) const /*override*/
{
    if( ge.is_self() )
    {
        // Store (or cache) a monomorphisation of Self, and error if this recurses
        if( this->ti.self_cache == ::HIR::TypeRef() ) {
            this->ti.self_cache = ::HIR::TypeRef::new_diverge();
            this->ti.self_cache = this->monomorph_type(sp, this->ti.impl->m_type);
        }
        else if( this->ti.self_cache == ::HIR::TypeRef::new_diverge() ) {
            // BUG!
            BUG(sp, "Use of `Self` in expansion of `Self`");
        }
        else {
        }
        return this->ti.self_cache.clone();
    }
    ASSERT_BUG(sp, ge.binding < 256, "Binding in " << ge << " out of range (>=256)");
    ASSERT_BUG(sp, ge.binding < this->ti.impl_params.m_types.size(), "Binding in " << ge << " out of range (>= " << this->ti.impl_params.m_types.size() << ")");
    return this->ti.impl_params.m_types.at(ge.binding).clone();
}
::HIR::ConstGeneric ImplRef::Monomorph::get_value(const Span& sp, const ::HIR::GenericRef& val) const /*override*/
{
    ASSERT_BUG(sp, val.binding < 256, "Generic value binding in " << val << " out of range (>=256)");
    ASSERT_BUG(sp, val.binding < this->ti.impl_params.m_values.size(), "Generic value binding in " << val << " out of range (>= " << this->ti.impl_params.m_values.size() << ")");
    return this->ti.impl_params.m_values.at(val.binding).clone();
}

::HIR::TypeRef ImplRef::get_impl_type() const
{
    Span    sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            BUG(Span(), "nullptr");
        }
        return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_type);
        ),
    (BoundedPtr,
        return e.type->clone();
        ),
    (Bounded,
        return e.type.clone();
        )
    )
    throw "";
}
::HIR::PathParams ImplRef::get_trait_params() const
{
    Span    sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            BUG(Span(), "nullptr");
        }

        return this->get_cb_monomorph_traitimpl(sp).monomorph_path_params(sp, e.impl->m_trait_args, true);
        ),
    (BoundedPtr,
        return e.trait_args->clone();
        ),
    (Bounded,
        return e.trait_args.clone();
        )
    )
    throw "";
}
::HIR::TypeRef ImplRef::get_trait_ty_param(unsigned int idx) const
{
    Span    sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        if( e.impl == nullptr ) {
            BUG(Span(), "nullptr");
        }
        if( idx >= e.impl->m_trait_args.m_types.size() )
            return ::HIR::TypeRef();
        return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_trait_args.m_types[idx]);
        ),
    (BoundedPtr,
        if( idx >= e.trait_args->m_types.size() )
            return ::HIR::TypeRef();
        return e.trait_args->m_types.at(idx).clone();
        ),
    (Bounded,
        if( idx >= e.trait_args.m_types.size() )
            return ::HIR::TypeRef();
        return e.trait_args.m_types.at(idx).clone();
        )
    )
    throw "";
    TODO(Span(), "");
}

::HIR::TypeRef ImplRef::get_type(const char* name) const
{
    if( !name[0] )
        return ::HIR::TypeRef();
    static Span  sp;
    TU_MATCH(Data, (this->m_data), (e),
    (TraitImpl,
        auto it = e.impl->m_types.find(name);
        if( it == e.impl->m_types.end() )
            return ::HIR::TypeRef();
        const ::HIR::TypeRef& tpl_ty = it->second.data;
        DEBUG("name=" << name << " tpl_ty=" << tpl_ty << " " << *this);
        if( monomorphise_type_needed(tpl_ty) ) {
            return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, tpl_ty);
        }
        else {
            return tpl_ty.clone();
        }
        ),
    (BoundedPtr,
        auto it = e.assoc->find(name);
        if(it == e.assoc->end())
            return ::HIR::TypeRef();
        return it->second.type.clone();
        ),
    (Bounded,
        auto it = e.assoc.find(name);
        if(it == e.assoc.end())
            return ::HIR::TypeRef();
        return it->second.type.clone();
        )
    )
    return ::HIR::TypeRef();
}

::std::ostream& operator<<(::std::ostream& os, const ImplRef& x)
{
    TU_MATCH_HDR( (x.m_data), { )
    TU_ARM(x.m_data, TraitImpl, e) {
        if( e.impl == nullptr ) {
            os << "none";
        }
        else {
            os << "impl";
            os << "(" << e.impl << ")";
            if( e.impl->m_params.m_types.size() )
            {
                os << "<";
                for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )
                {
                    const auto& ty_d = e.impl->m_params.m_types[i];
                    os << ty_d.m_name;
                    os << ",";
                }
                os << ">";
            }
            os << " " << *e.trait_path << e.impl->m_trait_args << " for " << e.impl->m_type << e.impl->m_params.fmt_bounds();
            os << " {";
            for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )
            {
                const auto& ty_d = e.impl->m_params.m_types[i];
                os << ty_d.m_name << " = ";
                if( e.impl_params.m_types[i] != HIR::TypeRef() ) {
                    os << e.impl_params.m_types[i];
                }
                else {
                    os << "?";
                }
                os << ",";
            }
            for(const auto& aty : e.impl->m_types)
            {
                os << "Self::" << aty.first << " = " << aty.second.data << ",";
            }
            os << "}";
        }
        }
    TU_ARM(x.m_data, BoundedPtr, e) {
        assert(e.type);
        assert(e.trait_args);
        assert(e.assoc);
        os << "bound (ptr) " << *e.type << " : ?" << *e.trait_args << " + {" << *e.assoc << "}";
        }
    TU_ARM(x.m_data, Bounded, e) {
        os << "bound " << e.type << " : ?" << e.trait_args << " + {"<<e.assoc<<"}";
        }
    }
    return os;
}
<|endoftext|>


<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation

Module Name:

    qffpa_tactic.cpp

Abstract:

    Tactic for QF_FPA benchmarks.

Author:

    Christoph (cwinter) 2012-01-16

Notes:

--*/
#include"tactical.h"
#include"simplify_tactic.h"
#include"bit_blaster_tactic.h"
#include"sat_tactic.h"
#include"fpa2bv_tactic.h"

#include"qffpa_tactic.h"

tactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) {
    params_ref sat_simp_p = p;
    sat_simp_p .set_bool("elim_and", true);

    return and_then(mk_simplify_tactic(m, p),
                    mk_fpa2bv_tactic(m, p),
                    using_params(mk_simplify_tactic(m, p), sat_simp_p),
                    mk_bit_blaster_tactic(m, p),
                    using_params(mk_simplify_tactic(m, p), sat_simp_p),
                    mk_sat_tactic(m, p),
                    mk_fail_if_undecided_tactic());
}

struct is_non_qffpa_predicate {
    struct found {};
    ast_manager & m;
    float_util    u;

    is_non_qffpa_predicate(ast_manager & _m) :m(_m), u(m) {}

    void operator()(var *) { throw found(); }

    void operator()(quantifier *) { throw found(); }

    void operator()(app * n) {
        sort * s = get_sort(n);
        if (!m.is_bool(s) && !(u.is_float(s) || u.is_rm(s)))
            throw found();
        family_id fid = s->get_family_id();
        if (fid == m.get_basic_family_id())
            return;
        if (fid == u.get_family_id())
            return;

        throw found();
    }
};

struct is_non_qffpabv_predicate {
    struct found {};
    ast_manager & m;
    bv_util       bu;
    float_util    fu;

    is_non_qffpabv_predicate(ast_manager & _m) :m(_m), bu(m), fu(m) {}

    void operator()(var *) { throw found(); }

    void operator()(quantifier *) { throw found(); }

    void operator()(app * n) {
        sort * s = get_sort(n);
        if (!m.is_bool(s) && !(fu.is_float(s) || fu.is_rm(s) || bu.is_bv_sort(s)))
            throw found();
        family_id fid = s->get_family_id();
        if (fid == m.get_basic_family_id())
            return;
        if (fid == fu.get_family_id() || fid == bu.get_family_id())
            return;

        throw found();
    }
};

class is_qffpa_probe : public probe {
public:
    virtual result operator()(goal const & g) {
        return !test<is_non_qffpa_predicate>(g);
    }
};

class is_qffpabv_probe : public probe {
public:
    virtual result operator()(goal const & g) {
        return !test<is_non_qffpabv_predicate>(g);
    }
};

probe * mk_is_qffpa_probe() {
    return alloc(is_qffpa_probe);
}

probe * mk_is_qffpabv_probe() {
    return alloc(is_qffpabv_probe);
}
    <commit_msg>bugfix for FPA<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation

Module Name:

    qffpa_tactic.cpp

Abstract:

    Tactic for QF_FPA benchmarks.

Author:

    Christoph (cwinter) 2012-01-16

Notes:

--*/
#include"tactical.h"
#include"simplify_tactic.h"
#include"bit_blaster_tactic.h"
#include"sat_tactic.h"
#include"fpa2bv_tactic.h"

#include"qffpa_tactic.h"

tactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) {
    params_ref sat_simp_p = p;
    sat_simp_p .set_bool("elim_and", true);

    return and_then(mk_simplify_tactic(m, p),
                    mk_fpa2bv_tactic(m, p),
                    using_params(mk_simplify_tactic(m, p), sat_simp_p),
                    mk_bit_blaster_tactic(m, p),
                    using_params(mk_simplify_tactic(m, p), sat_simp_p),
                    mk_sat_tactic(m, p),
                    mk_fail_if_undecided_tactic());
}

struct is_non_qffpa_predicate {
    struct found {};
    ast_manager & m;
    float_util    u;

    is_non_qffpa_predicate(ast_manager & _m) :m(_m), u(m) {}

    void operator()(var *) { throw found(); }

    void operator()(quantifier *) { throw found(); }

    void operator()(app * n) {
        sort * s = get_sort(n);
        if (!m.is_bool(s) && !(u.is_float(s) || u.is_rm(s)))
            throw found();
        if (is_uninterp(n))
            throw found();
        family_id fid = s->get_family_id();
        if (fid == m.get_basic_family_id())
            return;
        if (fid == u.get_family_id())
            return;

        throw found();
    }
};

struct is_non_qffpabv_predicate {
    struct found {};
    ast_manager & m;
    bv_util       bu;
    float_util    fu;

    is_non_qffpabv_predicate(ast_manager & _m) :m(_m), bu(m), fu(m) {}

    void operator()(var *) { throw found(); }

    void operator()(quantifier *) { throw found(); }

    void operator()(app * n) {
        sort * s = get_sort(n);
        if (!m.is_bool(s) && !(fu.is_float(s) || fu.is_rm(s) || bu.is_bv_sort(s)))
            throw found();
        if (is_uninterp(n))
            throw found();
        family_id fid = s->get_family_id();
        if (fid == m.get_basic_family_id())
            return;
        if (fid == fu.get_family_id() || fid == bu.get_family_id())
            return;

        throw found();
    }
};

class is_qffpa_probe : public probe {
public:
    virtual result operator()(goal const & g) {
        return !test<is_non_qffpa_predicate>(g);
    }
};

class is_qffpabv_probe : public probe {
public:
    virtual result operator()(goal const & g) {
        return !test<is_non_qffpabv_predicate>(g);
    }
};

probe * mk_is_qffpa_probe() {
    return alloc(is_qffpa_probe);
}

probe * mk_is_qffpabv_probe() {
    return alloc(is_qffpabv_probe);
}
    <|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <oleacc.h>

#include "app/l10n_util.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
  std::wstring title =
      l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
      ASCIIToWide(chrome::kAboutBlankURL));
  TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<commit_msg>Re-enabling TestAboutChromeViewAccObj.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <oleacc.h>

#include "app/l10n_util.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
  std::wstring title =
      l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
      ASCIIToWide(chrome::kAboutBlankURL));
  TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<|endoftext|>


<commit_before>#pragma once

#include <bts/blockchain/config.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/time.hpp>

#ifdef BTS_TEST_NETWORK
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 0
#else
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 4
#endif

#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE 512 // just a random assumption used to calibrate TRX per SEC
/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )

namespace bts { namespace blockchain {

struct delegate_config
{
    uint32_t            network_min_connection_count = NETWORK_MIN_CONNECTION_COUNT_DEFAULT;

    uint32_t            block_max_transaction_count = -1;
    uint32_t            block_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
    fc::microseconds    block_max_production_time = fc::seconds( 3 );

    uint32_t            transaction_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
    bool                transaction_canonical_signatures_required = false;
    share_type          transaction_min_fee = BTS_BLOCKCHAIN_PRECISION / 10;

    set<transaction_id_type>    transaction_blacklist;
    set<operation_type_enum>    operation_blacklist;

    void validate()const
    { try {
        FC_ASSERT( block_max_size <= BTS_BLOCKCHAIN_MAX_BLOCK_SIZE );
        FC_ASSERT( block_max_production_time.count() >= 0 );
        FC_ASSERT( block_max_production_time.to_seconds() <= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC );
        FC_ASSERT( transaction_max_size <= block_max_size );
        FC_ASSERT( transaction_min_fee >= 0 );
        FC_ASSERT( transaction_min_fee <= BTS_BLOCKCHAIN_MAX_SHARES );
    } FC_CAPTURE_AND_RETHROW() }
};

} } // bts::blockchain

FC_REFLECT( bts::blockchain::delegate_config,
        (network_min_connection_count)
        (block_max_transaction_count)
        (block_max_size)
        (block_max_production_time)
        (transaction_max_size)
        (transaction_canonical_signatures_required)
        (transaction_min_fee)
        (transaction_blacklist)
        (operation_blacklist)
        )
<commit_msg>update min net count for dev to 1<commit_after>#pragma once

#include <bts/blockchain/config.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/time.hpp>

#ifdef BTS_TEST_NETWORK
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 0
#else
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 1
#endif

#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE 512 // just a random assumption used to calibrate TRX per SEC
/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )

namespace bts { namespace blockchain {

struct delegate_config
{
    uint32_t            network_min_connection_count = NETWORK_MIN_CONNECTION_COUNT_DEFAULT;

    uint32_t            block_max_transaction_count = -1;
    uint32_t            block_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
    fc::microseconds    block_max_production_time = fc::seconds( 3 );

    uint32_t            transaction_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
    bool                transaction_canonical_signatures_required = false;
    share_type          transaction_min_fee = BTS_BLOCKCHAIN_PRECISION / 10;

    set<transaction_id_type>    transaction_blacklist;
    set<operation_type_enum>    operation_blacklist;

    void validate()const
    { try {
        FC_ASSERT( block_max_size <= BTS_BLOCKCHAIN_MAX_BLOCK_SIZE );
        FC_ASSERT( block_max_production_time.count() >= 0 );
        FC_ASSERT( block_max_production_time.to_seconds() <= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC );
        FC_ASSERT( transaction_max_size <= block_max_size );
        FC_ASSERT( transaction_min_fee >= 0 );
        FC_ASSERT( transaction_min_fee <= BTS_BLOCKCHAIN_MAX_SHARES );
    } FC_CAPTURE_AND_RETHROW() }
};

} } // bts::blockchain

FC_REFLECT( bts::blockchain::delegate_config,
        (network_min_connection_count)
        (block_max_transaction_count)
        (block_max_size)
        (block_max_production_time)
        (transaction_max_size)
        (transaction_canonical_signatures_required)
        (transaction_min_fee)
        (transaction_blacklist)
        (operation_blacklist)
        )
<|endoftext|>


<commit_before>// (c) Mathias Panzenböck
// http://github.com/panzi/mathfun/blob/master/examples/portable_endian.h
//

#pragma once

#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)

#   define __WINDOWS__

#endif

// use standard posix style headers for apple emscripten builds as well since emscripten sdk now ships its own
// libc headers
#if defined(__linux__) || defined(__CYGWIN__) || defined(__EMSCRIPTEN__)

#   include <endian.h>

#elif defined(__APPLE__)

#   include <machine/endian.h>
#   include <libkern/OSByteOrder.h>

#   define htobe16 OSSwapHostToBigInt16
#   define htole16 OSSwapHostToLittleInt16
#   define be16toh OSSwapBigToHostInt16
#   define le16toh OSSwapLittleToHostInt16

#   define htobe32 OSSwapHostToBigInt32
#   define htole32 OSSwapHostToLittleInt32
#   define be32toh OSSwapBigToHostInt32
#   define le32toh OSSwapLittleToHostInt32

#   define htobe64 OSSwapHostToBigInt64
#   define htole64 OSSwapHostToLittleInt64
#   define be64toh OSSwapBigToHostInt64
#   define le64toh OSSwapLittleToHostInt64

/**
#   define __BYTE_ORDER    BYTE_ORDER
#   define __BIG_ENDIAN    BIG_ENDIAN
#   define __LITTLE_ENDIAN LITTLE_ENDIAN
#   define __PDP_ENDIAN    PDP_ENDIAN
**/

#elif defined(__OpenBSD__)|| defined(__FreeBSD__)

#   include <sys/endian.h>

#elif defined(__NetBSD__) || defined(__DragonFly__)

#   define be16toh betoh16
#   define le16toh letoh16

#   define be32toh betoh32
#   define le32toh letoh32

#   define be64toh betoh64
#   define le64toh letoh64

#elif defined(__WINDOWS__)

#   include <winsock2.h>

#   if BYTE_ORDER == LITTLE_ENDIAN

#       define htobe16 htons
#       define htole16(x) (x)
#       define be16toh ntohs
#       define le16toh(x) (x)

#       define htobe32 htonl
#       define htole32(x) (x)
#       define be32toh ntohl
#       define le32toh(x) (x)

#       define htole64(x) (x)
#       define le64toh(x) (x)
#   ifndef __MINGW32__
#       define be64toh ntohll
#       define htobe64 htonll
#   else
#       define be64toh(x) ((((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))
#       define htobe64(x) ((((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
#   endif

#   elif BYTE_ORDER == BIG_ENDIAN

                                /* that would be xbox 360 */
#       define htobe16(x) (x)
#       define htole16(x) __builtin_bswap16(x)
#       define be16toh(x) (x)
#       define le16toh(x) __builtin_bswap16(x)

#       define htobe32(x) (x)
#       define htole32(x) __builtin_bswap32(x)
#       define be32toh(x) (x)
#       define le32toh(x) __builtin_bswap32(x)

#       define htobe64(x) (x)
#       define htole64(x) __builtin_bswap64(x)
#       define be64toh(x) (x)
#       define le64toh(x) __builtin_bswap64(x)

#   else

#       error byte order not supported

#   endif

#   define __BYTE_ORDER    BYTE_ORDER
#   define __BIG_ENDIAN    BIG_ENDIAN
#   define __LITTLE_ENDIAN LITTLE_ENDIAN
#   define __PDP_ENDIAN    PDP_ENDIAN

#else

#   error platform not supported

#endif
<commit_msg>More flexible endian.h handling for *BSD platforms (#119)<commit_after>// (c) Mathias Panzenböck
// http://github.com/panzi/mathfun/blob/master/examples/portable_endian.h
//

#pragma once

#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)

#   define __WINDOWS__

#endif

// use standard posix style headers for apple emscripten builds as well since emscripten sdk now ships its own
// libc headers
#if defined(__linux__) || defined(__CYGWIN__) || defined(__EMSCRIPTEN__)

#   include <endian.h>

#elif defined(__APPLE__)

#   include <machine/endian.h>
#   include <libkern/OSByteOrder.h>

#   define htobe16 OSSwapHostToBigInt16
#   define htole16 OSSwapHostToLittleInt16
#   define be16toh OSSwapBigToHostInt16
#   define le16toh OSSwapLittleToHostInt16

#   define htobe32 OSSwapHostToBigInt32
#   define htole32 OSSwapHostToLittleInt32
#   define be32toh OSSwapBigToHostInt32
#   define le32toh OSSwapLittleToHostInt32

#   define htobe64 OSSwapHostToBigInt64
#   define htole64 OSSwapHostToLittleInt64
#   define be64toh OSSwapBigToHostInt64
#   define le64toh OSSwapLittleToHostInt64

/**
#   define __BYTE_ORDER    BYTE_ORDER
#   define __BIG_ENDIAN    BIG_ENDIAN
#   define __LITTLE_ENDIAN LITTLE_ENDIAN
#   define __PDP_ENDIAN    PDP_ENDIAN
**/

#elif defined(__OpenBSD__)|| defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)

#   if defined __has_include && __has_include (<sys/endian.h>)
#       include <sys/endian.h>
#   elif defined __has_include && __has_include (<endian.h>)
#       include <endian.h>
#   else
#       define be16toh betoh16
#       define le16toh letoh16
#       define be32toh betoh32
#       define le32toh letoh32
#       define be64toh betoh64
#       define le64toh letoh64
#   endif

#elif defined(__WINDOWS__)

#   include <winsock2.h>

#   if BYTE_ORDER == LITTLE_ENDIAN
#       define htobe16 htons
#       define htole16(x) (x)
#       define be16toh ntohs
#       define le16toh(x) (x)

#       define htobe32 htonl
#       define htole32(x) (x)
#       define be32toh ntohl
#       define le32toh(x) (x)

#       define htole64(x) (x)
#       define le64toh(x) (x)
#   ifndef __MINGW32__
#       define be64toh ntohll
#       define htobe64 htonll
#   else
#       define be64toh(x) ((((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))
#       define htobe64(x) ((((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
#   endif

#   elif BYTE_ORDER == BIG_ENDIAN

                                /* that would be xbox 360 */
#       define htobe16(x) (x)
#       define htole16(x) __builtin_bswap16(x)
#       define be16toh(x) (x)
#       define le16toh(x) __builtin_bswap16(x)

#       define htobe32(x) (x)
#       define htole32(x) __builtin_bswap32(x)
#       define be32toh(x) (x)
#       define le32toh(x) __builtin_bswap32(x)

#       define htobe64(x) (x)
#       define htole64(x) __builtin_bswap64(x)
#       define be64toh(x) (x)
#       define le64toh(x) __builtin_bswap64(x)

#   else

#       error byte order not supported

#   endif

#   define __BYTE_ORDER    BYTE_ORDER
#   define __BIG_ENDIAN    BIG_ENDIAN
#   define __LITTLE_ENDIAN LITTLE_ENDIAN
#   define __PDP_ENDIAN    PDP_ENDIAN

#else

#   error platform not supported

#endif
<|endoftext|>


<commit_before>// dllmain.cpp : Defines the entry point for the DLL application.
#include <cstdio>
#include <memory>
#include <string>
#include <locale>
#include "stdafx.h"
#include "supp/timer.h"
#include "core/armor_up.h"
#include "utils/query.h"

using namespace monster_avengers;
std::unique_ptr<int> a;
std::string result;
Timer timer;

extern "C"
{
	__declspec(dllexport) const char *DisplayHelloFromDLL()
	{
		result = std::to_string(timer.Toc());
		return result.c_str();
	}
	__declspec(dllexport) void DoSearch(const wchar_t* text) {
		std::wstring query_text = text;
		setlocale(LC_ALL, "en_US.UTF-8");
		Query query;
		wprintf(L"sizeof(wchar_t): %d\n", sizeof(wchar_t));
		wprintf(L"Get %lc\n", a);

		// ArmorUp armor_up("d:/pf/projects/monster-avengers/dataset/MH4GU");
		// armor_up.Search<SCREEN>("(:weaopn-type ");
	}
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		timer.Tic();
		a.reset(new int(24));
		break;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		a.release();
		break;
	}
	return TRUE;
}

<commit_msg>working version, preliminary.<commit_after>// dllmain.cpp : Defines the entry point for the DLL application.
#include <cstdio>
#include <memory>
#include <string>
#include <locale>
#include "stdafx.h"
#include "supp/timer.h"
#include "core/armor_up.h"
#include "utils/query.h"

using namespace monster_avengers;
std::unique_ptr<int> a;
std::string result;
Timer timer;

extern "C"
{
	__declspec(dllexport) const char *DisplayHelloFromDLL()
	{
		result = std::to_string(timer.Toc());
		return result.c_str();
	}
	__declspec(dllexport) void DoSearch(const wchar_t* text) {
		std::wstring query_text = text;

		Query query;
		CHECK_SUCCESS(Query::Parse(query_text, &query));
		query.DebugPrint();

		ArmorUp armor_up("d:/pf/projects/monster-avengers/dataset/MH4GU");
		armor_up.Summarize();
		armor_up.Search<SCREEN>(query);
	}
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		setlocale(LC_ALL, "en_US.UTF-8");
		timer.Tic();
		a.reset(new int(24));
		break;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		a.release();
		break;
	}
	return TRUE;
}

<|endoftext|>


<commit_before>/// \file TFormulaGradientTests.cxx
///
/// \brief The file contain unit tests which test the clad-based gradient
///        computations.
///
/// \author Vassil Vassilev <vvasilev@cern.ch>
///
/// \date Oct, 2018
///
/*************************************************************************
 * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOTUnitTestSupport.h"

#include <Math/MinimizerOptions.h>
#include <TFormula.h>
#include <TF1.h>
#include <TFitResult.h>

#include "gtest/gtest.h"
#include "gmock/gmock.h"

TEST(TFormulaGradientPar, Sanity)
{
   TFormula f("f", "x*std::sin([0]) - y*std::cos([1])");
   double p[] = {30, 60};
   f.SetParameters(p);
   double x[] = {1, 2};
   TFormula::CladStorage result(2);
   f.GradientPar(x, result);

   ASSERT_FLOAT_EQ(x[0] * std::cos(30), result[0]);
   ASSERT_FLOAT_EQ(-x[1] * -std::sin(60), result[1]);
}

TEST(TFormulaGradientPar, ResultUpsize)
{
   TFormula f("f", "std::sin([1]) - std::cos([0])");
   double p[] = {60, 30};
   f.SetParameters(p);
   TFormula::CladStorage result;
   double x[] = {2, 1};

   ASSERT_TRUE(0 == result.size());
   ROOT_EXPECT_WARNING(f.GradientPar(x, result),
                       "TFormula::GradientPar",
                       "The size of gradient result is 0 but 2 is required. Resizing."
                       );

   ASSERT_FLOAT_EQ(std::cos(30), result[1]);
   ASSERT_FLOAT_EQ(std::sin(60), result[0]);
   ASSERT_TRUE(2 == result.size());
}

TEST(TFormulaGradientPar, ResultDownsize)
{
   TFormula f("f", "std::sin([0])");
   double p[] = {60};
   f.SetParameters(p);
   TFormula::CladStorage result(2);
   double x[] = {1};

   ASSERT_TRUE(2 == result.size());

   ROOT_EXPECT_NODIAG(f.GradientPar(x, result));

   ASSERT_FLOAT_EQ(std::cos(60), result[0]);
   ASSERT_TRUE(2 == result.size());
}

TEST(TFormulaGradientPar, GausCrossCheck)
{
   auto h = new TF1("f1", "gaus");
   // auto h = new TF1("f1", "landau"); -- inheritently does not work. See DIFLAN
   //crystalball, breitwigner, cheb3, bigaus,
   //auto h = new TF1("f1", "");
   double p[] = {3, 1, 2};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(3);
   h->GetFormula()->GradientPar(x, result_clad);

   TFormula::CladStorage result_num(3);
   h->GradientPar(x, result_num.data());

   ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
   ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
   ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}

TEST(TFormulaGradientPar, BreitWignerCrossCheck)
{
   auto h = new TF1("f1", "breitwigner");
   double p[] = {3, 1, 2.1};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(3);
   TFormula* formula = h->GetFormula();
   formula->GradientPar(x, result_clad);
   TFormula::CladStorage result_num(3);
   h->GradientPar(x, result_num.data());

   ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
   ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
   ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}

TEST(TFormulaGradientPar, BreitWignerCrossCheckAccuracyDemo)
{
   auto h = new TF1("f1", "breitwigner");
   double p[] = {3, 1, 2};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(3);
   TFormula* formula = h->GetFormula();
   formula->GradientPar(x, result_clad);
   TFormula::CladStorage result_num(3);
   h->GradientPar(x, result_num.data());

   // This is a classical example why clad is better.
   // The gradient with respect to gamma leads to a cancellation when gamma is
   // set to 2. This is not a problem for clad yielding the correct result of 0
   ASSERT_FLOAT_EQ(0, result_clad[2]);

   // However, that is not the case for the numerical approach where we give
   // a small but non-zero result.
   EXPECT_NEAR(0, result_num[2], /*abs_error*/1e-13);
}

// FIXME: Add more: crystalball, cheb3, bigaus?

TEST(TFormulaGradientPar, GetGradFormula)
{
   TFormula f("f", "gaus");
   double p[] = {3, 1, 2};
   f.SetParameters(p);
   ASSERT_TRUE(f.GenerateGradientPar());
   std::string s = f.GetGradientFormula().Data();
   // Windows does not support posix regex which are necessary here.
#ifndef R__WIN32
   ASSERT_THAT(s, testing::ContainsRegex("void TFormula____id[0-9]*_grad_1"));
#endif // R__WIN32
}

<commit_msg>[clad] Extend test coverage with bigaus function.<commit_after>/// \file TFormulaGradientTests.cxx
///
/// \brief The file contain unit tests which test the clad-based gradient
///        computations.
///
/// \author Vassil Vassilev <vvasilev@cern.ch>
///
/// \date Oct, 2018
///
/*************************************************************************
 * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOTUnitTestSupport.h"

#include <Math/MinimizerOptions.h>
#include <TFormula.h>
#include <TF1.h>
#include <TF2.h>
#include <TFitResult.h>

#include "gtest/gtest.h"
#include "gmock/gmock.h"

TEST(TFormulaGradientPar, Sanity)
{
   TFormula f("f", "x*std::sin([0]) - y*std::cos([1])");
   double p[] = {30, 60};
   f.SetParameters(p);
   double x[] = {1, 2};
   TFormula::CladStorage result(2);
   f.GradientPar(x, result);

   ASSERT_FLOAT_EQ(x[0] * std::cos(30), result[0]);
   ASSERT_FLOAT_EQ(-x[1] * -std::sin(60), result[1]);
}

TEST(TFormulaGradientPar, ResultUpsize)
{
   TFormula f("f", "std::sin([1]) - std::cos([0])");
   double p[] = {60, 30};
   f.SetParameters(p);
   TFormula::CladStorage result;
   double x[] = {2, 1};

   ASSERT_TRUE(0 == result.size());
   ROOT_EXPECT_WARNING(f.GradientPar(x, result),
                       "TFormula::GradientPar",
                       "The size of gradient result is 0 but 2 is required. Resizing."
                       );

   ASSERT_FLOAT_EQ(std::cos(30), result[1]);
   ASSERT_FLOAT_EQ(std::sin(60), result[0]);
   ASSERT_TRUE(2 == result.size());
}

TEST(TFormulaGradientPar, ResultDownsize)
{
   TFormula f("f", "std::sin([0])");
   double p[] = {60};
   f.SetParameters(p);
   TFormula::CladStorage result(2);
   double x[] = {1};

   ASSERT_TRUE(2 == result.size());

   ROOT_EXPECT_NODIAG(f.GradientPar(x, result));

   ASSERT_FLOAT_EQ(std::cos(60), result[0]);
   ASSERT_TRUE(2 == result.size());
}

TEST(TFormulaGradientPar, GausCrossCheck)
{
   auto h = new TF1("f1", "gaus");
   // auto h = new TF1("f1", "landau"); -- inheritently does not work. See DIFLAN
   //crystalball, breitwigner, cheb3, bigaus,
   //auto h = new TF1("f1", "");
   double p[] = {3, 1, 2};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(3);
   h->GetFormula()->GradientPar(x, result_clad);

   TFormula::CladStorage result_num(3);
   h->GradientPar(x, result_num.data());

   ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
   ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
   ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}

TEST(TFormulaGradientPar, BreitWignerCrossCheck)
{
   auto h = new TF1("f1", "breitwigner");
   double p[] = {3, 1, 2.1};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(3);
   TFormula* formula = h->GetFormula();
   formula->GradientPar(x, result_clad);
   TFormula::CladStorage result_num(3);
   h->GradientPar(x, result_num.data());

   ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
   ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
   ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}

TEST(TFormulaGradientPar, BreitWignerCrossCheckAccuracyDemo)
{
   auto h = new TF1("f1", "breitwigner");
   double p[] = {3, 1, 2};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(3);
   TFormula* formula = h->GetFormula();
   formula->GradientPar(x, result_clad);
   TFormula::CladStorage result_num(3);
   h->GradientPar(x, result_num.data());

   // This is a classical example why clad is better.
   // The gradient with respect to gamma leads to a cancellation when gamma is
   // set to 2. This is not a problem for clad yielding the correct result of 0
   ASSERT_FLOAT_EQ(0, result_clad[2]);

   // However, that is not the case for the numerical approach where we give
   // a small but non-zero result.
   EXPECT_NEAR(0, result_num[2], /*abs_error*/1e-13);
}

TEST(TFormulaGradientPar, BigausCrossCheck)
{
   auto h = new TF2("f1", "bigaus");
   const unsigned len = 6;
   double p[] = {/*Constant=*/1,/*MeanX=*/0,/*SigmaX=*/1,/*MeanY=*/1,/*SigmaY=*/2,/*Rho=*/0.};
   h->SetParameters(p);
   double x[] = {0};
   TFormula::CladStorage result_clad(len);
   TFormula* formula = h->GetFormula();
   formula->GradientPar(x, result_clad);
   TFormula::CladStorage result_num(len);
   h->GradientPar(x, result_num.data());

   for (unsigned i = 0; i < len; ++i)
     ASSERT_FLOAT_EQ(result_num[i], result_clad[i]);
}

// FIXME: Add more: crystalball, cheb3?

TEST(TFormulaGradientPar, GetGradFormula)
{
   TFormula f("f", "gaus");
   double p[] = {3, 1, 2};
   f.SetParameters(p);
   ASSERT_TRUE(f.GenerateGradientPar());
   std::string s = f.GetGradientFormula().Data();
   // Windows does not support posix regex which are necessary here.
#ifndef R__WIN32
   ASSERT_THAT(s, testing::ContainsRegex("void TFormula____id[0-9]*_grad_1"));
#endif // R__WIN32
}

<|endoftext|>


<commit_before>// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <addrman.h>
#include <blockencodings.h>
#include <chain.h>
#include <coins.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <net.h>
#include <primitives/block.h>
#include <protocol.h>
#include <pubkey.h>
#include <script/script.h>
#include <streams.h>
#include <undo.h>
#include <version.h>

#include <stdint.h>
#include <unistd.h>

#include <algorithm>
#include <memory>
#include <vector>

const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;

enum TEST_ID {
    CBLOCK_DESERIALIZE=0,
    CTRANSACTION_DESERIALIZE,
    CBLOCKLOCATOR_DESERIALIZE,
    CBLOCKMERKLEROOT,
    CADDRMAN_DESERIALIZE,
    CBLOCKHEADER_DESERIALIZE,
    CBANENTRY_DESERIALIZE,
    CTXUNDO_DESERIALIZE,
    CBLOCKUNDO_DESERIALIZE,
    CCOINS_DESERIALIZE,
    CNETADDR_DESERIALIZE,
    CSERVICE_DESERIALIZE,
    CMESSAGEHEADER_DESERIALIZE,
    CADDRESS_DESERIALIZE,
    CINV_DESERIALIZE,
    CBLOOMFILTER_DESERIALIZE,
    CDISKBLOCKINDEX_DESERIALIZE,
    CTXOUTCOMPRESSOR_DESERIALIZE,
    BLOCKTRANSACTIONS_DESERIALIZE,
    BLOCKTRANSACTIONSREQUEST_DESERIALIZE,
    TEST_ID_END
};

static bool read_stdin(std::vector<uint8_t> &data) {
    uint8_t buffer[1024];
    ssize_t length=0;
    while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
        data.insert(data.end(), buffer, buffer+length);

        if (data.size() > (1<<20)) return false;
    }
    return length==0;
}

static int test_one_input(std::vector<uint8_t> buffer) {
    if (buffer.size() < sizeof(uint32_t)) return 0;

    uint32_t test_id = 0xffffffff;
    memcpy(&test_id, buffer.data(), sizeof(uint32_t));
    buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));

    if (test_id >= TEST_ID_END) return 0;

    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
    try {
        int nVersion;
        ds >> nVersion;
        ds.SetVersion(nVersion);
    } catch (const std::ios_base::failure& e) {
        return 0;
    }

    switch(test_id) {
        case CBLOCK_DESERIALIZE:
        {
            try
            {
                CBlock block;
                ds >> block;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CTRANSACTION_DESERIALIZE:
        {
            try
            {
                CTransaction tx(deserialize, ds);
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CBLOCKLOCATOR_DESERIALIZE:
        {
            try
            {
                CBlockLocator bl;
                ds >> bl;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CBLOCKMERKLEROOT:
        {
            try
            {
                CBlock block;
                ds >> block;
                bool mutated;
                BlockMerkleRoot(block, &mutated);
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CADDRMAN_DESERIALIZE:
        {
            try
            {
                CAddrMan am;
                ds >> am;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CBLOCKHEADER_DESERIALIZE:
        {
            try
            {
                CBlockHeader bh;
                ds >> bh;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CBANENTRY_DESERIALIZE:
        {
            try
            {
                CBanEntry be;
                ds >> be;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CTXUNDO_DESERIALIZE:
        {
            try
            {
                CTxUndo tu;
                ds >> tu;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CBLOCKUNDO_DESERIALIZE:
        {
            try
            {
                CBlockUndo bu;
                ds >> bu;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CCOINS_DESERIALIZE:
        {
            try
            {
                Coin coin;
                ds >> coin;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CNETADDR_DESERIALIZE:
        {
            try
            {
                CNetAddr na;
                ds >> na;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CSERVICE_DESERIALIZE:
        {
            try
            {
                CService s;
                ds >> s;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CMESSAGEHEADER_DESERIALIZE:
        {
            CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
            try
            {
                CMessageHeader mh(pchMessageStart);
                ds >> mh;
                if (!mh.IsValid(pchMessageStart)) {return 0;}
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CADDRESS_DESERIALIZE:
        {
            try
            {
                CAddress a;
                ds >> a;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CINV_DESERIALIZE:
        {
            try
            {
                CInv i;
                ds >> i;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CBLOOMFILTER_DESERIALIZE:
        {
            try
            {
                CBloomFilter bf;
                ds >> bf;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CDISKBLOCKINDEX_DESERIALIZE:
        {
            try
            {
                CDiskBlockIndex dbi;
                ds >> dbi;
            } catch (const std::ios_base::failure& e) {return 0;}
            break;
        }
        case CTXOUTCOMPRESSOR_DESERIALIZE:
        {
            CTxOut to;
            CTxOutCompressor toc(to);
            try
            {
                ds >> toc;
            } catch (const std::ios_base::failure& e) {return 0;}

            break;
        }
        case BLOCKTRANSACTIONS_DESERIALIZE:
        {
            try
            {
                BlockTransactions bt;
                ds >> bt;
            } catch (const std::ios_base::failure& e) {return 0;}

            break;
        }
        case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:
        {
            try
            {
                BlockTransactionsRequest btr;
                ds >> btr;
            } catch (const std::ios_base::failure& e) {return 0;}

            break;
        }
        default:
            return 0;
    }
    return 0;
}

static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
void initialize() {
    globalVerifyHandle = MakeUnique<ECCVerifyHandle>();
}

// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    test_one_input(std::vector<uint8_t>(data, data + size));
    return 0;
}

// This function is used by libFuzzer
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
    initialize();
    return 0;
}

// Disabled under WIN32 due to clash with Cygwin's WinMain.
#ifndef WIN32
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
// the main(...) function.
__attribute__((weak))
#endif
int main(int argc, char **argv)
{
    initialize();
#ifdef __AFL_INIT
    // Enable AFL deferred forkserver mode. Requires compilation using
    // afl-clang-fast++. See fuzzing.md for details.
    __AFL_INIT();
#endif

#ifdef __AFL_LOOP
    // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
    // See fuzzing.md for details.
    int ret = 0;
    while (__AFL_LOOP(1000)) {
        std::vector<uint8_t> buffer;
        if (!read_stdin(buffer)) {
            continue;
        }
        ret = test_one_input(buffer);
    }
    return ret;
#else
    std::vector<uint8_t> buffer;
    if (!read_stdin(buffer)) {
        return 0;
    }
    return test_one_input(buffer);
#endif
}
<commit_msg>[test] fuzz: make test_one_input return void<commit_after>// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <addrman.h>
#include <blockencodings.h>
#include <chain.h>
#include <coins.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <net.h>
#include <primitives/block.h>
#include <protocol.h>
#include <pubkey.h>
#include <script/script.h>
#include <streams.h>
#include <undo.h>
#include <version.h>

#include <stdint.h>
#include <unistd.h>

#include <algorithm>
#include <memory>
#include <vector>

const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;

enum TEST_ID {
    CBLOCK_DESERIALIZE=0,
    CTRANSACTION_DESERIALIZE,
    CBLOCKLOCATOR_DESERIALIZE,
    CBLOCKMERKLEROOT,
    CADDRMAN_DESERIALIZE,
    CBLOCKHEADER_DESERIALIZE,
    CBANENTRY_DESERIALIZE,
    CTXUNDO_DESERIALIZE,
    CBLOCKUNDO_DESERIALIZE,
    CCOINS_DESERIALIZE,
    CNETADDR_DESERIALIZE,
    CSERVICE_DESERIALIZE,
    CMESSAGEHEADER_DESERIALIZE,
    CADDRESS_DESERIALIZE,
    CINV_DESERIALIZE,
    CBLOOMFILTER_DESERIALIZE,
    CDISKBLOCKINDEX_DESERIALIZE,
    CTXOUTCOMPRESSOR_DESERIALIZE,
    BLOCKTRANSACTIONS_DESERIALIZE,
    BLOCKTRANSACTIONSREQUEST_DESERIALIZE,
    TEST_ID_END
};

static bool read_stdin(std::vector<uint8_t>& data)
{
    uint8_t buffer[1024];
    ssize_t length = 0;
    while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
        data.insert(data.end(), buffer, buffer + length);

        if (data.size() > (1 << 20)) return false;
    }
    return length == 0;
}

void test_one_input(std::vector<uint8_t> buffer)
{
    if (buffer.size() < sizeof(uint32_t)) return;

    uint32_t test_id = 0xffffffff;
    memcpy(&test_id, buffer.data(), sizeof(uint32_t));
    buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));

    if (test_id >= TEST_ID_END) return;

    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
    try {
        int nVersion;
        ds >> nVersion;
        ds.SetVersion(nVersion);
    } catch (const std::ios_base::failure& e) {
        return;
    }

    switch(test_id) {
        case CBLOCK_DESERIALIZE:
        {
            try
            {
                CBlock block;
                ds >> block;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CTRANSACTION_DESERIALIZE:
        {
            try
            {
                CTransaction tx(deserialize, ds);
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CBLOCKLOCATOR_DESERIALIZE:
        {
            try
            {
                CBlockLocator bl;
                ds >> bl;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CBLOCKMERKLEROOT:
        {
            try
            {
                CBlock block;
                ds >> block;
                bool mutated;
                BlockMerkleRoot(block, &mutated);
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CADDRMAN_DESERIALIZE:
        {
            try
            {
                CAddrMan am;
                ds >> am;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CBLOCKHEADER_DESERIALIZE:
        {
            try
            {
                CBlockHeader bh;
                ds >> bh;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CBANENTRY_DESERIALIZE:
        {
            try
            {
                CBanEntry be;
                ds >> be;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CTXUNDO_DESERIALIZE:
        {
            try
            {
                CTxUndo tu;
                ds >> tu;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CBLOCKUNDO_DESERIALIZE:
        {
            try
            {
                CBlockUndo bu;
                ds >> bu;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CCOINS_DESERIALIZE:
        {
            try
            {
                Coin coin;
                ds >> coin;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CNETADDR_DESERIALIZE:
        {
            try
            {
                CNetAddr na;
                ds >> na;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CSERVICE_DESERIALIZE:
        {
            try
            {
                CService s;
                ds >> s;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CMESSAGEHEADER_DESERIALIZE:
        {
            CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
            try
            {
                CMessageHeader mh(pchMessageStart);
                ds >> mh;
                if (!mh.IsValid(pchMessageStart)) {return;}
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CADDRESS_DESERIALIZE:
        {
            try
            {
                CAddress a;
                ds >> a;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CINV_DESERIALIZE:
        {
            try
            {
                CInv i;
                ds >> i;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CBLOOMFILTER_DESERIALIZE:
        {
            try
            {
                CBloomFilter bf;
                ds >> bf;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CDISKBLOCKINDEX_DESERIALIZE:
        {
            try
            {
                CDiskBlockIndex dbi;
                ds >> dbi;
            } catch (const std::ios_base::failure& e) {return;}
            break;
        }
        case CTXOUTCOMPRESSOR_DESERIALIZE:
        {
            CTxOut to;
            CTxOutCompressor toc(to);
            try
            {
                ds >> toc;
            } catch (const std::ios_base::failure& e) {return;}

            break;
        }
        case BLOCKTRANSACTIONS_DESERIALIZE:
        {
            try
            {
                BlockTransactions bt;
                ds >> bt;
            } catch (const std::ios_base::failure& e) {return;}

            break;
        }
        case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:
        {
            try
            {
                BlockTransactionsRequest btr;
                ds >> btr;
            } catch (const std::ios_base::failure& e) {return;}

            break;
        }
        default:
            return;
    }
    return;
}

void initialize()
{
    const static auto verify_handle = MakeUnique<ECCVerifyHandle>();
}

// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
    test_one_input(std::vector<uint8_t>(data, data + size));
    return 0;
}

// This function is used by libFuzzer
extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv)
{
    initialize();
    return 0;
}

// Disabled under WIN32 due to clash with Cygwin's WinMain.
#ifndef WIN32
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
// the main(...) function.
__attribute__((weak))
#endif
int main(int argc, char **argv)
{
    initialize();
#ifdef __AFL_INIT
    // Enable AFL deferred forkserver mode. Requires compilation using
    // afl-clang-fast++. See fuzzing.md for details.
    __AFL_INIT();
#endif

#ifdef __AFL_LOOP
    // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
    // See fuzzing.md for details.
    while (__AFL_LOOP(1000)) {
        std::vector<uint8_t> buffer;
        if (!read_stdin(buffer)) {
            continue;
        }
        test_one_input(buffer);
    }
#else
    std::vector<uint8_t> buffer;
    if (!read_stdin(buffer)) {
        return 0;
    }
    test_one_input(buffer);
#endif
}
<|endoftext|>