<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XOPERATION_HPP
#define XOPERATION_HPP

#include <functional>
#include <algorithm>
#include <type_traits>

#include "xfunction.hpp"
#include "xscalar.hpp"

namespace xt
{

    /***********
     * helpers *
     ***********/

    template <class T>
    struct identity
    {
        using result_type = T;

        constexpr T operator()(const T& t) const noexcept
        {
            return +t;
        }
    };

    template <class T>
    struct conditional_ternary
    {
        using result_type = T;

        constexpr result_type operator()(const T& t1, const T& t2, const T& t3) const noexcept
        {
            return t1 ? t2 : t3;
        }
    };

    template <class T>
    struct conditional
    {
        using result_type = bool;

        constexpr result_type operator()(const T t1, const T t2) const noexcept
        {
            return t1 < t2;
        }
    };

    namespace detail
    {
        template <template <class...> class F, class... E>
        inline auto make_xfunction(const E&... e) noexcept
        {
            using functor_type = F<common_value_type<E...>>;
            using result_type = typename functor_type::result_type;
            using type = xfunction<functor_type, result_type, get_xexpression_type<E>...>;
            return type(functor_type(), get_xexpression(e)...);
        }

        template <template <class...> class F, class... E>
        using get_xfunction_type = std::enable_if_t<has_xexpression<E...>::value,
                                                    xfunction<F<common_value_type<E...>>,
                                                              typename F<common_value_type<E...>>::result_type,
                                                              get_xexpression_type<E>...>>;
    }

    /*************
     * operators *
     *************/

    template <class E>
    inline auto operator+(const xexpression<E>& e) noexcept
    {
        return detail::make_xfunction<identity>(e.derived_cast());
    }

    template <class E>
    inline auto operator-(const xexpression<E>& e) noexcept
    {
        return detail::make_xfunction<std::negate>(e.derived_cast());
    }

    template <class E1, class E2>
    inline auto operator+(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::plus, E1, E2>
    {
        return detail::make_xfunction<std::plus>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator-(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::minus, E1, E2>
    {
        return detail::make_xfunction<std::minus>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator*(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::multiplies, E1, E2>
    {
        return detail::make_xfunction<std::multiplies>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator/(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::divides, E1, E2>
    {
        return detail::make_xfunction<std::divides>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator||(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::logical_or, E1, E2>
    {
        return detail::make_xfunction<std::logical_or>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator&&(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::logical_and, E1, E2>
    {
        return detail::make_xfunction<std::logical_and>(e1, e2);
    }

    template <class E>
    inline auto operator!(const E& e) noexcept
        -> detail::get_xfunction_type<std::logical_not, E>
    {
        return detail::make_xfunction<std::logical_not>(e);
    }

    template <class E1, class E2>
    inline auto operator<(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::less, E1, E2>
    {
        return detail::make_xfunction<std::less>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator<=(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::less_equal, E1, E2>
    {
        return detail::make_xfunction<std::less_equal>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator>(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::greater, E1, E2>
    {
        return detail::make_xfunction<std::greater>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator>=(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::greater_equal, E1, E2>
    {
        return detail::make_xfunction<std::greater_equal>(e1, e2);
    }

    template <class E1, class E2>
    inline auto equal_to(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::equal_to, E1, E2>
    {
        return detail::make_xfunction<std::equal_to>(e1, e2);
    }

    template <class E1, class E2, class E3>
    inline auto where(const E1& e1, const E2& e2, const E3& e3) noexcept
        -> detail::get_xfunction_type<conditional_ternary, E1, E2, E3>
    {
         return detail::make_xfunction<conditional_ternary>(e1, e2, e3);
    }

    template <class E1>
    inline auto any(const xexpression<E1>& e1)
        -> bool
    {
        const E1& e1_d = e1.derived_cast();
        return std::any_of(e1_d.storage_begin(), e1_d.storage_end(),
                           [](const typename E1::value_type& el) { return el; });
    }

    template <class E1>
    inline auto all(const xexpression<E1>& e1)
        -> bool
    {
        const E1& e1_d = e1.derived_cast();
        return std::all_of(e1_d.storage_begin(), e1_d.storage_end(),
                           [](const typename E1::value_type& el) { return el; });
    }
}

#endif

<commit_msg>clean up<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XOPERATION_HPP
#define XOPERATION_HPP

#include <functional>
#include <algorithm>
#include <type_traits>

#include "xfunction.hpp"
#include "xscalar.hpp"

namespace xt
{

    /***********
     * helpers *
     ***********/

    namespace detail
    {
        template <class T>
        struct identity
        {
            using result_type = T;

            constexpr T operator()(const T& t) const noexcept
            {
                return +t;
            }
        };

        template <class T>
        struct conditional_ternary
        {
            using result_type = T;

            constexpr result_type operator()(const T& t1, const T& t2, const T& t3) const noexcept
            {
                return t1 ? t2 : t3;
            }
        };

        template <template <class...> class F, class... E>
        inline auto make_xfunction(const E&... e) noexcept
        {
            using functor_type = F<common_value_type<E...>>;
            using result_type = typename functor_type::result_type;
            using type = xfunction<functor_type, result_type, get_xexpression_type<E>...>;
            return type(functor_type(), get_xexpression(e)...);
        }

        template <template <class...> class F, class... E>
        using get_xfunction_type = std::enable_if_t<has_xexpression<E...>::value,
                                                    xfunction<F<common_value_type<E...>>,
                                                              typename F<common_value_type<E...>>::result_type,
                                                              get_xexpression_type<E>...>>;
    }

    /*************
     * operators *
     *************/

    template <class E>
    inline auto operator+(const xexpression<E>& e) noexcept
    {
        return detail::make_xfunction<detail::identity>(e.derived_cast());
    }

    template <class E>
    inline auto operator-(const xexpression<E>& e) noexcept
    {
        return detail::make_xfunction<std::negate>(e.derived_cast());
    }

    template <class E1, class E2>
    inline auto operator+(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::plus, E1, E2>
    {
        return detail::make_xfunction<std::plus>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator-(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::minus, E1, E2>
    {
        return detail::make_xfunction<std::minus>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator*(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::multiplies, E1, E2>
    {
        return detail::make_xfunction<std::multiplies>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator/(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::divides, E1, E2>
    {
        return detail::make_xfunction<std::divides>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator||(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::logical_or, E1, E2>
    {
        return detail::make_xfunction<std::logical_or>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator&&(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::logical_and, E1, E2>
    {
        return detail::make_xfunction<std::logical_and>(e1, e2);
    }

    template <class E>
    inline auto operator!(const E& e) noexcept
        -> detail::get_xfunction_type<std::logical_not, E>
    {
        return detail::make_xfunction<std::logical_not>(e);
    }

    template <class E1, class E2>
    inline auto operator<(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::less, E1, E2>
    {
        return detail::make_xfunction<std::less>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator<=(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::less_equal, E1, E2>
    {
        return detail::make_xfunction<std::less_equal>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator>(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::greater, E1, E2>
    {
        return detail::make_xfunction<std::greater>(e1, e2);
    }

    template <class E1, class E2>
    inline auto operator>=(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::greater_equal, E1, E2>
    {
        return detail::make_xfunction<std::greater_equal>(e1, e2);
    }

    template <class E1, class E2>
    inline auto equal_to(const E1& e1, const E2& e2) noexcept
        -> detail::get_xfunction_type<std::equal_to, E1, E2>
    {
        return detail::make_xfunction<std::equal_to>(e1, e2);
    }

    template <class E1, class E2, class E3>
    inline auto where(const E1& e1, const E2& e2, const E3& e3) noexcept
        -> detail::get_xfunction_type<detail::conditional_ternary, E1, E2, E3>
    {
         return detail::make_xfunction<detail::conditional_ternary>(e1, e2, e3);
    }

    template <class E1>
    inline auto any(const xexpression<E1>& e1)
        -> bool
    {
        const E1& e1_d = e1.derived_cast();
        return std::any_of(e1_d.storage_begin(), e1_d.storage_end(),
                           [](const typename E1::value_type& el) { return el; });
    }

    template <class E1>
    inline auto all(const xexpression<E1>& e1)
        -> bool
    {
        const E1& e1_d = e1.derived_cast();
        return std::all_of(e1_d.storage_begin(), e1_d.storage_end(),
                           [](const typename E1::value_type& el) { return el; });
    }
}

#endif

<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeMathPch.h"

namespace Js
{
    // These implementations need to be compiled with /arch:sse2
#define DivImpl(type) template<> type AsmJsMath::Div(type aLeft, type aRight) { return aLeft / aRight; }
#define MulImpl(type) template<> type AsmJsMath::Mul(type aLeft, type aRight) { return aLeft * aRight; }
#define DivMulImpl(type) DivImpl(type) MulImpl(type)

    DivMulImpl(float)
    DivMulImpl(double)
    DivMulImpl(int64)
    DivMulImpl(uint64)
    MulImpl(int32)
    MulImpl(uint32)

    template<>
    int32 AsmJsMath::Div<int32>(int32 aLeft, int32 aRight)
    {
        return aRight == 0 ? 0 : (aLeft == (1 << 31) && aRight == -1) ? aLeft : aLeft / aRight;
    }

    template<>
    uint32 AsmJsMath::Div<uint32>(uint32 aLeft, uint32 aRight)
    {
        return aRight == 0 ? 0 : aLeft / aRight;
    }
}
<commit_msg>[1.4>master] Force to not inline asm.js div for double on x86 to force to use sse2<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeMathPch.h"

namespace Js
{
    // These implementations need to be compiled with /arch:sse2
#define DivImpl(type, noinline) template<> noinline type AsmJsMath::Div(type aLeft, type aRight) { return aLeft / aRight; }
#define MulImpl(type, noinline) template<> noinline type AsmJsMath::Mul(type aLeft, type aRight) { return aLeft * aRight; }
#define DivMulImpl(type, noinline) DivImpl(type, noinline) MulImpl(type, noinline)

#if _M_IX86
#define DB_NOINLINE _NOINLINE
#else
#define DB_NOINLINE
#endif
    DivMulImpl(double, DB_NOINLINE)
    DivMulImpl(float,)
    DivMulImpl(int64,)
    DivMulImpl(uint64,)
    MulImpl(int32,)
    MulImpl(uint32,)

    template<>
    int32 AsmJsMath::Div<int32>(int32 aLeft, int32 aRight)
    {
        return aRight == 0 ? 0 : (aLeft == (1 << 31) && aRight == -1) ? aLeft : aLeft / aRight;
    }

    template<>
    uint32 AsmJsMath::Div<uint32>(uint32 aLeft, uint32 aRight)
    {
        return aRight == 0 ? 0 : aLeft / aRight;
    }
}
<|endoftext|>


<commit_before>#include <node.h>
#include <nan.h>
#include <stdlib.h>

#ifdef _MSC_VER
// Windows header
# include <Windows.h>
#else
// Unix header

# include <dirent.h>
# include <sys/stat.h>

#endif

using namespace v8;

// Type signature

bool IsCurrentDir(const wchar_t* path);
bool IsCurrentDir(const char* path);

#ifdef _MSC_VER
// Windows system call

bool ReaddirImpl(Local<String>& path, Local<Array>& result) {
    int len = path->Length();
    wchar_t* path_buf = new wchar_t[len + 3];

    int wrote = path->Write((uint16_t*) path_buf);
    if(wrote < 1) {
        goto fail;
    }

    if(path_buf[len - 1] == L'\\') {
        path_buf[len] = L'*';
        path_buf[len + 1] = L'\0';
    } else {
        path_buf[len] = L'\\';
        path_buf[len + 1] = L'*';
        path_buf[len + 2] = L'\0';
    }

    WIN32_FIND_DATAW find_data;
    HANDLE handle = FindFirstFileW(path_buf, &find_data);
    if(handle == INVALID_HANDLE_VALUE) {
        goto fail;
    }

    int index = 0;
    do {
        if(! IsCurrentDir(find_data.cFileName)) {
            Local<String> filename = NanNew<String>((uint16_t*) find_data.cFileName);
            result->Set(NanNew<Number>(index++), filename);
        }
    } while(FindNextFileW(handle, &find_data));

    FindClose(handle);
    delete[] path_buf;
    return true;

fail:
    delete[] path_buf;
    return false;
}

DWORD GetAttr(Local<String>& path) {
    String::Value path_value(path);
    if(*path_value == NULL) {
        return INVALID_FILE_ATTRIBUTES;
    }
    return GetFileAttributesW((const wchar_t*) *path_value);
}

bool IsSymbolicLinkImpl(Local<String>& path) {
    DWORD attr = GetAttr(path);
    if(attr == INVALID_FILE_ATTRIBUTES) {
        return false;
    }
    return attr & FILE_ATTRIBUTE_REPARSE_POINT;
}

bool ExistsImpl(Local<String>& path) {
    return GetAttr(path) != INVALID_FILE_ATTRIBUTES;
}

#else

// Unix system call
bool ReaddirImpl(Local<String>& path, Local<Array>& result) {
    String::Utf8Value path_value(path);
    if(*path_value == NULL) {
        return false;
    }

    struct dirent** namelist;
    int size = scandir(*path_value, &namelist, NULL, alphasort);
    if(size < 0) {
        return false;
    }

    int index = 0;
    for(int i = 0; i < size; i++) {
        if(IsCurrentDir(namelist[i]->d_name) == false) {
            Local<String> filename = NanNew<String>(namelist[i]->d_name);
            result->Set(NanNew<Number>(index++), filename);
        }
        free(namelist[i]);
    }

    free(namelist);
    return true;
}

bool IsSymbolicLinkImpl(Local<String>& path) {
    String::Utf8Value path_value(path);
    if(*path_value == NULL) {
        return false;
    }

    struct stat st;
    int err = lstat(*path_value, &st);
    if(err) {
        return false;
    }

    return st.st_mode & S_IFLNK;
}

bool ExistsImpl(Local<String>& path) {
    String::Utf8Value path_value(path);
    if(*path_value == NULL) {
        return false;
    }

    struct stat st;
    return stat(*path_value, &st) == 0;
}

#endif

bool IsCurrentDir(const wchar_t* name) {
    if(name[0] == L'.') {
        return name[1] == L'\0' || (name[1] == L'.' && name[2] == L'\0');
    }
    return false;
}

bool IsCurrentDir(const char* name) {
    if(name[0] == '.') {
        return name[1] == '\0' || (name[1] == '.' && name[2] == '\0');
    }
    return false;
}

NAN_METHOD(Readdir) {
    NanScope();
    assert(args.Length() == 1);
    assert(args[0]->IsString());

    Local<Array> result = NanNew<Array>();
    Local<String> path = args[0]->ToString();
    bool success = ReaddirImpl(path, result);

    if(success) {
        NanReturnValue(result);
    } else {
        NanReturnValue(NanNull());
    }
}

NAN_METHOD(IsSymbolicLink) {
    NanScope();
    assert(args.Length() == 1);
    assert(args[0]->IsString());

    Local<String> path = args[0]->ToString();
    bool is_sym = IsSymbolicLinkImpl(path);
    NanReturnValue(is_sym ? NanTrue() : NanFalse());
}

NAN_METHOD(Exists) {
    NanScope();
    assert(args.Length() == 1);
    assert(args[0]->IsString());

    Local<String> path = args[0]->ToString();
    bool exists = ExistsImpl(path);
    NanReturnValue(exists ? NanTrue() : NanFalse());
}

void Init(Handle<Object> exports) {
    NanScope();
    NODE_SET_METHOD(exports, "readdirSyncSafe", Readdir);
    NODE_SET_METHOD(exports, "isSymbolicLinkSync", IsSymbolicLink);
    NODE_SET_METHOD(exports, "existsSync", Exists);
}

NODE_MODULE(speedup, Init)
<commit_msg>Refactoring<commit_after>#include <node.h>
#include <nan.h>
#include <stdlib.h>

#ifdef _MSC_VER
// Windows header
# include <Windows.h>
#else
// Unix header
# include <dirent.h>
# include <sys/stat.h>
#endif

using namespace v8;

#ifdef _MSC_VER
// Windows system call

bool IsCurrentDir(const wchar_t* name) {
    if(name[0] == L'.') {
        return name[1] == L'\0' || (name[1] == L'.' && name[2] == L'\0');
    }
    return false;
}

bool ReaddirImpl(Local<String>& path, Local<Array>& result) {
    int len = path->Length();
    wchar_t* path_buf = new wchar_t[len + 3];

    int wrote = path->Write((uint16_t*) path_buf);
    if(wrote < 1) {
        goto fail;
    }

    if(path_buf[len - 1] == L'\\') {
        path_buf[len] = L'*';
        path_buf[len + 1] = L'\0';
    } else {
        path_buf[len] = L'\\';
        path_buf[len + 1] = L'*';
        path_buf[len + 2] = L'\0';
    }

    WIN32_FIND_DATAW find_data;
    HANDLE handle = FindFirstFileW(path_buf, &find_data);
    if(handle == INVALID_HANDLE_VALUE) {
        goto fail;
    }

    int index = 0;
    do {
        if(! IsCurrentDir(find_data.cFileName)) {
            Local<String> filename = NanNew((uint16_t*) find_data.cFileName);
            result->Set(index++, filename);
        }
    } while(FindNextFileW(handle, &find_data));

    FindClose(handle);
    delete[] path_buf;
    return true;

fail:
    delete[] path_buf;
    return false;
}

DWORD GetAttr(Local<String>& path) {
    String::Value path_value(path);
    if(*path_value == NULL) {
        return INVALID_FILE_ATTRIBUTES;
    }
    return GetFileAttributesW((const wchar_t*) *path_value);
}

bool IsSymbolicLinkImpl(Local<String>& path) {
    DWORD attr = GetAttr(path);
    if(attr == INVALID_FILE_ATTRIBUTES) {
        return false;
    }
    return attr & FILE_ATTRIBUTE_REPARSE_POINT;
}

bool ExistsImpl(Local<String>& path) {
    return GetAttr(path) != INVALID_FILE_ATTRIBUTES;
}

#else
// Unix system call

bool IsCurrentDir(const char* name) {
    if(name[0] == '.') {
        return name[1] == '\0' || (name[1] == '.' && name[2] == '\0');
    }
    return false;
}

bool ReaddirImpl(Local<String>& path, Local<Array>& result) {
    String::Utf8Value path_value(path);
    if(*path_value == NULL) {
        return false;
    }

    struct dirent** namelist;
    int size = scandir(*path_value, &namelist, NULL, alphasort);
    if(size < 0) {
        return false;
    }

    int index = 0;
    for(int i = 0; i < size; i++) {
        if(IsCurrentDir(namelist[i]->d_name) == false) {
            Local<String> filename = NanNew(namelist[i]->d_name);
            result->Set(index++, filename);
        }
        free(namelist[i]);
    }

    free(namelist);
    return true;
}

bool IsSymbolicLinkImpl(Local<String>& path) {
    String::Utf8Value path_value(path);
    if(*path_value == NULL) {
        return false;
    }

    struct stat st;
    int err = lstat(*path_value, &st);
    if(err) {
        return false;
    }

    return st.st_mode & S_IFLNK;
}

bool ExistsImpl(Local<String>& path) {
    String::Utf8Value path_value(path);
    if(*path_value == NULL) {
        return false;
    }

    struct stat st;
    return stat(*path_value, &st) == 0;
}

#endif

NAN_METHOD(Readdir) {
    NanScope();
    assert(args.Length() == 1);
    assert(args[0]->IsString());

    Local<Array> result = NanNew<Array>();
    Local<String> path = args[0]->ToString();
    bool success = ReaddirImpl(path, result);

    if(success) {
        NanReturnValue(result);
    } else {
        NanReturnValue(NanNull());
    }
}

NAN_METHOD(IsSymbolicLink) {
    NanScope();
    assert(args.Length() == 1);
    assert(args[0]->IsString());

    Local<String> path = args[0]->ToString();
    bool is_sym = IsSymbolicLinkImpl(path);
    NanReturnValue(is_sym ? NanTrue() : NanFalse());
}

NAN_METHOD(Exists) {
    NanScope();
    assert(args.Length() == 1);
    assert(args[0]->IsString());

    Local<String> path = args[0]->ToString();
    bool exists = ExistsImpl(path);
    NanReturnValue(exists ? NanTrue() : NanFalse());
}

void Init(Handle<Object> exports) {
    NanScope();
    NODE_SET_METHOD(exports, "readdirSyncSafe", Readdir);
    NODE_SET_METHOD(exports, "isSymbolicLinkSync", IsSymbolicLink);
    NODE_SET_METHOD(exports, "existsSync", Exists);
}

NODE_MODULE(speedup, Init)
<|endoftext|>


<commit_before>//===-- Utils.cpp - TransformUtils Infrastructure -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the common initialization infrastructure for the
// TransformUtils library.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils.h"
#include "llvm-c/Initialization.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassRegistry.h"

using namespace llvm;

/// initializeTransformUtils - Initialize all passes in the TransformUtils
/// library.
void llvm::initializeTransformUtils(PassRegistry &Registry) {
  initializeAddDiscriminatorsLegacyPassPass(Registry);
  initializeBreakCriticalEdgesPass(Registry);
  initializeInstNamerPass(Registry);
  initializeLCSSAWrapperPassPass(Registry);
  initializeLibCallsShrinkWrapLegacyPassPass(Registry);
  initializeLoopSimplifyPass(Registry);
  initializeLowerInvokeLegacyPassPass(Registry);
  initializeLowerSwitchPass(Registry);
  initializeNameAnonGlobalLegacyPassPass(Registry);
  initializePromoteLegacyPassPass(Registry);
  initializeStripNonLineTableDebugInfoPass(Registry);
  initializeUnifyFunctionExitNodesPass(Registry);
  initializeInstSimplifierPass(Registry);
  initializeMetaRenamerPass(Registry);
  initializeStripGCRelocatesPass(Registry);
  initializePredicateInfoPrinterLegacyPassPass(Registry);
}

/// LLVMInitializeTransformUtils - C binding for initializeTransformUtilsPasses.
void LLVMInitializeTransformUtils(LLVMPassRegistryRef R) {
  initializeTransformUtils(*unwrap(R));
}

void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM) {
  unwrap(PM)->add(createLowerSwitchPass());
}

void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM) {
  unwrap(PM)->add(createPromoteMemoryToRegisterPass());
}

<commit_msg>[Transforms] Make sure to include the c binding header when defining c binding functions<commit_after>//===-- Utils.cpp - TransformUtils Infrastructure -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the common initialization infrastructure for the
// TransformUtils library.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils.h"
#include "llvm-c/Initialization.h"
#include "llvm-c/Transforms/Scalar.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassRegistry.h"

using namespace llvm;

/// initializeTransformUtils - Initialize all passes in the TransformUtils
/// library.
void llvm::initializeTransformUtils(PassRegistry &Registry) {
  initializeAddDiscriminatorsLegacyPassPass(Registry);
  initializeBreakCriticalEdgesPass(Registry);
  initializeInstNamerPass(Registry);
  initializeLCSSAWrapperPassPass(Registry);
  initializeLibCallsShrinkWrapLegacyPassPass(Registry);
  initializeLoopSimplifyPass(Registry);
  initializeLowerInvokeLegacyPassPass(Registry);
  initializeLowerSwitchPass(Registry);
  initializeNameAnonGlobalLegacyPassPass(Registry);
  initializePromoteLegacyPassPass(Registry);
  initializeStripNonLineTableDebugInfoPass(Registry);
  initializeUnifyFunctionExitNodesPass(Registry);
  initializeInstSimplifierPass(Registry);
  initializeMetaRenamerPass(Registry);
  initializeStripGCRelocatesPass(Registry);
  initializePredicateInfoPrinterLegacyPassPass(Registry);
}

/// LLVMInitializeTransformUtils - C binding for initializeTransformUtilsPasses.
void LLVMInitializeTransformUtils(LLVMPassRegistryRef R) {
  initializeTransformUtils(*unwrap(R));
}

void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM) {
  unwrap(PM)->add(createLowerSwitchPass());
}

void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM) {
  unwrap(PM)->add(createPromoteMemoryToRegisterPass());
}

<|endoftext|>


<commit_before>//===-- TypeSymbolTable.cpp - Implement the TypeSymbolTable class ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TypeSymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//

#include "llvm/TypeSymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/RWMutex.h"
#include "llvm/System/Threading.h"
#include <algorithm>
using namespace llvm;

#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0

static ManagedStatic<sys::SmartRWMutex<true> > TypeSymbolTableLock;

TypeSymbolTable::~TypeSymbolTable() {
  // Drop all abstract type references in the type plane...
  for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
    if (TI->second->isAbstract())   // If abstract, drop the reference...
      cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
  }
}

std::string TypeSymbolTable::getUniqueName(const StringRef &BaseName) const {
  std::string TryName = BaseName;

  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);

  const_iterator End = tmap.end();

  // See if the name exists
  while (tmap.find(TryName) != End)            // Loop until we find a free
    TryName = BaseName.str() + utostr(++LastUnique); // name in the symbol table
  return TryName;
}

// lookup a type by name - returns null on failure
Type* TypeSymbolTable::lookup(const StringRef &Name) const {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);

  const_iterator TI = tmap.find(Name);
  Type* result = 0;
  if (TI != tmap.end())
    result = const_cast<Type*>(TI->second);
  return result;
}

TypeSymbolTable::iterator TypeSymbolTable::find(const StringRef &Name) {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  return tmap.find(Name);
}

TypeSymbolTable::const_iterator
TypeSymbolTable::find(const StringRef &Name) const {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  return tmap.find(Name);
}

// remove - Remove a type from the symbol table...
Type* TypeSymbolTable::remove(iterator Entry) {
  TypeSymbolTableLock->writer_acquire();

  assert(Entry != tmap.end() && "Invalid entry to remove!");
  const Type* Result = Entry->second;

#if DEBUG_SYMBOL_TABLE
  dump();
  errs() << " Removing Value: " << Result->getName() << "\n";
#endif

  tmap.erase(Entry);

  TypeSymbolTableLock->writer_release();

  // If we are removing an abstract type, remove the symbol table from it's use
  // list...
  if (Result->isAbstract()) {
#if DEBUG_ABSTYPE
    errs() << "Removing abstract type from symtab"
           << Result->getDescription()
           << "\n";
#endif
    cast<DerivedType>(Result)->removeAbstractTypeUser(this);
  }

  return const_cast<Type*>(Result);
}

// insert - Insert a type into the symbol table with the specified name...
void TypeSymbolTable::insert(const StringRef &Name, const Type* T) {
  assert(T && "Can't insert null type into symbol table!");

  TypeSymbolTableLock->writer_acquire();

  if (tmap.insert(std::make_pair(Name, T)).second) {
    // Type inserted fine with no conflict.

#if DEBUG_SYMBOL_TABLE
    dump();
    errs() << " Inserted type: " << Name << ": " << T->getDescription() << "\n";
#endif
  } else {
    // If there is a name conflict...

    // Check to see if there is a naming conflict.  If so, rename this type!
    std::string UniqueName = Name;
    if (lookup(Name))
      UniqueName = getUniqueName(Name);

#if DEBUG_SYMBOL_TABLE
    dump();
    errs() << " Inserting type: " << UniqueName << ": "
           << T->getDescription() << "\n";
#endif

    // Insert the tmap entry
    tmap.insert(make_pair(UniqueName, T));
  }

  TypeSymbolTableLock->writer_release();

  // If we are adding an abstract type, add the symbol table to it's use list.
  if (T->isAbstract()) {
    cast<DerivedType>(T)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
    errs() << "Added abstract type to ST: " << T->getDescription() << "\n";
#endif
  }
}

// This function is called when one of the types in the type plane are refined
void TypeSymbolTable::refineAbstractType(const DerivedType *OldType,
                                         const Type *NewType) {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);

  // Loop over all of the types in the symbol table, replacing any references
  // to OldType with references to NewType.  Note that there may be multiple
  // occurrences, and although we only need to remove one at a time, it's
  // faster to remove them all in one pass.
  //
  for (iterator I = begin(), E = end(); I != E; ++I) {
    if (I->second == (Type*)OldType) {  // FIXME when Types aren't const.
#if DEBUG_ABSTYPE
      errs() << "Removing type " << OldType->getDescription() << "\n";
#endif
      OldType->removeAbstractTypeUser(this);

      I->second = (Type*)NewType;  // TODO FIXME when types aren't const
      if (NewType->isAbstract()) {
#if DEBUG_ABSTYPE
        errs() << "Added type " << NewType->getDescription() << "\n";
#endif
        cast<DerivedType>(NewType)->addAbstractTypeUser(this);
      }
    }
  }
}

// Handle situation where type becomes Concreate from Abstract
void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
  // Loop over all of the types in the symbol table, dropping any abstract
  // type user entries for AbsTy which occur because there are names for the
  // type.
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  for (iterator TI = begin(), TE = end(); TI != TE; ++TI)
    if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy)))
      AbsTy->removeAbstractTypeUser(this);
}

static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
  errs() << "  '" << T.first << "' = ";
  T.second->dump();
  errs() << "\n";
}

void TypeSymbolTable::dump() const {
  errs() << "TypeSymbolPlane: ";
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  for_each(tmap.begin(), tmap.end(), DumpTypes);
}

// vim: sw=2 ai
<commit_msg>Fix the build when DEBUG_SYMBOL_TABLE is set.<commit_after>//===-- TypeSymbolTable.cpp - Implement the TypeSymbolTable class ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TypeSymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//

#include "llvm/TypeSymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/RWMutex.h"
#include "llvm/System/Threading.h"
#include <algorithm>
using namespace llvm;

#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0

static ManagedStatic<sys::SmartRWMutex<true> > TypeSymbolTableLock;

TypeSymbolTable::~TypeSymbolTable() {
  // Drop all abstract type references in the type plane...
  for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
    if (TI->second->isAbstract())   // If abstract, drop the reference...
      cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
  }
}

std::string TypeSymbolTable::getUniqueName(const StringRef &BaseName) const {
  std::string TryName = BaseName;

  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);

  const_iterator End = tmap.end();

  // See if the name exists
  while (tmap.find(TryName) != End)            // Loop until we find a free
    TryName = BaseName.str() + utostr(++LastUnique); // name in the symbol table
  return TryName;
}

// lookup a type by name - returns null on failure
Type* TypeSymbolTable::lookup(const StringRef &Name) const {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);

  const_iterator TI = tmap.find(Name);
  Type* result = 0;
  if (TI != tmap.end())
    result = const_cast<Type*>(TI->second);
  return result;
}

TypeSymbolTable::iterator TypeSymbolTable::find(const StringRef &Name) {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  return tmap.find(Name);
}

TypeSymbolTable::const_iterator
TypeSymbolTable::find(const StringRef &Name) const {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  return tmap.find(Name);
}

// remove - Remove a type from the symbol table...
Type* TypeSymbolTable::remove(iterator Entry) {
  TypeSymbolTableLock->writer_acquire();

  assert(Entry != tmap.end() && "Invalid entry to remove!");
  const Type* Result = Entry->second;

#if DEBUG_SYMBOL_TABLE
  dump();
  errs() << " Removing Value: " << Result->getDescription() << "\n";
#endif

  tmap.erase(Entry);

  TypeSymbolTableLock->writer_release();

  // If we are removing an abstract type, remove the symbol table from it's use
  // list...
  if (Result->isAbstract()) {
#if DEBUG_ABSTYPE
    errs() << "Removing abstract type from symtab"
           << Result->getDescription()
           << "\n";
#endif
    cast<DerivedType>(Result)->removeAbstractTypeUser(this);
  }

  return const_cast<Type*>(Result);
}

// insert - Insert a type into the symbol table with the specified name...
void TypeSymbolTable::insert(const StringRef &Name, const Type* T) {
  assert(T && "Can't insert null type into symbol table!");

  TypeSymbolTableLock->writer_acquire();

  if (tmap.insert(std::make_pair(Name, T)).second) {
    // Type inserted fine with no conflict.

#if DEBUG_SYMBOL_TABLE
    dump();
    errs() << " Inserted type: " << Name << ": " << T->getDescription() << "\n";
#endif
  } else {
    // If there is a name conflict...

    // Check to see if there is a naming conflict.  If so, rename this type!
    std::string UniqueName = Name;
    if (lookup(Name))
      UniqueName = getUniqueName(Name);

#if DEBUG_SYMBOL_TABLE
    dump();
    errs() << " Inserting type: " << UniqueName << ": "
           << T->getDescription() << "\n";
#endif

    // Insert the tmap entry
    tmap.insert(make_pair(UniqueName, T));
  }

  TypeSymbolTableLock->writer_release();

  // If we are adding an abstract type, add the symbol table to it's use list.
  if (T->isAbstract()) {
    cast<DerivedType>(T)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
    errs() << "Added abstract type to ST: " << T->getDescription() << "\n";
#endif
  }
}

// This function is called when one of the types in the type plane are refined
void TypeSymbolTable::refineAbstractType(const DerivedType *OldType,
                                         const Type *NewType) {
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);

  // Loop over all of the types in the symbol table, replacing any references
  // to OldType with references to NewType.  Note that there may be multiple
  // occurrences, and although we only need to remove one at a time, it's
  // faster to remove them all in one pass.
  //
  for (iterator I = begin(), E = end(); I != E; ++I) {
    if (I->second == (Type*)OldType) {  // FIXME when Types aren't const.
#if DEBUG_ABSTYPE
      errs() << "Removing type " << OldType->getDescription() << "\n";
#endif
      OldType->removeAbstractTypeUser(this);

      I->second = (Type*)NewType;  // TODO FIXME when types aren't const
      if (NewType->isAbstract()) {
#if DEBUG_ABSTYPE
        errs() << "Added type " << NewType->getDescription() << "\n";
#endif
        cast<DerivedType>(NewType)->addAbstractTypeUser(this);
      }
    }
  }
}

// Handle situation where type becomes Concreate from Abstract
void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
  // Loop over all of the types in the symbol table, dropping any abstract
  // type user entries for AbsTy which occur because there are names for the
  // type.
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  for (iterator TI = begin(), TE = end(); TI != TE; ++TI)
    if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy)))
      AbsTy->removeAbstractTypeUser(this);
}

static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
  errs() << "  '" << T.first << "' = ";
  T.second->dump();
  errs() << "\n";
}

void TypeSymbolTable::dump() const {
  errs() << "TypeSymbolPlane: ";
  sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock);
  for_each(tmap.begin(), tmap.end(), DumpTypes);
}

// vim: sw=2 ai
<|endoftext|>


<commit_before>/**
 * @file llviewerchat.cpp
 * @brief Builds menus out of items.
 *
 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"
#include "llviewerchat.h"

// newview includes
#include "llagent.h" 	// gAgent
#include "llslurl.h"
#include "lluicolor.h"
#include "lluicolortable.h"
#include "llviewercontrol.h" // gSavedSettings
#include "llviewerregion.h"
#include "llworld.h"
#include "llinstantmessage.h" //SYSTEM_FROM
#include "fskeywords.h"
#include "lggcontactsets.h"
#include "rlvhandler.h"
#if LL_WINDOWS
#include "growlmanager.h"
#endif

// LLViewerChat
LLViewerChat::font_change_signal_t LLViewerChat::sChatFontChangedSignal;

//static
void LLViewerChat::getChatColor(const LLChat& chat, LLColor4& r_color, bool is_local)
{
	if(chat.mMuted)
	{
		r_color= LLUIColorTable::instance().getColor("LtGray");
	}
	else
	{
		switch(chat.mSourceType)
		{
			case CHAT_SOURCE_SYSTEM:
				r_color = LLUIColorTable::instance().getColor("SystemChatColor");
				break;
			case CHAT_SOURCE_AGENT:
				if (chat.mFromID.isNull() || SYSTEM_FROM == chat.mFromName)
				{
					r_color = LLUIColorTable::instance().getColor("SystemChatColor");
				}
				else
				{
					if(gAgentID == chat.mFromID)
					{
						r_color = LLUIColorTable::instance().getColor("UserChatColor");
					}
					else
					{
						r_color = LLUIColorTable::instance().getColor("AgentChatColor");
					}
					//color based on contact sets prefs
					if(LGGContactSets::getInstance()->hasFriendColorThatShouldShow(chat.mFromID,TRUE))
					{
						r_color = LGGContactSets::getInstance()->getFriendColor(chat.mFromID);
					}
				}
				break;
			case CHAT_SOURCE_OBJECT:
				if (chat.mChatType == CHAT_TYPE_DEBUG_MSG)
				{
					r_color = LLUIColorTable::instance().getColor("ScriptErrorColor");
				}
				else if ( chat.mChatType == CHAT_TYPE_OWNER )
				{
					r_color = LLUIColorTable::instance().getColor("llOwnerSayChatColor");
				}
				else if ( chat.mChatType == CHAT_TYPE_DIRECT )
				{
					r_color = LLUIColorTable::instance().getColor("DirectChatColor");
				}
				else if ( chat.mChatType == CHAT_TYPE_IM )
				{
					r_color = LLUIColorTable::instance().getColor("ObjectIMColor");
				}
				else
				{
					r_color = LLUIColorTable::instance().getColor("ObjectChatColor");
				}
				break;
			default:
				r_color.setToWhite();
		}

		//Keyword alerts -KC
		if ((gAgentID != chat.mFromID || chat.mFromName == SYSTEM_FROM) && FSKeywords::getInstance()->chatContainsKeyword(chat, is_local))
		{
			std::string msg = chat.mFromName;
			std::string prefix = chat.mText.substr(0, 4);
			if(prefix == "/me " || prefix == "/me'")
			{
				msg = msg + chat.mText.substr(3);
			}
			else
			{
				msg = msg + ": " + chat.mText;
			}

			gGrowlManager->notify("Keyword Alert", msg, "Keyword Alert");

			static LLCachedControl<bool> sFSKeywordChangeColor(gSavedPerAccountSettings, "FSKeywordChangeColor");
			if (sFSKeywordChangeColor)
			{
				static LLCachedControl<LLColor4> sFSKeywordColor(gSavedPerAccountSettings, "FSKeywordColor");
				r_color = sFSKeywordColor;
			}
		}

		if (!chat.mPosAgent.isExactlyZero())
		{
			LLVector3 pos_agent = gAgent.getPositionAgent();
			F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent);
// <FS:CR> Aurora Sim
			//F32 dist_near_chat = gAgent.getNearChatRadius();
			//if (!avatarp || dist_vec_squared(avatarp->getPositionAgent(), gAgent.getPositionAgent()) > say_distance_squared)
			F32 dist_near_chat = LLWorld::getInstance()->getSayDistance();
// </FS:CR> Aurora Sim
			if (distance_squared > dist_near_chat * dist_near_chat)
			{
				// diminish far-off chat
				r_color.mV[VALPHA] = 0.8f;
			}
		}
	}
}

//static
void LLViewerChat::getChatColor(const LLChat& chat, std::string& r_color_name, F32& r_color_alpha)
{
	if(chat.mMuted)
	{
		r_color_name = "LtGray";
	}
	else
	{
		switch(chat.mSourceType)
		{
			case CHAT_SOURCE_SYSTEM:
				r_color_name = "SystemChatColor";
				break;

			case CHAT_SOURCE_AGENT:
				if (chat.mFromID.isNull())
				{
					r_color_name = "SystemChatColor";
				}
				else
				{
					if(gAgentID == chat.mFromID)
					{
						r_color_name = "UserChatColor";
					}
					else
					{
						r_color_name = "AgentChatColor";
					}
				}
				break;

			case CHAT_SOURCE_OBJECT:
				if (chat.mChatType == CHAT_TYPE_DEBUG_MSG)
				{
					r_color_name = "ScriptErrorColor";
				}
				else if ( chat.mChatType == CHAT_TYPE_OWNER )
				{
					r_color_name = "llOwnerSayChatColor";
				}
				else if ( chat.mChatType == CHAT_TYPE_DIRECT )
				{
					r_color_name = "DirectChatColor";
				}
				else if ( chat.mChatType == CHAT_TYPE_IM )
				{
					r_color_name = "ObjectIMColor";
				}
				else
				{
					r_color_name = "ObjectChatColor";
				}
				break;
			default:
				r_color_name = "White";
		}

		if (!chat.mPosAgent.isExactlyZero())
		{
			LLVector3 pos_agent = gAgent.getPositionAgent();
			F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent);
// <FS:CR> Aurora som
			//F32 dist_near_chat = gAgent.getNearChatRadius();
			F32 dist_near_chat = LLWorld::getInstance()->getSayDistance();
// </FS:CR> Aurora sim
			if (distance_squared > dist_near_chat * dist_near_chat)
			{
				// diminish far-off chat
				r_color_alpha = 0.8f;
			}
			else
			{
				r_color_alpha = 1.0f;
			}
		}
	}

}

//static
LLFontGL* LLViewerChat::getChatFont()
{
	S32 font_size = gSavedSettings.getS32("ChatFontSize");
	LLFontGL* fontp = NULL;
	switch(font_size)
	{
		case 0:
			fontp = LLFontGL::getFontSansSerifSmall();
			break;
		default:
		case 1:
			fontp = LLFontGL::getFontSansSerif();
			break;
		case 2:
			fontp = LLFontGL::getFontSansSerifBig();
			break;
		case 3:
			fontp = LLFontGL::getFontSansSerifHuge();
			break;
	}

	return fontp;

}

//static
S32 LLViewerChat::getChatFontSize()
{
	return gSavedSettings.getS32("ChatFontSize");
}

//static
void LLViewerChat::formatChatMsg(const LLChat& chat, std::string& formated_msg)
{
	std::string tmpmsg = chat.mText;

	if(chat.mChatStyle == CHAT_STYLE_IRC)
	{
		formated_msg = chat.mFromName + tmpmsg.substr(3);
	}
	else
	{
		formated_msg = tmpmsg;
	}

}

//static
std::string LLViewerChat::getSenderSLURL(const LLChat& chat, const LLSD& args)
{
	switch (chat.mSourceType)
	{
	case CHAT_SOURCE_AGENT:
		return LLSLURL("agent", chat.mFromID, "about").getSLURLString();

	case CHAT_SOURCE_OBJECT:
		return getObjectImSLURL(chat, args);

	// <FS:Ansariel> Stop spamming the log when processing system messages
	case CHAT_SOURCE_SYSTEM:
		return LLStringUtil::null;
	// </FS:Ansariel>

	default:
		llwarns << "Getting SLURL for an unsupported sender type: " << chat.mSourceType << llendl;
	}

	return LLStringUtil::null;
}

//static
std::string LLViewerChat::getObjectImSLURL(const LLChat& chat, const LLSD& args)
{
	std::string url = LLSLURL("objectim", chat.mFromID, "").getSLURLString();
	url += "?name=" + chat.mFromName;
	url += "&owner=" + chat.mOwnerID.asString();

	std::string slurl = args["slurl"].asString();
	if (slurl.empty())
	{
		LLViewerRegion *region = LLWorld::getInstance()->getRegionFromPosAgent(chat.mPosAgent);
		if(region)
		{
			LLSLURL region_slurl(region->getName(), chat.mPosAgent);
			slurl = region_slurl.getLocationString();
		}
	}

	url += "&slurl=" + LLURI::escape(slurl);

	return url;
}

//static
boost::signals2::connection LLViewerChat::setFontChangedCallback(const font_change_signal_t::slot_type& cb)
{
	return sChatFontChangedSignal.connect(cb);
}

//static
void LLViewerChat::signalChatFontChanged()
{
	// Notify all observers that our font has changed
	sChatFontChangedSignal(getChatFont());
}
<commit_msg>FIRE-5889: Object IM's Not Triggering Growl Notifications<commit_after>/**
 * @file llviewerchat.cpp
 * @brief Builds menus out of items.
 *
 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"
#include "llviewerchat.h"

// newview includes
#include "llagent.h" 	// gAgent
#include "llslurl.h"
#include "lluicolor.h"
#include "lluicolortable.h"
#include "llviewercontrol.h" // gSavedSettings
#include "llviewerregion.h"
#include "llworld.h"
#include "llinstantmessage.h" //SYSTEM_FROM
#include "fskeywords.h"
#include "lggcontactsets.h"
#include "rlvhandler.h"
#if LL_WINDOWS
#include "growlmanager.h"
#endif

// LLViewerChat
LLViewerChat::font_change_signal_t LLViewerChat::sChatFontChangedSignal;

//static
void LLViewerChat::getChatColor(const LLChat& chat, LLColor4& r_color, bool is_local)
{
	if(chat.mMuted)
	{
		r_color= LLUIColorTable::instance().getColor("LtGray");
	}
	else
	{
		switch(chat.mSourceType)
		{
			case CHAT_SOURCE_SYSTEM:
				r_color = LLUIColorTable::instance().getColor("SystemChatColor");
				break;
			case CHAT_SOURCE_AGENT:
				if (chat.mFromID.isNull() || SYSTEM_FROM == chat.mFromName)
				{
					r_color = LLUIColorTable::instance().getColor("SystemChatColor");
				}
				else
				{
					if(gAgentID == chat.mFromID)
					{
						r_color = LLUIColorTable::instance().getColor("UserChatColor");
					}
					else
					{
						r_color = LLUIColorTable::instance().getColor("AgentChatColor");
					}
					//color based on contact sets prefs
					if(LGGContactSets::getInstance()->hasFriendColorThatShouldShow(chat.mFromID,TRUE))
					{
						r_color = LGGContactSets::getInstance()->getFriendColor(chat.mFromID);
					}
				}
				break;
			case CHAT_SOURCE_OBJECT:
				if (chat.mChatType == CHAT_TYPE_DEBUG_MSG)
				{
					r_color = LLUIColorTable::instance().getColor("ScriptErrorColor");
				}
				else if ( chat.mChatType == CHAT_TYPE_OWNER )
				{
					r_color = LLUIColorTable::instance().getColor("llOwnerSayChatColor");
				}
				else if ( chat.mChatType == CHAT_TYPE_DIRECT )
				{
					r_color = LLUIColorTable::instance().getColor("DirectChatColor");
				}
				else if ( chat.mChatType == CHAT_TYPE_IM )
				{
					r_color = LLUIColorTable::instance().getColor("ObjectIMColor");
					// <FS:LO> FIRE-5889: Object IM's Not Triggering Growl Notifications
					std::string msg = chat.mFromName;
					std::string prefix = chat.mText.substr(0, 4);
					if(prefix == "/me " || prefix == "/me'")
					{
						msg = msg + chat.mText.substr(3);
					}
					else
					{
						msg = msg + ": " + chat.mText;
					}
					gGrowlManager->notify(chat.mFromName, msg, GROWL_IM_MESSAGE_TYPE);
					// </FS:LO>
				}
				else
				{
					r_color = LLUIColorTable::instance().getColor("ObjectChatColor");
				}
				break;
			default:
				r_color.setToWhite();
		}

		//Keyword alerts -KC
		if ((gAgentID != chat.mFromID || chat.mFromName == SYSTEM_FROM) && FSKeywords::getInstance()->chatContainsKeyword(chat, is_local))
		{
			std::string msg = chat.mFromName;
			std::string prefix = chat.mText.substr(0, 4);
			if(prefix == "/me " || prefix == "/me'")
			{
				msg = msg + chat.mText.substr(3);
			}
			else
			{
				msg = msg + ": " + chat.mText;
			}

			gGrowlManager->notify("Keyword Alert", msg, "Keyword Alert");

			static LLCachedControl<bool> sFSKeywordChangeColor(gSavedPerAccountSettings, "FSKeywordChangeColor");
			if (sFSKeywordChangeColor)
			{
				static LLCachedControl<LLColor4> sFSKeywordColor(gSavedPerAccountSettings, "FSKeywordColor");
				r_color = sFSKeywordColor;
			}
		}

		if (!chat.mPosAgent.isExactlyZero())
		{
			LLVector3 pos_agent = gAgent.getPositionAgent();
			F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent);
// <FS:CR> Aurora Sim
			//F32 dist_near_chat = gAgent.getNearChatRadius();
			//if (!avatarp || dist_vec_squared(avatarp->getPositionAgent(), gAgent.getPositionAgent()) > say_distance_squared)
			F32 dist_near_chat = LLWorld::getInstance()->getSayDistance();
// </FS:CR> Aurora Sim
			if (distance_squared > dist_near_chat * dist_near_chat)
			{
				// diminish far-off chat
				r_color.mV[VALPHA] = 0.8f;
			}
		}
	}
}

//static
void LLViewerChat::getChatColor(const LLChat& chat, std::string& r_color_name, F32& r_color_alpha)
{
	if(chat.mMuted)
	{
		r_color_name = "LtGray";
	}
	else
	{
		switch(chat.mSourceType)
		{
			case CHAT_SOURCE_SYSTEM:
				r_color_name = "SystemChatColor";
				break;

			case CHAT_SOURCE_AGENT:
				if (chat.mFromID.isNull())
				{
					r_color_name = "SystemChatColor";
				}
				else
				{
					if(gAgentID == chat.mFromID)
					{
						r_color_name = "UserChatColor";
					}
					else
					{
						r_color_name = "AgentChatColor";
					}
				}
				break;

			case CHAT_SOURCE_OBJECT:
				if (chat.mChatType == CHAT_TYPE_DEBUG_MSG)
				{
					r_color_name = "ScriptErrorColor";
				}
				else if ( chat.mChatType == CHAT_TYPE_OWNER )
				{
					r_color_name = "llOwnerSayChatColor";
				}
				else if ( chat.mChatType == CHAT_TYPE_DIRECT )
				{
					r_color_name = "DirectChatColor";
				}
				else if ( chat.mChatType == CHAT_TYPE_IM )
				{
					r_color_name = "ObjectIMColor";
				}
				else
				{
					r_color_name = "ObjectChatColor";
				}
				break;
			default:
				r_color_name = "White";
		}

		if (!chat.mPosAgent.isExactlyZero())
		{
			LLVector3 pos_agent = gAgent.getPositionAgent();
			F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent);
// <FS:CR> Aurora som
			//F32 dist_near_chat = gAgent.getNearChatRadius();
			F32 dist_near_chat = LLWorld::getInstance()->getSayDistance();
// </FS:CR> Aurora sim
			if (distance_squared > dist_near_chat * dist_near_chat)
			{
				// diminish far-off chat
				r_color_alpha = 0.8f;
			}
			else
			{
				r_color_alpha = 1.0f;
			}
		}
	}

}

//static
LLFontGL* LLViewerChat::getChatFont()
{
	S32 font_size = gSavedSettings.getS32("ChatFontSize");
	LLFontGL* fontp = NULL;
	switch(font_size)
	{
		case 0:
			fontp = LLFontGL::getFontSansSerifSmall();
			break;
		default:
		case 1:
			fontp = LLFontGL::getFontSansSerif();
			break;
		case 2:
			fontp = LLFontGL::getFontSansSerifBig();
			break;
		case 3:
			fontp = LLFontGL::getFontSansSerifHuge();
			break;
	}

	return fontp;

}

//static
S32 LLViewerChat::getChatFontSize()
{
	return gSavedSettings.getS32("ChatFontSize");
}

//static
void LLViewerChat::formatChatMsg(const LLChat& chat, std::string& formated_msg)
{
	std::string tmpmsg = chat.mText;

	if(chat.mChatStyle == CHAT_STYLE_IRC)
	{
		formated_msg = chat.mFromName + tmpmsg.substr(3);
	}
	else
	{
		formated_msg = tmpmsg;
	}

}

//static
std::string LLViewerChat::getSenderSLURL(const LLChat& chat, const LLSD& args)
{
	switch (chat.mSourceType)
	{
	case CHAT_SOURCE_AGENT:
		return LLSLURL("agent", chat.mFromID, "about").getSLURLString();

	case CHAT_SOURCE_OBJECT:
		return getObjectImSLURL(chat, args);

	// <FS:Ansariel> Stop spamming the log when processing system messages
	case CHAT_SOURCE_SYSTEM:
		return LLStringUtil::null;
	// </FS:Ansariel>

	default:
		llwarns << "Getting SLURL for an unsupported sender type: " << chat.mSourceType << llendl;
	}

	return LLStringUtil::null;
}

//static
std::string LLViewerChat::getObjectImSLURL(const LLChat& chat, const LLSD& args)
{
	std::string url = LLSLURL("objectim", chat.mFromID, "").getSLURLString();
	url += "?name=" + chat.mFromName;
	url += "&owner=" + chat.mOwnerID.asString();

	std::string slurl = args["slurl"].asString();
	if (slurl.empty())
	{
		LLViewerRegion *region = LLWorld::getInstance()->getRegionFromPosAgent(chat.mPosAgent);
		if(region)
		{
			LLSLURL region_slurl(region->getName(), chat.mPosAgent);
			slurl = region_slurl.getLocationString();
		}
	}

	url += "&slurl=" + LLURI::escape(slurl);

	return url;
}

//static
boost::signals2::connection LLViewerChat::setFontChangedCallback(const font_change_signal_t::slot_type& cb)
{
	return sChatFontChangedSignal.connect(cb);
}

//static
void LLViewerChat::signalChatFontChanged()
{
	// Notify all observers that our font has changed
	sChatFontChangedSignal(getChatFont());
}
<|endoftext|>


<commit_before>#include "teensy3/WProgram.h"
#include "teensy3/core_pins.h"
#include "teensy3/usb_serial.h"

#define ROWS 15
#define COLS 112

#define SYNC 10
#define CLK 11
#define DAT 12
#define HIBANK 3
#define LOBANK 4
#define BIT0 0
#define BIT1 1
#define BIT2 2

#define bufferSize 2048

int serialbuffer[bufferSize];
int img1[ROWS][COLS];
int img2[ROWS][COLS];

int currentRow;
int serialEnd;

void setRow(int row) {
  digitalWrite(LOBANK, HIGH);
  digitalWrite(HIBANK, HIGH);
  digitalWrite(BIT0, row & 1);
  digitalWrite(BIT1, row & 2);
  digitalWrite(BIT2, row & 4);
  if ((row < 8) & (row < 16) & (row >= 0)) {
    digitalWrite(HIBANK, LOW);
  } else if ((row >= 8) & (row < 16)) {
    digitalWrite(LOBANK, LOW);
  }
}

void initialize() {
    pinMode(CLK, OUTPUT);
    pinMode(DAT, OUTPUT);
    pinMode(LOBANK, OUTPUT);
    pinMode(HIBANK, OUTPUT);
    pinMode(BIT0, OUTPUT);
    pinMode(BIT1, OUTPUT);
    pinMode(BIT2, OUTPUT);
    pinMode(SYNC, OUTPUT);

    currentRow = 0;
    serialEnd = 0;
}

extern "C" int main(void) {
  initialize();
  elapsedMillis refresh = 0;
  int* img = (int*)img1;
  int *nimg = (int*)img2;

  int ledState = 0;

  Serial.begin(9600);

  while(1) {
    setRow(16);
    digitalWrite(SYNC, currentRow);
    for(int col = 0; col < COLS; col++) {
      digitalWrite(DAT, img[currentRow*COLS + col] ? HIGH : LOW);
      digitalWrite(CLK, LOW);
      delayMicroseconds(2);
      digitalWrite(CLK, HIGH);
    }
    setRow(ROWS - currentRow - 1);
    currentRow++;
    currentRow %= 16;
    for (int i=0; i<118; i++) {
      if (Serial.available()) {
        serialbuffer[serialEnd] = Serial.read();
        serialEnd++;
      }
      if (serialEnd == 1) {
        if (serialbuffer[0] != 0xCA) {
          serialEnd = 0;
        }
      }
      if (serialEnd == 2) {
        if (serialbuffer[1] != 0xFE) {
          serialEnd = 0;
        }
      }
      if (serialEnd > 2) {
        if (serialbuffer[2] == 0x00) { //Blit frame
          if (img == (int*)img1) {
            img = (int*)img2;
            nimg = (int*)img1;
          } else {
            img = (int*)img1;
            nimg = (int*)img2;
          }
          serialEnd = 0;
        }
        if ((serialbuffer[2] == 0x01) & (serialEnd == COLS*ROWS+3)) {
          for (int i=0; i<COLS*ROWS; i++) {
            nimg[i] = serialbuffer[i+3];
          }
          serialEnd = 0;
        }
      }
      if (serialEnd > bufferSize) {
        serialEnd = 0;
      }
    }
    refresh = 0;
  }
}
<commit_msg>Blink LED while serial data is received<commit_after>#include "teensy3/WProgram.h"
#include "teensy3/core_pins.h"
#include "teensy3/usb_serial.h"

#define ROWS 15
#define COLS 112

#define SYNC 10
#define CLK 11
#define DAT 12
#define HIBANK 3
#define LOBANK 4
#define BIT0 0
#define BIT1 1
#define BIT2 2

#define bufferSize 2048

int serialbuffer[bufferSize];
int img1[ROWS][COLS];
int img2[ROWS][COLS];

int currentRow;
int serialEnd;

void setRow(int row) {
  digitalWrite(LOBANK, HIGH);
  digitalWrite(HIBANK, HIGH);
  digitalWrite(BIT0, row & 1);
  digitalWrite(BIT1, row & 2);
  digitalWrite(BIT2, row & 4);
  if ((row < 8) & (row < 16) & (row >= 0)) {
    digitalWrite(HIBANK, LOW);
  } else if ((row >= 8) & (row < 16)) {
    digitalWrite(LOBANK, LOW);
  }
}

void initialize() {
    pinMode(CLK, OUTPUT);
    pinMode(DAT, OUTPUT);
    pinMode(LOBANK, OUTPUT);
    pinMode(HIBANK, OUTPUT);
    pinMode(BIT0, OUTPUT);
    pinMode(BIT1, OUTPUT);
    pinMode(BIT2, OUTPUT);
    pinMode(SYNC, OUTPUT);
    pinMode(13, OUTPUT);

    currentRow = 0;
    serialEnd = 0;
}

extern "C" int main(void) {
  initialize();
  elapsedMillis refresh = 0;
  int* img = (int*)img1;
  int *nimg = (int*)img2;

  int ledState = 0;

  Serial.begin(9600);

  while(1) {
    setRow(16);
    digitalWrite(SYNC, currentRow);
    for(int col = 0; col < COLS; col++) {
      digitalWrite(DAT, img[currentRow*COLS + col] ? HIGH : LOW);
      digitalWrite(CLK, LOW);
      delayMicroseconds(2);
      digitalWrite(CLK, HIGH);
    }
    setRow(ROWS - currentRow - 1);
    currentRow++;
    currentRow %= 16;
    for (int i=0; i<118; i++) {
      if (Serial.available()) {
        digitalWrite(13, HIGH);
        serialbuffer[serialEnd] = Serial.read();
        serialEnd++;
      }
      if (serialEnd == 1) {
        if (serialbuffer[0] != 0xCA) {
          digitalWrite(13, LOW);
          serialEnd = 0;
        }
      }
      if (serialEnd == 2) {
        if (serialbuffer[1] != 0xFE) {
          digitalWrite(13, LOW);
          serialEnd = 0;
        }
      }
      if (serialEnd > 2) {
        if (serialbuffer[2] == 0x00) { //Blit frame
          digitalWrite(13, LOW);
          if (img == (int*)img1) {
            img = (int*)img2;
            nimg = (int*)img1;
          } else {
            img = (int*)img1;
            nimg = (int*)img2;
          }
          serialEnd = 0;
        }
        if ((serialbuffer[2] == 0x01) & (serialEnd == COLS*ROWS+3)) {
          for (int i=0; i<COLS*ROWS; i++) {
            nimg[i] = serialbuffer[i+3];
          }
          digitalWrite(13, LOW);
          serialEnd = 0;
        }
      }
      if (serialEnd > bufferSize) {
        digitalWrite(13, LOW);
        serialEnd = 0;
      }
    }
    refresh = 0;
  }
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_HH
#define DUNE_GDT_OPERATORS_ELLIPTIC_HH

#include <dune/grid/common/gridview.hh>

#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container.hh>

#include <dune/gdt/localevaluation/elliptic.hh>
#include <dune/gdt/localoperator/integrals.hh>
#include <dune/gdt/operators/interfaces.hh>
#include <dune/gdt/operators/default.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class DiffusionFactorType,
          typename DiffusionTensorType, // may be void
          class GridView, class Range, class Source = Range, class Field = typename Range::RangeFieldType>
class EllipticLocalizableProduct : public LocalizableProductDefault<GridView, Range, Source, Field>
{
  typedef LocalizableProductDefault<GridView, Range, Source, Field> BaseType;
  typedef LocalVolumeIntegralOperator<LocalEvaluation::Elliptic<DiffusionFactorType, DiffusionTensorType>>
      LocalEllipticOperatorType;

public:
  // Usually, we only hace to hold the data functions for the local operator and perfect forward the rest of the
  // arguments to BaseType. Here, it is a bit more complicated, since DiffusionTensorType might be void (and
  // DiffusionFactorType is the the only diffusion). To handle this case we require the enable_if hacks below to
  // disable half of the ctors if DiffusionTensorType is void. In addition we require each ctor twice, once with
  // over_integrate, once without (since the perfect forwarding does not allow for default arguments).

  template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function.
            ,
            typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value) //
                                               && (std::is_same<DiffusionImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const DiffusionImp& diffusion, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(diffusion)
  {
    this->add(local_elliptic_operator_);
  }

  template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function.
            ,
            typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value)
                                               && (std::is_same<DiffusionImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionImp& diffusion, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(over_integrate, diffusion)
  {
    this->add(local_elliptic_operator_);
  }

  template <typename DiffusionFactorImp // This ctor is only enabled
            ,
            typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor).
            ,
            typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value)
                                               && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionFactorImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const DiffusionFactorImp& diffusion_factor,
                                      const DiffusionTensorImp& diffusion_tensor, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(diffusion_factor, diffusion_tensor)
  {
    this->add(local_elliptic_operator_);
  }

  template <typename DiffusionFactorImp // This ctor is only enabled
            ,
            typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor).
            ,
            typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value)
                                               && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionFactorImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionFactorImp& diffusion_factor,
                                      const DiffusionTensorImp& diffusion_tensor, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(over_integrate, diffusion_factor, diffusion_tensor)
  {
    this->add(local_elliptic_operator_);
  }

private:
  const LocalEllipticOperatorType local_elliptic_operator_;
}; // class EllipticLocalizableProduct

/**
 * \sa EllipticLocalizableProduct, especially for the role of diffusion.
 */
template <class DiffusionType, class GridViewType, class RangeType, class SourceType>
typename std::enable_if<Stuff::is_localizable_function<DiffusionType>::value
                            && Stuff::is_localizable_function<RangeType>::value
                            && Stuff::is_localizable_function<SourceType>::value,
                        std::unique_ptr<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType,
                                                                   SourceType>>>::type
make_elliptic_localizable_product(const DiffusionType& diffusion, const GridViewType& grid_view, const RangeType& range,
                                  const SourceType& source, const size_t over_integrate = 0)
{
  return DSC::make_unique<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType, SourceType>>(
      over_integrate, diffusion, grid_view, range, source);
}

/**
 * \sa EllipticLocalizableProduct, especially for the role of diffusion_factor and diffusion_tensor.
 */
template <class DiffusionFactorType, class DiffusionTensorType, class GridViewType, class RangeType, class SourceType>
typename std::enable_if<Stuff::is_localizable_function<DiffusionFactorType>::value
                            && Stuff::is_localizable_function<DiffusionTensorType>::value
                            && Stuff::is_localizable_function<RangeType>::value
                            && Stuff::is_localizable_function<SourceType>::value,
                        std::unique_ptr<EllipticLocalizableProduct<DiffusionFactorType, DiffusionTensorType,
                                                                   GridViewType, RangeType, SourceType>>>::type
make_elliptic_localizable_product(const DiffusionFactorType& diffusion_factor,
                                  const DiffusionTensorType& diffusion_tensor, const GridViewType& grid_view,
                                  const RangeType& range, const SourceType& source, const size_t over_integrate = 0)
{
  return DSC::make_unique<EllipticLocalizableProduct<DiffusionFactorType,
                                                     DiffusionTensorType,
                                                     GridViewType,
                                                     RangeType,
                                                     SourceType>>(
      over_integrate, diffusion_factor, diffusion_tensor, grid_view, range, source);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_ELLIPTIC_HH
<commit_msg>[operators.elliptic] add delimiters<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_HH
#define DUNE_GDT_OPERATORS_ELLIPTIC_HH

#include <dune/grid/common/gridview.hh>

#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container.hh>

#include <dune/gdt/localevaluation/elliptic.hh>
#include <dune/gdt/localoperator/integrals.hh>
#include <dune/gdt/operators/interfaces.hh>
#include <dune/gdt/operators/default.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

// ////////////////////////// //
// EllipticLocalizableProduct //
// ////////////////////////// //

template <class DiffusionFactorType,
          typename DiffusionTensorType, // may be void
          class GridView, class Range, class Source = Range, class Field = typename Range::RangeFieldType>
class EllipticLocalizableProduct : public LocalizableProductDefault<GridView, Range, Source, Field>
{
  typedef LocalizableProductDefault<GridView, Range, Source, Field> BaseType;
  typedef LocalVolumeIntegralOperator<LocalEvaluation::Elliptic<DiffusionFactorType, DiffusionTensorType>>
      LocalEllipticOperatorType;

public:
  // Usually, we only hace to hold the data functions for the local operator and perfect forward the rest of the
  // arguments to BaseType. Here, it is a bit more complicated, since DiffusionTensorType might be void (and
  // DiffusionFactorType is the the only diffusion). To handle this case we require the enable_if hacks below to
  // disable half of the ctors if DiffusionTensorType is void. In addition we require each ctor twice, once with
  // over_integrate, once without (since the perfect forwarding does not allow for default arguments).

  template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function.
            ,
            typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value) //
                                               && (std::is_same<DiffusionImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const DiffusionImp& diffusion, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(diffusion)
  {
    this->add(local_elliptic_operator_);
  }

  template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function.
            ,
            typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value)
                                               && (std::is_same<DiffusionImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionImp& diffusion, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(over_integrate, diffusion)
  {
    this->add(local_elliptic_operator_);
  }

  template <typename DiffusionFactorImp // This ctor is only enabled
            ,
            typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor).
            ,
            typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value)
                                               && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionFactorImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const DiffusionFactorImp& diffusion_factor,
                                      const DiffusionTensorImp& diffusion_tensor, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(diffusion_factor, diffusion_tensor)
  {
    this->add(local_elliptic_operator_);
  }

  template <typename DiffusionFactorImp // This ctor is only enabled
            ,
            typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor).
            ,
            typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value)
                                               && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value)
                                               && sizeof(DiffusionFactorImp)>::type,
            class... Args>
  explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionFactorImp& diffusion_factor,
                                      const DiffusionTensorImp& diffusion_tensor, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_elliptic_operator_(over_integrate, diffusion_factor, diffusion_tensor)
  {
    this->add(local_elliptic_operator_);
  }

private:
  const LocalEllipticOperatorType local_elliptic_operator_;
}; // class EllipticLocalizableProduct

// ///////////////////////////////// //
// make_elliptic_localizable_product //
// ///////////////////////////////// //

/**
 * \sa EllipticLocalizableProduct, especially for the role of diffusion.
 */
template <class DiffusionType, class GridViewType, class RangeType, class SourceType>
typename std::enable_if<Stuff::is_localizable_function<DiffusionType>::value
                            && Stuff::is_localizable_function<RangeType>::value
                            && Stuff::is_localizable_function<SourceType>::value,
                        std::unique_ptr<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType,
                                                                   SourceType>>>::type
make_elliptic_localizable_product(const DiffusionType& diffusion, const GridViewType& grid_view, const RangeType& range,
                                  const SourceType& source, const size_t over_integrate = 0)
{
  return DSC::make_unique<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType, SourceType>>(
      over_integrate, diffusion, grid_view, range, source);
}

/**
 * \sa EllipticLocalizableProduct, especially for the role of diffusion_factor and diffusion_tensor.
 */
template <class DiffusionFactorType, class DiffusionTensorType, class GridViewType, class RangeType, class SourceType>
typename std::enable_if<Stuff::is_localizable_function<DiffusionFactorType>::value
                            && Stuff::is_localizable_function<DiffusionTensorType>::value
                            && Stuff::is_localizable_function<RangeType>::value
                            && Stuff::is_localizable_function<SourceType>::value,
                        std::unique_ptr<EllipticLocalizableProduct<DiffusionFactorType, DiffusionTensorType,
                                                                   GridViewType, RangeType, SourceType>>>::type
make_elliptic_localizable_product(const DiffusionFactorType& diffusion_factor,
                                  const DiffusionTensorType& diffusion_tensor, const GridViewType& grid_view,
                                  const RangeType& range, const SourceType& source, const size_t over_integrate = 0)
{
  return DSC::make_unique<EllipticLocalizableProduct<DiffusionFactorType,
                                                     DiffusionTensorType,
                                                     GridViewType,
                                                     RangeType,
                                                     SourceType>>(
      over_integrate, diffusion_factor, diffusion_tensor, grid_view, range, source);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_ELLIPTIC_HH
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CONSTRAINTS_HH
#define DUNE_GDT_SPACES_CONSTRAINTS_HH

#include <ostream>

#include <dune/common/dynvector.hh>
#include <dune/common/dynmatrix.hh>

#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/crtp.hh>

namespace Dune {
namespace GDT {
namespace Spaces {

template< class Traits, class ValueImp = double >
class ConstraintsInterface
  : public Stuff::CRTPInterface< ConstraintsInterface< Traits, ValueImp >, Traits >
{
public:
  typedef typename Traits::derived_type derived_type;
  typedef ValueImp                      ValueType;

  inline size_t rows() const
  {
    CHECK_CRTP(this->as_imp().rows());
    return this->as_imp().rows();
  }

  inline size_t cols() const
  {
    CHECK_CRTP(this->as_imp().cols());
    return this->as_imp().cols();
  }

  inline size_t global_row(const size_t ii) const
  {
    CHECK_CRTP(this->as_imp().global_row(ii));
    return this->as_imp().global_row(ii);
  }

  inline size_t global_col(const size_t jj) const
  {
    CHECK_CRTP(this->as_imp().global_col(jj));
    return this->as_imp().global_col(jj);
  }

  inline ValueType value(const size_t ii, const size_t jj) const
  {
    CHECK_CRTP(this->as_imp().value(ii, jj));
    return this->as_imp().value(ii, jj);
  }

private:
  template< class T, class V >
  friend std::ostream& operator<<(std::ostream& /*out*/, const ConstraintsInterface< T, V >& /*constraints*/);
}; // class ConstraintsInterface

template< class T, class V >
std::ostream& operator<<(std::ostream& out, const ConstraintsInterface< T, V >& constraints)
{
  out << "gdt.spaces.constraints of size " << constraints.rows() << " x " << constraints.cols() << ", containing\n";
  for (size_t ii = 0; ii < constraints.rows(); ++ii)
    for (size_t jj = 0; jj < constraints.cols(); ++jj)
      out << "  " << constraints.global_row(ii) << ", " << constraints.global_col(jj) << ": "
          << constraints.value(ii, jj) << "\n";
  return out;
} // ... operator<<(...)

namespace Constraints {
namespace internal {

template< class DerivedTraits, class ValueImp >
class Default
  : public ConstraintsInterface< DerivedTraits, ValueImp >
{
  typedef ConstraintsInterface< DerivedTraits, ValueImp > BaseType;
public:
  typedef DerivedTraits                Traits;
  typedef typename BaseType::ValueType ValueType;

private:
  typedef DynamicVector< size_t >    IndicesType;
  typedef DynamicMatrix< ValueType > ValuesType;

public:
  Default(const size_t rws, const size_t cls)
    : rows_(rws)
    , cols_(cls)
    , global_rows_(rows_)
    , global_cols_(cols_)
    , values_(rows_, cols_)
  {}

  size_t rows() const
  {
    return rows_;
  }

  size_t cols() const
  {
    return cols_;
  }

  void set_size(const size_t rr, const size_t cc)
  {
    rows_ = rr;
    cols_ = cc;
    bool changed = false;
    if (rows_ > global_rows_.size()) {
      global_rows_.resize(rows_, 0);
      changed = true;
    }
    if (cols_ > global_cols_.size()) {
      global_cols_.resize(cols_, 0);
      changed = true;
    }
    if (changed)
      values_.resize(global_rows_.size(), global_cols_.size(), 0);
  } // ... set_size(...)

  size_t& global_row(const size_t ii)
  {
    assert(ii < std::min(rows_, global_rows_.size()));
    return global_rows_[ii];
  }

  size_t global_row(const size_t ii) const
  {
    assert(ii < std::min(rows_, global_rows_.size()));
    return global_rows_[ii];
  }

  size_t& global_col(const size_t jj)
  {
    assert(jj < std::min(cols_, global_cols_.size()));
    return global_cols_[jj];
  }

  size_t global_col(const size_t jj) const
  {
    assert(jj < std::min(cols_, global_cols_.size()));
    return global_cols_[jj];
  }

  ValueType& value(const size_t ii, const size_t jj)
  {
    assert(ii < std::min(rows_, global_rows_.size()));
    assert(jj < std::min(cols_, global_cols_.size()));
    return values_[ii][jj];
  }

  ValueType value(const size_t ii, const size_t jj) const
  {
    assert(ii < std::min(rows_, global_rows_.size()));
    assert(jj < std::min(cols_, global_cols_.size()));
    return values_[ii][jj];
  }

private:
  size_t rows_;
  size_t cols_;
  IndicesType global_rows_;
  IndicesType global_cols_;
  ValuesType values_;
}; // class Default

} // namespace internal

template< class IntersectionType, class ValueImp = double >
class Dirichlet;

namespace internal {

template< class IntersectionType, class ValueImp >
class DirichletTraits
{
public:
  typedef Dirichlet< IntersectionType, ValueImp > derived_type;
};

} // namespace internal

template< class IntersectionType, class ValueImp >
class Dirichlet
  : public internal::Default< internal::DirichletTraits< IntersectionType, ValueImp >, ValueImp >
{
  typedef internal::Default< internal::DirichletTraits< IntersectionType, ValueImp >, ValueImp > BaseType;
public:
  typedef Stuff::Grid::BoundaryInfoInterface< IntersectionType > BoundaryInfoType;

  Dirichlet(const BoundaryInfoType& bnd_info, const size_t rws, const size_t cls, const bool set_rw = true)
    : BaseType(rws, cls)
    , boundary_info_(bnd_info)
    , set_row_(set_rw)
  {}

  const BoundaryInfoType& boundary_info() const
  {
    return boundary_info_;
  }

  bool set_row() const
  {
    return set_row_;
  }

private:
  const BoundaryInfoType& boundary_info_;
  const bool set_row_;
}; // class Dirichlet

} // namespace Constraints
} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CONSTRAINTS_HH
<commit_msg>[spaces.constraints] refactor, refs #51<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CONSTRAINTS_HH
#define DUNE_GDT_SPACES_CONSTRAINTS_HH

#include <ostream>

#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/la/container/interfaces.hh>

namespace Dune {
namespace GDT {
namespace Spaces {

/**
 * \brief CRTP interface for all implementations of constraints.
 *
 *        We need this interface for template matching in the SystemAssembler.
 */
template< class Traits >
class ConstraintsInterface
  : public Stuff::CRTPInterface< ConstraintsInterface< Traits >, Traits >
{
public:
  typedef typename Traits::derived_type derived_type;
}; // class ConstraintsInterface

// forward
template< class IntersectionType >
class DirichletConstraints;

namespace internal {

template< class IntersectionType >
class DirichletConstraintsTraits
{
public:
  typedef DirichletConstraints< IntersectionType > derived_type;
};

} // namespace internal

template< class IntersectionType >
class DirichletConstraints
  : public ConstraintsInterface< internal::DirichletConstraintsTraits< IntersectionType > >
{
public:
  typedef internal::DirichletConstraintsTraits< IntersectionType > Traits;
  typedef Stuff::Grid::BoundaryInfoInterface< IntersectionType >   BoundaryInfoType;

  DirichletConstraints(const BoundaryInfoType& bnd_info, const size_t sz, const bool set = true)
    : boundary_info_(bnd_info)
    , size_(sz)
    , set_(set)
  {}

  const BoundaryInfoType& boundary_info() const
  {
    return boundary_info_;
  }

  inline void insert(const size_t DoF)
  {
    assert(DoF < size_);
    dirichlet_DoFs_.insert(DoF);
  }

  template< class M >
  void apply(Stuff::LA::MatrixInterface< M >& matrix) const
  {
    assert(matrix.rows() == size_);
    if (set_) {
      for (const auto& DoF : dirichlet_DoFs_)
        matrix.unit_row(DoF);
    } else {
      for (const auto& DoF : dirichlet_DoFs_)
        matrix.clear_row(DoF);
    }
  } // ... apply(...)

  template< class V >
  void apply(Stuff::LA::VectorInterface< V >& vector) const
  {
    assert(vector.size() == size_);
    for (const auto& DoF : dirichlet_DoFs_)
      vector[DoF] = 0.0;
  }

  template< class M, class V >
  void apply(Stuff::LA::MatrixInterface< M >& matrix, Stuff::LA::VectorInterface< V >& vector) const
  {
    assert(matrix.rows() == size_);
    assert(vector.size() == size_);
    if (set_) {
      for (const auto& DoF : dirichlet_DoFs_) {
        matrix.unit_row(DoF);
        vector[DoF] = 0.0;
      }
    } else {
      for (const auto& DoF : dirichlet_DoFs_) {
        matrix.clear_row(DoF);
        vector[DoF] = 0.0;
      }
    }
  } // ... apply(...)

private:
  const BoundaryInfoType& boundary_info_;
  const size_t size_;
  const bool set_;
  std::set< size_t > dirichlet_DoFs_;
}; // class DirichletConstraints

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CONSTRAINTS_HH
<|endoftext|>