<commit_before>#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>

#include "base91.hpp"

#define LOG std::cerr << "L_" << __LINE__ << ": "

//------------------------------------------------------------------------------

template <typename T>
bool test_refurbish(const size_t size)
{
    T data_original(size);
    std::generate(data_original.begin(), data_original.end(), std::rand);

    std::string text;
    base91::encode(data_original, text);

    const std::string base91_alphabet
        = "!~}|{zyxwvutsrqponmlkjihgfedcba`_^]#[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)($&%";
    size_t n = 0;
    // verify whether encoded text contains symbols from base91 alphabet only
    for (auto it_text : text)
    {
        if (std::string::npos == base91_alphabet.find(it_text))
        {
            LOG << "error on " << n << " element '" << it_text << "' not in '" << base91_alphabet << "'"
                << std::endl;
            return false;
        }
        ++n;
    }

    LOG << "Test with data [" << data_original.size() << "] -> encoded text [" << text.size() << "]" << std::endl;
    if (80 < text.size())
    {
        LOG << "Limit to first 80 symbols:" << std::endl << text.substr(1, 79) << std::endl;
    }
    else
    {
        LOG << text << std::endl;
    }

    T data_refurbed;
    base91::decode(text, data_refurbed);

    if (data_original.size() != data_refurbed.size())
    {
        LOG << "data_original size (" << data_original.size() << ") does not equal data_refurbed size ("
            << data_refurbed.size() << ")" << std::endl;
        return false;
    }

    n = 0;
    auto it_original = data_original.begin();
    auto it_refurbed = data_refurbed.begin();
    while (it_original != data_original.end() and it_refurbed != data_refurbed.end())
    {
        if (*it_original != *it_refurbed)
        {
            LOG << "error on " << n << " element" << std::endl;
            return false;
        }
        ++n;
        ++it_original;
        ++it_refurbed;
    }
    LOG << "Test passed with size = " << data_original.size() << std::endl;

    if (base91::compute_encoded_size(size) != text.size())
    {
        LOG << "computed " << base91::compute_encoded_size(size) << " != " << text.size() << std::endl;
        return false;
    }

    if (base91::assume_decoded_size(text.size()) != size)
    {
        LOG << "assumed " << base91::assume_decoded_size(size) << " != " << text.size() << std::endl;
        return false;
    }

    return true;
}

//------------------------------------------------------------------------------

bool test_static_with_space()
{
    const std::string pangram_test = "* / * / *The quick brown fox\tjumps\nover\rthe lazy dog { < # > }";
    const std::string pangram_expected = "*/*/*Thequickbrownfoxjumpsoverthelazydog{<#>}";
    std::vector<unsigned char> data;
    base91::decode(pangram_test, data);

    const std::vector<unsigned char> data_expected = {197, 188, 152, 123, 190, 170, 196, 57, 20, 212, 152, 234, 45,
        19, 38, 185, 248, 29, 56, 51, 69, 134, 70, 46, 193, 65, 219, 166, 60, 124, 38, 76, 84, 125, 125, 174};

    if (data_expected.size() != data.size())
    {
        LOG << "data size = " << data.size() << ": expected size = " << data_expected.size() << std::endl;
        return false;
    }

    size_t n = 0;
    auto it = data.begin();
    auto it_ = data_expected.begin();
    while (it != data.end() and it_ != data_expected.end())
    {
        if (*it != *it_)
        {
            LOG << "Error on " << n << " element. got " << int(*it_) << " expected " << int(*it) << std::endl;
            return false;
        }
        ++n;
        ++it;
        ++it_;
    }

    if (data.size() != n)
    {
        LOG << "Pass only " << n << "bytes. Expected " << data.size() << std::endl;
        return false;
    }

    std::string pangram_refurb;
    base91::encode(data, pangram_refurb);

    if (pangram_expected != pangram_refurb)
    {
        LOG << "Not matched" << std::endl << pangram_expected << std::endl << pangram_refurb << std::endl;
        return false;
    }
    LOG << "Static test passed" << std::endl;
    return true;
}

//------------------------------------------------------------------------------

int main(const int argc, const char *argv[])
{
    std::srand(std::time(nullptr));
    // various size of random data to cover all possibly calculated size
    for (int n = 0; n < 33; ++n)
    {
        if (not( //
                test_refurbish<std::vector<char>>(n) //
                && //
                test_refurbish<std::vector<unsigned char>>(n) //
                ))
            return 1;
    }
    // 1Mb of random data
    if ( //
        test_refurbish<std::vector<char>>(std::rand() % (1 << 20)) //
        && //
        test_refurbish<std::vector<unsigned char>>(std::rand() % (1 << 20)) //
        && //
        test_static_with_space() //
    )
        return 0;
    return 1;
}

//------------------------------------------------------------------------------
<commit_msg>stress test for c++<commit_after>#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>

#include "base91.hpp"

#define LOG std::cerr << "L_" << __LINE__ << ": "

//------------------------------------------------------------------------------

template <typename T>
bool test_refurbish(const size_t size)
{
    T data_original(size);
    std::generate(data_original.begin(), data_original.end(), std::rand);

    std::string text;
    base91::encode(data_original, text);

    const std::string base91_alphabet
        = "!~}|{zyxwvutsrqponmlkjihgfedcba`_^]#[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)($&%";
    size_t n = 0;
    // verify whether encoded text contains symbols from base91 alphabet only
    for (auto it_text : text)
    {
        if (std::string::npos == base91_alphabet.find(it_text))
        {
            LOG << "error on " << n << " element '" << it_text << "' not in '" << base91_alphabet << "'"
                << std::endl;
            return false;
        }
        ++n;
    }

    LOG << "Test with data [" << data_original.size() << "] -> encoded text [" << text.size() << "]" << std::endl;
    if (80 < text.size())
    {
        LOG << "Limit to first 80 symbols:" << std::endl << text.substr(1, 79) << std::endl;
    }
    else
    {
        LOG << text << std::endl;
    }

    T data_refurbed;
    base91::decode(text, data_refurbed);

    if (data_original.size() != data_refurbed.size())
    {
        LOG << "data_original size (" << data_original.size() << ") does not equal data_refurbed size ("
            << data_refurbed.size() << ")" << std::endl;
        return false;
    }

    n = 0;
    auto it_original = data_original.begin();
    auto it_refurbed = data_refurbed.begin();
    while (it_original != data_original.end() and it_refurbed != data_refurbed.end())
    {
        if (*it_original != *it_refurbed)
        {
            LOG << "error on " << n << " element" << std::endl;
            return false;
        }
        ++n;
        ++it_original;
        ++it_refurbed;
    }
    LOG << "Test passed with size = " << data_original.size() << std::endl;

    if (base91::compute_encoded_size(size) != text.size())
    {
        LOG << "computed " << base91::compute_encoded_size(size) << " != " << text.size() << std::endl;
        return false;
    }

    if (base91::assume_decoded_size(text.size()) != size)
    {
        LOG << "assumed " << base91::assume_decoded_size(size) << " != " << text.size() << std::endl;
        return false;
    }

    return true;
}

//------------------------------------------------------------------------------

bool test_static_with_space()
{
    const std::string pangram_test = "* / * / *The quick brown fox\tjumps\nover\rthe lazy dog { < # > }";
    const std::string pangram_expected = "*/*/*Thequickbrownfoxjumpsoverthelazydog{<#>}";
    std::vector<unsigned char> data;
    base91::decode(pangram_test, data);

    const std::vector<unsigned char> data_expected = {197, 188, 152, 123, 190, 170, 196, 57, 20, 212, 152, 234, 45,
        19, 38, 185, 248, 29, 56, 51, 69, 134, 70, 46, 193, 65, 219, 166, 60, 124, 38, 76, 84, 125, 125, 174};

    if (data_expected.size() != data.size())
    {
        LOG << "data size = " << data.size() << ": expected size = " << data_expected.size() << std::endl;
        return false;
    }

    size_t n = 0;
    auto it = data.begin();
    auto it_ = data_expected.begin();
    while (it != data.end() and it_ != data_expected.end())
    {
        if (*it != *it_)
        {
            LOG << "Error on " << n << " element. got " << int(*it_) << " expected " << int(*it) << std::endl;
            return false;
        }
        ++n;
        ++it;
        ++it_;
    }

    if (data.size() != n)
    {
        LOG << "Pass only " << n << "bytes. Expected " << data.size() << std::endl;
        return false;
    }

    std::string pangram_refurb;
    base91::encode(data, pangram_refurb);

    if (pangram_expected != pangram_refurb)
    {
        LOG << "Not matched" << std::endl << pangram_expected << std::endl << pangram_refurb << std::endl;
        return false;
    }
    LOG << "Static test passed" << std::endl;
    return true;
}

//------------------------------------------------------------------------------

bool test_stress(const size_t size)
{
    std::string text;
    text.resize(size);
    std::generate(text.begin(), text.end(), std::rand);
    std::vector<unsigned char> data;
    base91::decode(text, data);
    LOG << "Stress test: from " << size << " symbols were decoded " << data.size() << " bytes" << std::endl;
    LOG << "Stress test passed" << std::endl;
    return true;
}

//------------------------------------------------------------------------------

int main(const int argc, const char *argv[])
{
    std::srand(std::time(nullptr));
    // various size of random data to cover all possibly calculated size
    for (int n = 0; n < 33; ++n)
    {
        if (not( //
                test_refurbish<std::vector<char>>(n) //
                && //
                test_refurbish<std::vector<unsigned char>>(n) //
                ))
            return 1;
    }
    // 1Mb of random data
    if ( //
        test_refurbish<std::vector<char>>(std::rand() % (1 << 20)) //
        && //
        test_refurbish<std::vector<unsigned char>>(std::rand() % (1 << 20)) //
        && //
        test_static_with_space() //
        && //
        test_stress(1 << 20) //
    )
        return 0;
    return 1;
}

//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include "Test.h"

using namespace ::testing;

#define EVIL_EOF (-0xE0F)

extern "C" FILE* test_fopen(const char* filename,
                            const char* mode);
extern "C" int test_fwrite(const void *data,
                           size_t size,
                           size_t nmemb,
                           FILE *f);
extern "C" int test_fflush(FILE *f);
extern "C" int test_fclose(FILE *f);
extern "C" int test_ferror(FILE *f);
extern "C" void __evil_malloc_reset(void);

class FflushTest : public evil::Test {
public:
    FILE *_f;

    virtual void SetUp() {
        evil::Test::SetUp();

        EXPECT_CALL(_syscalls, _isatty(_))
            .WillOnce(Return(0));
        EXPECT_CALL(_syscalls, _open(_, _, _))
            .WillOnce(Return(3));

        _f = test_fopen("", "w");
        ASSERT_NE(nullptr, _f);
    }

    virtual void TearDown() {
        EXPECT_CALL(_syscalls, _close(3))
            .WillOnce(Return(0));
        EXPECT_EQ(0, test_fclose(_f));

        evil::Test::TearDown();
    }
};

TEST_F(FflushTest, null) {
    evil::UBChecker ub{1};
    EXPECT_EQ(EVIL_EOF, test_fflush(nullptr));
}

TEST_F(FflushTest, nothing_to_do) {
    EXPECT_EQ(0, test_fflush(_f));
}

TEST_F(FflushTest, failed_write) {
    const char data[] = "foo";
    EXPECT_EQ(sizeof(data), test_fwrite(data, sizeof(data), 1, _f));

    EXPECT_CALL(_syscalls, _write(3, _, 4))
        .WillOnce(Return(-1));

    EXPECT_EQ(EVIL_EOF, test_fflush(_f));
    EXPECT_NE(0, test_ferror(_f));
}

TEST_F(FflushTest, short_write) {
    const char data[] = "foo";
    EXPECT_EQ(sizeof(data), test_fwrite(data, sizeof(data), 1, _f));

    EXPECT_CALL(_syscalls, _write(3, _, 4))
        .WillOnce(Return(2));

    EXPECT_EQ(EVIL_EOF, test_fflush(_f));
    EXPECT_NE(0, test_ferror(_f));
}
<commit_msg>Fix FflushTest.failed_write<commit_after>#include "Test.h"

using namespace ::testing;

#define EVIL_EOF (-0xE0F)

extern "C" FILE* test_fopen(const char* filename,
                            const char* mode);
extern "C" int test_fwrite(const void *data,
                           size_t size,
                           size_t nmemb,
                           FILE *f);
extern "C" int test_fflush(FILE *f);
extern "C" int test_fclose(FILE *f);
extern "C" int test_ferror(FILE *f);
extern "C" void __evil_malloc_reset(void);

class FflushTest : public evil::Test {
public:
    FILE *_f;

    virtual void SetUp() {
        evil::Test::SetUp();

        EXPECT_CALL(_syscalls, _isatty(_))
            .WillOnce(Return(0));
        EXPECT_CALL(_syscalls, _open(_, _, _))
            .WillOnce(Return(3));

        _f = test_fopen("", "w");
        ASSERT_NE(nullptr, _f);
    }

    virtual void TearDown() {
        EXPECT_CALL(_syscalls, _close(3))
            .WillOnce(Return(0));
        EXPECT_EQ(0, test_fclose(_f));

        evil::Test::TearDown();
    }
};

TEST_F(FflushTest, null) {
    evil::UBChecker ub{1};
    EXPECT_EQ(EVIL_EOF, test_fflush(nullptr));
}

TEST_F(FflushTest, nothing_to_do) {
    EXPECT_EQ(0, test_fflush(_f));
}

TEST_F(FflushTest, failed_write) {
    const char data[] = "foo";
    EXPECT_EQ(sizeof(data), test_fwrite(data, 1, sizeof(data), _f));

    EXPECT_CALL(_syscalls, _write(3, _, 4))
        .WillOnce(Return(-1));

    EXPECT_EQ(EVIL_EOF, test_fflush(_f));
    EXPECT_NE(0, test_ferror(_f));
}

TEST_F(FflushTest, short_write) {
    const char data[] = "foo";
    EXPECT_EQ(sizeof(data), test_fwrite(data, sizeof(data), 1, _f));

    EXPECT_CALL(_syscalls, _write(3, _, 4))
        .WillOnce(Return(2));

    EXPECT_EQ(EVIL_EOF, test_fflush(_f));
    EXPECT_NE(0, test_ferror(_f));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dsEntriesNoExp.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: obo $ $Date: 2005-07-08 10:38:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _DBAUI_LISTVIEWITEMS_HXX_
#include "listviewitems.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#ifndef _DBU_BRW_HRC_
#include "dbu_brw.hrc"
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif

using namespace ::com::sun::star::frame;
using namespace ::dbtools;
using namespace ::svx;

// .........................................................................
namespace dbaui
{
// .........................................................................
// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getChildType( SvLBoxEntry* _pEntry ) const
{
    DBG_ASSERT(isContainer(_pEntry), "SbaTableQueryBrowser::getChildType: invalid entry!");
    switch (getEntryType(_pEntry))
    {
        case etTableContainer:
            return etTable;
        case etQueryContainer:
            return etQuery;
    }
    return etUnknown;
}

// -----------------------------------------------------------------------------
String SbaTableQueryBrowser::GetEntryText( SvLBoxEntry* _pEntry ) const
{
    return m_pTreeView->getListBox()->GetEntryText(_pEntry);
}

// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getEntryType( SvLBoxEntry* _pEntry ) const
{
    if (!_pEntry)
        return etUnknown;

    SvLBoxEntry* pRootEntry     = m_pTreeView->getListBox()->GetRootLevelParent(_pEntry);
    SvLBoxEntry* pEntryParent   = m_pTreeView->getListBox()->GetParent(_pEntry);
    SvLBoxEntry* pTables        = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_TABLES);
    SvLBoxEntry* pQueries       = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_QUERIES);

#ifdef DBG_UTIL
    String sTest;
    if (pTables) sTest = m_pTreeView->getListBox()->GetEntryText(pTables);
    if (pQueries) sTest = m_pTreeView->getListBox()->GetEntryText(pQueries);
#endif

    if (pRootEntry == _pEntry)
        return etDatasource;

    if (pTables == _pEntry)
        return etTableContainer;

    if (pQueries == _pEntry)
        return etQueryContainer;

    if (pTables == pEntryParent)
        return etTable;

    if (pQueries == pEntryParent)
        return etQuery;

    return etUnknown;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::select(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
    SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
    if (pTextItem)
    {
        static_cast<OBoldListboxString*>(pTextItem)->emphasize(_bSelect);
        m_pTreeModel->InvalidateEntry(_pEntry);
    }
    else
        DBG_ERROR("SbaTableQueryBrowser::select: invalid entry!");
}

//------------------------------------------------------------------------------
void SbaTableQueryBrowser::selectPath(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
    while (_pEntry)
    {
        select(_pEntry, _bSelect);
        _pEntry = m_pTreeModel->GetParent(_pEntry);
    }
}
//------------------------------------------------------------------------------
sal_Bool SbaTableQueryBrowser::isSelected(SvLBoxEntry* _pEntry) const
{
    SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
    if (pTextItem)
        return static_cast<OBoldListboxString*>(pTextItem)->isEmphasized();
    else
        DBG_ERROR("SbaTableQueryBrowser::isSelected: invalid entry!");
    return sal_False;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::SelectionChanged()
{
    if ( !m_bShowMenu )
    {
        InvalidateFeature(ID_BROWSER_INSERTCOLUMNS);
        InvalidateFeature(ID_BROWSER_INSERTCONTENT);
        InvalidateFeature(ID_BROWSER_FORMLETTER);
    }
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::describeSupportedFeatures()
{
    SbaXDataBrowserController::describeSupportedFeatures();

    implDescribeSupportedFeature( ".uno:Title",                             ID_BROWSER_TITLE );
    if ( !m_bShowMenu )
    {
        implDescribeSupportedFeature( ".uno:DSBrowserExplorer",                 ID_BROWSER_EXPLORER, CommandGroup::VIEW );

        implDescribeSupportedFeature( ".uno:DSBFormLetter",                     ID_BROWSER_FORMLETTER, CommandGroup::DOCUMENT );
        implDescribeSupportedFeature( ".uno:DSBInsertColumns",                  ID_BROWSER_INSERTCOLUMNS, CommandGroup::INSERT );
        implDescribeSupportedFeature( ".uno:DSBInsertContent",                  ID_BROWSER_INSERTCONTENT, CommandGroup::INSERT );
        implDescribeSupportedFeature( ".uno:DSBDocumentDataSource",             ID_BROWSER_DOCUMENT_DATASOURCE, CommandGroup::VIEW );

        implDescribeSupportedFeature( ".uno:DataSourceBrowser/FormLetter",          ID_BROWSER_FORMLETTER );
        implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertColumns",       ID_BROWSER_INSERTCOLUMNS );
        implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertContent",       ID_BROWSER_INSERTCONTENT );
        implDescribeSupportedFeature( ".uno:DataSourceBrowser/DocumentDataSource",  ID_BROWSER_DOCUMENT_DATASOURCE );
    }

    implDescribeSupportedFeature( ".uno:CloseWin",      ID_BROWSER_CLOSE, CommandGroup::DOCUMENT );
    implDescribeSupportedFeature( ".uno:DBRebuildData", ID_BROWSER_REFRESH_REBUILD, CommandGroup::DATA );
}
// -------------------------------------------------------------------------
String SbaTableQueryBrowser::getURL() const
{
    return String();
}
// -----------------------------------------------------------------------------
void SbaTableQueryBrowser::notifyHiContrastChanged()
{
    if ( m_pTreeView )
    {
        sal_Bool bHiContrast = isHiContrast();

        if ( m_bHiContrast != bHiContrast )
        {
            m_bHiContrast = bHiContrast;
            // change all bitmap entries
            DBTreeListBox* pListBox = m_pTreeView->getListBox();

            SvLBoxEntry* pEntryLoop = m_pTreeModel->First();
            while ( pEntryLoop )
            {
                DBTreeListModel::DBTreeListUserData* pData = static_cast<DBTreeListModel::DBTreeListUserData*>(pEntryLoop->GetUserData());
                if ( pData )
                {
                    ModuleRes aResId(DBTreeListModel::getImageResId(pData->eType,isHiContrast()));
                    Image aImage(aResId);
                    USHORT nCount = pEntryLoop->ItemCount();
                    for (USHORT i=0;i<nCount;++i)
                    {
                        SvLBoxItem* pItem = pEntryLoop->GetItem(i);
                        if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXCONTEXTBMP)
                        {
                            static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap1(pEntryLoop,aImage);
                            static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap2(pEntryLoop,aImage);
                            break;
                        }
                    }
                }
                pEntryLoop = m_pTreeModel->Next(pEntryLoop);
            }
        }
    }
}
// -----------------------------------------------------------------------------
// .........................................................................
}   // namespace dbaui
// .........................................................................

<commit_msg>INTEGRATION: CWS ooo19126 (1.13.46); FILE MERGED 2005/09/05 17:33:15 rt 1.13.46.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dsEntriesNoExp.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:28:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _DBAUI_LISTVIEWITEMS_HXX_
#include "listviewitems.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBAUI_DBTREELISTBOX_HXX
#include "dbtreelistbox.hxx"
#endif
#ifndef _DBU_BRW_HRC_
#include "dbu_brw.hrc"
#endif
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif

using namespace ::com::sun::star::frame;
using namespace ::dbtools;
using namespace ::svx;

// .........................................................................
namespace dbaui
{
// .........................................................................
// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getChildType( SvLBoxEntry* _pEntry ) const
{
    DBG_ASSERT(isContainer(_pEntry), "SbaTableQueryBrowser::getChildType: invalid entry!");
    switch (getEntryType(_pEntry))
    {
        case etTableContainer:
            return etTable;
        case etQueryContainer:
            return etQuery;
    }
    return etUnknown;
}

// -----------------------------------------------------------------------------
String SbaTableQueryBrowser::GetEntryText( SvLBoxEntry* _pEntry ) const
{
    return m_pTreeView->getListBox()->GetEntryText(_pEntry);
}

// -----------------------------------------------------------------------------
SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getEntryType( SvLBoxEntry* _pEntry ) const
{
    if (!_pEntry)
        return etUnknown;

    SvLBoxEntry* pRootEntry     = m_pTreeView->getListBox()->GetRootLevelParent(_pEntry);
    SvLBoxEntry* pEntryParent   = m_pTreeView->getListBox()->GetParent(_pEntry);
    SvLBoxEntry* pTables        = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_TABLES);
    SvLBoxEntry* pQueries       = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_QUERIES);

#ifdef DBG_UTIL
    String sTest;
    if (pTables) sTest = m_pTreeView->getListBox()->GetEntryText(pTables);
    if (pQueries) sTest = m_pTreeView->getListBox()->GetEntryText(pQueries);
#endif

    if (pRootEntry == _pEntry)
        return etDatasource;

    if (pTables == _pEntry)
        return etTableContainer;

    if (pQueries == _pEntry)
        return etQueryContainer;

    if (pTables == pEntryParent)
        return etTable;

    if (pQueries == pEntryParent)
        return etQuery;

    return etUnknown;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::select(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
    SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
    if (pTextItem)
    {
        static_cast<OBoldListboxString*>(pTextItem)->emphasize(_bSelect);
        m_pTreeModel->InvalidateEntry(_pEntry);
    }
    else
        DBG_ERROR("SbaTableQueryBrowser::select: invalid entry!");
}

//------------------------------------------------------------------------------
void SbaTableQueryBrowser::selectPath(SvLBoxEntry* _pEntry, sal_Bool _bSelect)
{
    while (_pEntry)
    {
        select(_pEntry, _bSelect);
        _pEntry = m_pTreeModel->GetParent(_pEntry);
    }
}
//------------------------------------------------------------------------------
sal_Bool SbaTableQueryBrowser::isSelected(SvLBoxEntry* _pEntry) const
{
    SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL;
    if (pTextItem)
        return static_cast<OBoldListboxString*>(pTextItem)->isEmphasized();
    else
        DBG_ERROR("SbaTableQueryBrowser::isSelected: invalid entry!");
    return sal_False;
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::SelectionChanged()
{
    if ( !m_bShowMenu )
    {
        InvalidateFeature(ID_BROWSER_INSERTCOLUMNS);
        InvalidateFeature(ID_BROWSER_INSERTCONTENT);
        InvalidateFeature(ID_BROWSER_FORMLETTER);
    }
}
//------------------------------------------------------------------------------
void SbaTableQueryBrowser::describeSupportedFeatures()
{
    SbaXDataBrowserController::describeSupportedFeatures();

    implDescribeSupportedFeature( ".uno:Title",                             ID_BROWSER_TITLE );
    if ( !m_bShowMenu )
    {
        implDescribeSupportedFeature( ".uno:DSBrowserExplorer",                 ID_BROWSER_EXPLORER, CommandGroup::VIEW );

        implDescribeSupportedFeature( ".uno:DSBFormLetter",                     ID_BROWSER_FORMLETTER, CommandGroup::DOCUMENT );
        implDescribeSupportedFeature( ".uno:DSBInsertColumns",                  ID_BROWSER_INSERTCOLUMNS, CommandGroup::INSERT );
        implDescribeSupportedFeature( ".uno:DSBInsertContent",                  ID_BROWSER_INSERTCONTENT, CommandGroup::INSERT );
        implDescribeSupportedFeature( ".uno:DSBDocumentDataSource",             ID_BROWSER_DOCUMENT_DATASOURCE, CommandGroup::VIEW );

        implDescribeSupportedFeature( ".uno:DataSourceBrowser/FormLetter",          ID_BROWSER_FORMLETTER );
        implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertColumns",       ID_BROWSER_INSERTCOLUMNS );
        implDescribeSupportedFeature( ".uno:DataSourceBrowser/InsertContent",       ID_BROWSER_INSERTCONTENT );
        implDescribeSupportedFeature( ".uno:DataSourceBrowser/DocumentDataSource",  ID_BROWSER_DOCUMENT_DATASOURCE );
    }

    implDescribeSupportedFeature( ".uno:CloseWin",      ID_BROWSER_CLOSE, CommandGroup::DOCUMENT );
    implDescribeSupportedFeature( ".uno:DBRebuildData", ID_BROWSER_REFRESH_REBUILD, CommandGroup::DATA );
}
// -------------------------------------------------------------------------
String SbaTableQueryBrowser::getURL() const
{
    return String();
}
// -----------------------------------------------------------------------------
void SbaTableQueryBrowser::notifyHiContrastChanged()
{
    if ( m_pTreeView )
    {
        sal_Bool bHiContrast = isHiContrast();

        if ( m_bHiContrast != bHiContrast )
        {
            m_bHiContrast = bHiContrast;
            // change all bitmap entries
            DBTreeListBox* pListBox = m_pTreeView->getListBox();

            SvLBoxEntry* pEntryLoop = m_pTreeModel->First();
            while ( pEntryLoop )
            {
                DBTreeListModel::DBTreeListUserData* pData = static_cast<DBTreeListModel::DBTreeListUserData*>(pEntryLoop->GetUserData());
                if ( pData )
                {
                    ModuleRes aResId(DBTreeListModel::getImageResId(pData->eType,isHiContrast()));
                    Image aImage(aResId);
                    USHORT nCount = pEntryLoop->ItemCount();
                    for (USHORT i=0;i<nCount;++i)
                    {
                        SvLBoxItem* pItem = pEntryLoop->GetItem(i);
                        if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXCONTEXTBMP)
                        {
                            static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap1(pEntryLoop,aImage);
                            static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap2(pEntryLoop,aImage);
                            break;
                        }
                    }
                }
                pEntryLoop = m_pTreeModel->Next(pEntryLoop);
            }
        }
    }
}
// -----------------------------------------------------------------------------
// .........................................................................
}   // namespace dbaui
// .........................................................................

<|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_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH

#include <vector>
#include <type_traits>

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

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/mapper/interface.hh>

namespace Dune {
namespace GDT {

template< class VectorImp >
class ConstLocalDoFVector
{
  static_assert(std::is_base_of< Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
  typedef VectorImp VectorType;
  typedef typename VectorType::ScalarType ScalarType;

  template< class M, class EntityType >
  ConstLocalDoFVector(const MapperInterface< M >& mapper,
                      const EntityType& entity,
                      const VectorType& vector)
    : vector_(vector)
    , indices_(mapper.numDofs(entity))
  {
    mapper.globalIndices(entity, indices_);
  }

  ~ConstLocalDoFVector() {}

  size_t size() const
  {
    return indices_.size();
  }

  ScalarType get(const size_t ii) const
  {
    assert(ii < indices_.size());
    return vector_.get_entry(indices_[ii]);
  }

private:
  const VectorType& vector_;
protected:
  Dune::DynamicVector< size_t > indices_;

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

template< class V >
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector< V >& vector)
{
  out << "[";
  const size_t sz = vector.size();
  if (sz > 0) {
    out << vector.get(0);
    for (size_t ii = 1; ii < sz; ++ii)
      out << ", " << vector.get(ii);
  } else
    out << " ";
  out << "]";
  return out;
} // ... operator<<(...)

template< class VectorImp >
class LocalDoFVector
  : public ConstLocalDoFVector< VectorImp >
{
  typedef ConstLocalDoFVector< VectorImp > BaseType;
public:
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::ScalarType ScalarType;

  template< class M, class EntityType >
  LocalDoFVector(const MapperInterface< M >& mapper,
                 const EntityType& entity,
                 VectorType& vector)
    : BaseType(mapper, entity, vector)
    , vector_(vector)
  {}

  ~LocalDoFVector() {}

  void set(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.set_entry(indices_[ii], val);
  }

  void add(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.add_to_entry(indices_[ii], val);
  }

private:
  using BaseType::indices_;
  VectorType& vector_;
}; // class LocalDoFVector

template< class SpaceImp, class VectorImp >
class ConstLocalDiscreteFunction
  : public Stuff::LocalfunctionInterface< typename SpaceImp::EntityType,
                                          typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
                                          typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
{
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits >, SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< Dune::Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same< typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType >::value,
                "Types do not match!");
  typedef Stuff::LocalfunctionInterface
      < typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
        typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
    BaseType;
  typedef ConstLocalDiscreteFunction< SpaceImp, VectorImp > ThisType;
public:
  typedef SpaceImp                      SpaceType;
  typedef VectorImp                     VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const unsigned int                 dimRangeRows = BaseType::dimRangeCols;
  static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType      RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef ConstLocalDoFVector< VectorType > ConstLocalDoFVectorType;

  ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
    : BaseType(ent)
    , space_(space)
    , base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
    , localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
    , tmpBaseValues_(base_->size(), RangeType(0))
    , tmpBaseJacobianValues_(base_->size(), JacobianRangeType(0))
  {
    assert(localVector_->size() == base_->size());
  }

  ConstLocalDiscreteFunction(ThisType&& source) = default;

  ConstLocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~ConstLocalDiscreteFunction() {}

  const BaseFunctionSetType& base() const
  {
    return *base_;
  }

  const ConstLocalDoFVectorType& vector() const
  {
    return *localVector_;
  }

  virtual size_t order() const DS_OVERRIDE
  {
    return base_->order();
  }

  virtual void evaluate(const DomainType& xx, RangeType& ret) const DS_OVERRIDE
  {
    assert(this->is_a_valid_point(xx));
    ret *= 0.0;
    assert(localVector_->size() == tmpBaseValues_->size());
    base_->evaluate(xx, *tmpBaseValues_);
    for (size_t ii = 0; ii < localVector_->size(); ++ii) {
      (*tmpBaseValues_)[ii] *= localVector_->get(ii);
      ret += (*tmpBaseValues_)[ii];
    }
  } // ... evaluate(...)

  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE
  {
    assert(this->is_a_valid_point(xx));
    ret *= RangeFieldType(0);
    assert(localVector_->size() == tmpBaseJacobianValues_->size());
    base_->jacobian(xx, *tmpBaseJacobianValues_);
    for (size_t ii = 0; ii < localVector_->size(); ++ii) {
      (*tmpBaseJacobianValues_)[ii] *= localVector_->get(ii);
      ret += (*tmpBaseJacobianValues_)[ii];
    }
  } // ... jacobian(...)

  using BaseType::evaluate;
  using BaseType::jacobian;

protected:
  const SpaceType& space_;
  std::unique_ptr< const BaseFunctionSetType > base_;
  std::unique_ptr< const ConstLocalDoFVectorType > localVector_;
private:
  mutable DS::PerThreadValue<std::vector<RangeType>> tmpBaseValues_;
  mutable DS::PerThreadValue<std::vector<JacobianRangeType>> tmpBaseJacobianValues_;
}; // class ConstLocalDiscreteFunction

template< class SpaceImp, class VectorImp >
class LocalDiscreteFunction
  : public ConstLocalDiscreteFunction< SpaceImp, VectorImp >
{
  typedef ConstLocalDiscreteFunction< SpaceImp, VectorImp > BaseType;
  typedef LocalDiscreteFunction< SpaceImp, VectorImp >      ThisType;
public:
  typedef typename BaseType::SpaceType  SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const unsigned int                 dimRangeRows = BaseType::dimRangeCols;
  static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType      RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef LocalDoFVector< VectorType > LocalDoFVectorType;

  LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
    : BaseType(space, globalVector, ent)
    , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  //! previous comment questioned validity, defaulting this doesn't touch that question
  LocalDiscreteFunction(ThisType&& source) = default;

  LocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~LocalDiscreteFunction() {}

  LocalDoFVectorType& vector()
  {
    return *localVector_;
  }

private:
  using BaseType::space_;
  using BaseType::entity_;
  using BaseType::base_;
  std::unique_ptr< LocalDoFVectorType > localVector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[df.local] makes tmp values local to function scope<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_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH

#include <vector>
#include <type_traits>

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

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/mapper/interface.hh>

namespace Dune {
namespace GDT {

template< class VectorImp >
class ConstLocalDoFVector
{
  static_assert(std::is_base_of< Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
  typedef VectorImp VectorType;
  typedef typename VectorType::ScalarType ScalarType;

  template< class M, class EntityType >
  ConstLocalDoFVector(const MapperInterface< M >& mapper,
                      const EntityType& entity,
                      const VectorType& vector)
    : vector_(vector)
    , indices_(mapper.numDofs(entity))
  {
    mapper.globalIndices(entity, indices_);
  }

  ~ConstLocalDoFVector() {}

  size_t size() const
  {
    return indices_.size();
  }

  ScalarType get(const size_t ii) const
  {
    assert(ii < indices_.size());
    return vector_.get_entry(indices_[ii]);
  }

private:
  const VectorType& vector_;
protected:
  Dune::DynamicVector< size_t > indices_;

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

template< class V >
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector< V >& vector)
{
  out << "[";
  const size_t sz = vector.size();
  if (sz > 0) {
    out << vector.get(0);
    for (size_t ii = 1; ii < sz; ++ii)
      out << ", " << vector.get(ii);
  } else
    out << " ";
  out << "]";
  return out;
} // ... operator<<(...)

template< class VectorImp >
class LocalDoFVector
  : public ConstLocalDoFVector< VectorImp >
{
  typedef ConstLocalDoFVector< VectorImp > BaseType;
public:
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::ScalarType ScalarType;

  template< class M, class EntityType >
  LocalDoFVector(const MapperInterface< M >& mapper,
                 const EntityType& entity,
                 VectorType& vector)
    : BaseType(mapper, entity, vector)
    , vector_(vector)
  {}

  ~LocalDoFVector() {}

  void set(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.set_entry(indices_[ii], val);
  }

  void add(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.add_to_entry(indices_[ii], val);
  }

private:
  using BaseType::indices_;
  VectorType& vector_;
}; // class LocalDoFVector

template< class SpaceImp, class VectorImp >
class ConstLocalDiscreteFunction
  : public Stuff::LocalfunctionInterface< typename SpaceImp::EntityType,
                                          typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
                                          typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
{
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits >, SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< Dune::Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same< typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType >::value,
                "Types do not match!");
  typedef Stuff::LocalfunctionInterface
      < typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain,
        typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols >
    BaseType;
  typedef ConstLocalDiscreteFunction< SpaceImp, VectorImp > ThisType;
public:
  typedef SpaceImp                      SpaceType;
  typedef VectorImp                     VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const unsigned int                 dimRangeRows = BaseType::dimRangeCols;
  static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType      RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef ConstLocalDoFVector< VectorType > ConstLocalDoFVectorType;

  ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
    : BaseType(ent)
    , space_(space)
    , base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
    , localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  ConstLocalDiscreteFunction(ThisType&& source) = default;

  ConstLocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~ConstLocalDiscreteFunction() {}

  const BaseFunctionSetType& base() const
  {
    return *base_;
  }

  const ConstLocalDoFVectorType& vector() const
  {
    return *localVector_;
  }

  virtual size_t order() const DS_OVERRIDE
  {
    return base_->order();
  }

  virtual void evaluate(const DomainType& xx, RangeType& ret) const DS_OVERRIDE
  {
    assert(this->is_a_valid_point(xx));
    ret *= 0.0;
    std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
    assert(localVector_->size() == tmpBaseValues.size());
    base_->evaluate(xx, tmpBaseValues);
    for (size_t ii = 0; ii < localVector_->size(); ++ii) {
      tmpBaseValues[ii] *= localVector_->get(ii);
      ret += tmpBaseValues[ii];
    }
  } // ... evaluate(...)

  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE
  {
    assert(this->is_a_valid_point(xx));
    ret *= RangeFieldType(0);
    std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
    assert(localVector_->size() == tmpBaseJacobianValues.size());
    base_->jacobian(xx, tmpBaseJacobianValues);
    for (size_t ii = 0; ii < localVector_->size(); ++ii) {
      tmpBaseJacobianValues[ii] *= localVector_->get(ii);
      ret += tmpBaseJacobianValues[ii];
    }
  } // ... jacobian(...)

  using BaseType::evaluate;
  using BaseType::jacobian;

protected:
  const SpaceType& space_;
  std::unique_ptr< const BaseFunctionSetType > base_;
  std::unique_ptr< const ConstLocalDoFVectorType > localVector_;
}; // class ConstLocalDiscreteFunction

template< class SpaceImp, class VectorImp >
class LocalDiscreteFunction
  : public ConstLocalDiscreteFunction< SpaceImp, VectorImp >
{
  typedef ConstLocalDiscreteFunction< SpaceImp, VectorImp > BaseType;
  typedef LocalDiscreteFunction< SpaceImp, VectorImp >      ThisType;
public:
  typedef typename BaseType::SpaceType  SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const unsigned int                 dimRangeRows = BaseType::dimRangeCols;
  static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType      RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef LocalDoFVector< VectorType > LocalDoFVectorType;

  LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
    : BaseType(space, globalVector, ent)
    , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  //! previous comment questioned validity, defaulting this doesn't touch that question
  LocalDiscreteFunction(ThisType&& source) = default;

  LocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~LocalDiscreteFunction() {}

  LocalDoFVectorType& vector()
  {
    return *localVector_;
  }

private:
  using BaseType::space_;
  using BaseType::entity_;
  using BaseType::base_;
  std::unique_ptr< LocalDoFVectorType > localVector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|>


<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===//
//                         _       _
//                        | |     | |
//                    __ _| |_ ___| | __ _ _ __   __ _
//                   / _` | __/ __| |/ _` | '_ \ / _` |
//                  | (_| | || (__| | (_| | | | | (_| |
//                   \__, |\__\___|_|\__,_|_| |_|\__, | - GridTools Clang DSL
//                    __/ |                       __/ |
//                   |___/                       |___/
//
//
//  This file is distributed under the MIT License (MIT).
//  See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//

#include "gtclang/Frontend/GTClangASTConsumer.h"
#include "dawn/Compiler/DawnCompiler.h"
#include "dawn/SIR/SIR.h"
#include "dawn/SIR/SIRSerializerJSON.h"
#include "dawn/Support/Config.h"
#include "dawn/Support/Format.h"
#include "dawn/Support/StringUtil.h"
#include "gtclang/Frontend/ClangFormat.h"
#include "gtclang/Frontend/GTClangASTAction.h"
#include "gtclang/Frontend/GTClangASTVisitor.h"
#include "gtclang/Frontend/GTClangContext.h"
#include "gtclang/Frontend/GlobalVariableParser.h"
#include "gtclang/Frontend/StencilParser.h"
#include "gtclang/Support/Config.h"
#include "gtclang/Support/FileUtil.h"
#include "gtclang/Support/Logger.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/Version.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include <cstdio>
#include <ctime>
#include <iostream>
#include <memory>
#include <system_error>

namespace gtclang {

/// @brief Get current time-stamp
static const std::string currentDateTime() {
  std::time_t now = time(0);
  char buf[80];
  std::strftime(buf, sizeof(buf), "%Y-%m-%d  %X", std::localtime(&now));
  return buf;
}

/// @brief Extract the DAWN options from the GTClang options
static std::unique_ptr<dawn::Options> makeDAWNOptions(const Options& options) {
  auto DAWNOptions = llvm::make_unique<dawn::Options>();
#define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \
  DAWNOptions->NAME = options.NAME;
#include "dawn/Compiler/Options.inc"
#undef OPT
  return DAWNOptions;
}

GTClangASTConsumer::GTClangASTConsumer(GTClangContext* context, const std::string& file,
                                       GTClangASTAction* parentAction)
    : context_(context), file_(file), parentAction_(parentAction) {
  DAWN_LOG(INFO) << "Creating ASTVisitor ... ";
  visitor_ = llvm::make_unique<GTClangASTVisitor>(context);
}

void GTClangASTConsumer::HandleTranslationUnit(clang::ASTContext& ASTContext) {
  context_->setASTContext(&ASTContext);
  if(!context_->hasDiagnostics())
    context_->setDiagnostics(&ASTContext.getDiagnostics());

  DAWN_LOG(INFO) << "Parsing translation unit... ";

  clang::TranslationUnitDecl* TU = ASTContext.getTranslationUnitDecl();
  for(auto& decl : TU->decls())
    visitor_->TraverseDecl(decl);

  DAWN_LOG(INFO) << "Done parsing translation unit";

  if(context_->getASTContext().getDiagnostics().hasErrorOccurred()) {
    DAWN_LOG(INFO) << "Erros occurred. Aborting";
    return;
  }

  DAWN_LOG(INFO) << "Generating SIR ... ";
  auto& SM = context_->getSourceManager();

  // Assemble SIR
  std::shared_ptr<dawn::SIR> SIR = std::make_shared<dawn::SIR>();
  SIR->Filename = SM.getFileEntryForID(SM.getMainFileID())->getName();

  const StencilParser& stencilParser = visitor_->getStencilParser();

  for(const auto& stencilPair : stencilParser.getStencilMap()) {
    SIR->Stencils.emplace_back(stencilPair.second);
    SIR->Stencils.back()->Attributes = context_->getStencilAttribute(stencilPair.second->Name);
  }

  for(const auto& stencilPair : stencilParser.getStencilFunctionMap()) {
    SIR->StencilFunctions.emplace_back(stencilPair.second);
    SIR->StencilFunctions.back()->Attributes =
        context_->getStencilAttribute(stencilPair.second->Name);
  }

  const GlobalVariableParser& globalsParser = visitor_->getGlobalVariableParser();
  SIR->GlobalVariableMap = globalsParser.getGlobalVariableMap();

  if(context_->getOptions().DumpSIR) {
    dawn::SIRSerializerJSON::serialize("sir.json", SIR.get());
    SIR->dump();
  }
  parentAction_->setSIR(SIR);

  // Set the backend
  dawn::DawnCompiler::CodeGenKind codeGen = dawn::DawnCompiler::CG_GTClang;
  if(context_->getOptions().Backend == "gridtools")
    codeGen = dawn::DawnCompiler::CG_GTClang;
  else if(context_->getOptions().Backend == "c++")
    codeGen = dawn::DawnCompiler::CG_GTClangNaiveCXX;
  else {
    context_->getDiagnostics().report(Diagnostics::err_invalid_option)
        << ("-backend=" + context_->getOptions().Backend)
        << dawn::RangeToString(", ", "", "")(std::vector<std::string>{"gridtools", "c++"});
  }

  // Compile the SIR to GridTools
  dawn::DawnCompiler Compiler(makeDAWNOptions(context_->getOptions()).get());
  std::unique_ptr<dawn::TranslationUnit> DawnTranslationUnit = Compiler.compile(SIR.get(), codeGen);

  // Report diagnostics from Dawn
  if(Compiler.getDiagnostics().hasDiags()) {
    for(const auto& diags : Compiler.getDiagnostics().getQueue()) {
      context_->getDiagnostics().report(*diags);
    }
  }

  if(!DawnTranslationUnit || Compiler.getDiagnostics().hasErrors()) {
    DAWN_LOG(INFO) << "Errors in Dawn. Aborting";
    return;
  }

  // Do we generate code?
  if(!context_->getOptions().CodeGen) {
    DAWN_LOG(INFO) << "Skipping code-generation";
    return;
  }

  // Create new in-memory FS
  llvm::IntrusiveRefCntPtr<clang::vfs::InMemoryFileSystem> memFS(
      new clang::vfs::InMemoryFileSystem);
  clang::FileManager files(clang::FileSystemOptions(), memFS);
  clang::SourceManager sources(context_->getASTContext().getDiagnostics(), files);

  // Get a copy of the main-file's code
  std::unique_ptr<llvm::MemoryBuffer> generatedCode =
      llvm::MemoryBuffer::getMemBufferCopy(SM.getBufferData(SM.getMainFileID()));

  // Determine filename of generated file (by default we append "_gen" to the filename)
  std::string generatedFilename;
  if(context_->getOptions().OutputFile.empty())
    generatedFilename = llvm::StringRef(file_).split(".cpp").first.str() + "_gen.cpp";
  else {
    const auto& OutputFile = context_->getOptions().OutputFile;
    llvm::SmallVector<char, 40> path(OutputFile.data(), OutputFile.data() + OutputFile.size());
    llvm::sys::fs::make_absolute(path);
    generatedFilename.assign(path.data(), path.size());
  }

  // Create the generated file
  DAWN_LOG(INFO) << "Creating generated file " << generatedFilename;
  clang::FileID generatedFileID =
      createInMemoryFile(generatedFilename, generatedCode.get(), sources, files, memFS.get());

  // Replace clang DSL with gridtools
  clang::Rewriter rewriter(sources, context_->getASTContext().getLangOpts());
  for(const auto& stencilPair : stencilParser.getStencilMap()) {
    clang::CXXRecordDecl* stencilDecl = stencilPair.first;
    if(rewriter.ReplaceText(stencilDecl->getSourceRange(),
                            stencilPair.second->Attributes.has(dawn::sir::Attr::AK_NoCodeGen)
                                ? "class " + stencilPair.second->Name + "{}"
                                : DawnTranslationUnit->getStencils().at(stencilPair.second->Name)))
      context_->getDiagnostics().report(Diagnostics::err_fs_error) << dawn::format(
          "unable to replace stencil code at: %s", stencilDecl->getLocation().printToString(SM));
  }

  // Replace globals struct
  if(!globalsParser.isEmpty() && !DawnTranslationUnit->getGlobals().empty()) {
    if(rewriter.ReplaceText(globalsParser.getRecordDecl()->getSourceRange(),
                            DawnTranslationUnit->getGlobals()))
      context_->getDiagnostics().report(Diagnostics::err_fs_error)
          << dawn::format("unable to replace globals code at: %s",
                          globalsParser.getRecordDecl()->getLocation().printToString(SM));
  }

  // Remove the code from stencil-functions
  for(const auto& stencilFunPair : stencilParser.getStencilFunctionMap()) {
    clang::CXXRecordDecl* stencilFunDecl = stencilFunPair.first;
    rewriter.ReplaceText(stencilFunDecl->getSourceRange(),
                         "class " + stencilFunPair.second->Name + "{}");
  }

  std::string code;
  llvm::raw_string_ostream os(code);
  rewriter.getEditBuffer(generatedFileID).write(os);
  os.flush();

  // Format the file
  if(context_->getOptions().ClangFormat) {
    ClangFormat clangformat(context_);
    code = clangformat.format(code);
  }

  // Write file to disk
  DAWN_LOG(INFO) << "Writing file to disk... ";
  std::error_code ec;
  llvm::sys::fs::OpenFlags flags = llvm::sys::fs::OpenFlags::F_RW;
  llvm::raw_fd_ostream fout(generatedFilename, ec, flags);

  // Print a header
  fout << dawn::format("// gtclang (%s)\n// based on LLVM/Clang (%s), Dawn (%s)\n",
                       GTCLANG_FULL_VERSION_STR, LLVM_VERSION_STRING, DAWN_VERSION_STR);
  fout << "// Generated on " << currentDateTime() << "\n\n";

  // Add the macro definitions
  for(const auto& macroDefine : DawnTranslationUnit->getPPDefines())
    fout << macroDefine << "\n";

  fout.write(code.data(), code.size());
  if(ec.value())
    context_->getDiagnostics().report(Diagnostics::err_fs_error) << ec.message();
}

} // namespace gtclang
<commit_msg>Remove JSON serialization<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===//
//                         _       _
//                        | |     | |
//                    __ _| |_ ___| | __ _ _ __   __ _
//                   / _` | __/ __| |/ _` | '_ \ / _` |
//                  | (_| | || (__| | (_| | | | | (_| |
//                   \__, |\__\___|_|\__,_|_| |_|\__, | - GridTools Clang DSL
//                    __/ |                       __/ |
//                   |___/                       |___/
//
//
//  This file is distributed under the MIT License (MIT).
//  See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//

#include "gtclang/Frontend/GTClangASTConsumer.h"
#include "dawn/Compiler/DawnCompiler.h"
#include "dawn/SIR/SIR.h"
#include "dawn/Support/Config.h"
#include "dawn/Support/Format.h"
#include "dawn/Support/StringUtil.h"
#include "gtclang/Frontend/ClangFormat.h"
#include "gtclang/Frontend/GTClangASTAction.h"
#include "gtclang/Frontend/GTClangASTVisitor.h"
#include "gtclang/Frontend/GTClangContext.h"
#include "gtclang/Frontend/GlobalVariableParser.h"
#include "gtclang/Frontend/StencilParser.h"
#include "gtclang/Support/Config.h"
#include "gtclang/Support/FileUtil.h"
#include "gtclang/Support/Logger.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/Version.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include <cstdio>
#include <ctime>
#include <iostream>
#include <memory>
#include <system_error>

namespace gtclang {

/// @brief Get current time-stamp
static const std::string currentDateTime() {
  std::time_t now = time(0);
  char buf[80];
  std::strftime(buf, sizeof(buf), "%Y-%m-%d  %X", std::localtime(&now));
  return buf;
}

/// @brief Extract the DAWN options from the GTClang options
static std::unique_ptr<dawn::Options> makeDAWNOptions(const Options& options) {
  auto DAWNOptions = llvm::make_unique<dawn::Options>();
#define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \
  DAWNOptions->NAME = options.NAME;
#include "dawn/Compiler/Options.inc"
#undef OPT
  return DAWNOptions;
}

GTClangASTConsumer::GTClangASTConsumer(GTClangContext* context, const std::string& file,
                                       GTClangASTAction* parentAction)
    : context_(context), file_(file), parentAction_(parentAction) {
  DAWN_LOG(INFO) << "Creating ASTVisitor ... ";
  visitor_ = llvm::make_unique<GTClangASTVisitor>(context);
}

void GTClangASTConsumer::HandleTranslationUnit(clang::ASTContext& ASTContext) {
  context_->setASTContext(&ASTContext);
  if(!context_->hasDiagnostics())
    context_->setDiagnostics(&ASTContext.getDiagnostics());

  DAWN_LOG(INFO) << "Parsing translation unit... ";

  clang::TranslationUnitDecl* TU = ASTContext.getTranslationUnitDecl();
  for(auto& decl : TU->decls())
    visitor_->TraverseDecl(decl);

  DAWN_LOG(INFO) << "Done parsing translation unit";

  if(context_->getASTContext().getDiagnostics().hasErrorOccurred()) {
    DAWN_LOG(INFO) << "Erros occurred. Aborting";
    return;
  }

  DAWN_LOG(INFO) << "Generating SIR ... ";
  auto& SM = context_->getSourceManager();

  // Assemble SIR
  std::shared_ptr<dawn::SIR> SIR = std::make_shared<dawn::SIR>();
  SIR->Filename = SM.getFileEntryForID(SM.getMainFileID())->getName();

  const StencilParser& stencilParser = visitor_->getStencilParser();

  for(const auto& stencilPair : stencilParser.getStencilMap()) {
    SIR->Stencils.emplace_back(stencilPair.second);
    SIR->Stencils.back()->Attributes = context_->getStencilAttribute(stencilPair.second->Name);
  }

  for(const auto& stencilPair : stencilParser.getStencilFunctionMap()) {
    SIR->StencilFunctions.emplace_back(stencilPair.second);
    SIR->StencilFunctions.back()->Attributes =
        context_->getStencilAttribute(stencilPair.second->Name);
  }

  const GlobalVariableParser& globalsParser = visitor_->getGlobalVariableParser();
  SIR->GlobalVariableMap = globalsParser.getGlobalVariableMap();

  if(context_->getOptions().DumpSIR) {
    SIR->dump();
  }
  parentAction_->setSIR(SIR);

  // Set the backend
  dawn::DawnCompiler::CodeGenKind codeGen = dawn::DawnCompiler::CG_GTClang;
  if(context_->getOptions().Backend == "gridtools")
    codeGen = dawn::DawnCompiler::CG_GTClang;
  else if(context_->getOptions().Backend == "c++")
    codeGen = dawn::DawnCompiler::CG_GTClangNaiveCXX;
  else {
    context_->getDiagnostics().report(Diagnostics::err_invalid_option)
        << ("-backend=" + context_->getOptions().Backend)
        << dawn::RangeToString(", ", "", "")(std::vector<std::string>{"gridtools", "c++"});
  }

  // Compile the SIR to GridTools
  dawn::DawnCompiler Compiler(makeDAWNOptions(context_->getOptions()).get());
  std::unique_ptr<dawn::TranslationUnit> DawnTranslationUnit = Compiler.compile(SIR.get(), codeGen);

  // Report diagnostics from Dawn
  if(Compiler.getDiagnostics().hasDiags()) {
    for(const auto& diags : Compiler.getDiagnostics().getQueue()) {
      context_->getDiagnostics().report(*diags);
    }
  }

  if(!DawnTranslationUnit || Compiler.getDiagnostics().hasErrors()) {
    DAWN_LOG(INFO) << "Errors in Dawn. Aborting";
    return;
  }

  // Do we generate code?
  if(!context_->getOptions().CodeGen) {
    DAWN_LOG(INFO) << "Skipping code-generation";
    return;
  }

  // Create new in-memory FS
  llvm::IntrusiveRefCntPtr<clang::vfs::InMemoryFileSystem> memFS(
      new clang::vfs::InMemoryFileSystem);
  clang::FileManager files(clang::FileSystemOptions(), memFS);
  clang::SourceManager sources(context_->getASTContext().getDiagnostics(), files);

  // Get a copy of the main-file's code
  std::unique_ptr<llvm::MemoryBuffer> generatedCode =
      llvm::MemoryBuffer::getMemBufferCopy(SM.getBufferData(SM.getMainFileID()));

  // Determine filename of generated file (by default we append "_gen" to the filename)
  std::string generatedFilename;
  if(context_->getOptions().OutputFile.empty())
    generatedFilename = llvm::StringRef(file_).split(".cpp").first.str() + "_gen.cpp";
  else {
    const auto& OutputFile = context_->getOptions().OutputFile;
    llvm::SmallVector<char, 40> path(OutputFile.data(), OutputFile.data() + OutputFile.size());
    llvm::sys::fs::make_absolute(path);
    generatedFilename.assign(path.data(), path.size());
  }

  // Create the generated file
  DAWN_LOG(INFO) << "Creating generated file " << generatedFilename;
  clang::FileID generatedFileID =
      createInMemoryFile(generatedFilename, generatedCode.get(), sources, files, memFS.get());

  // Replace clang DSL with gridtools
  clang::Rewriter rewriter(sources, context_->getASTContext().getLangOpts());
  for(const auto& stencilPair : stencilParser.getStencilMap()) {
    clang::CXXRecordDecl* stencilDecl = stencilPair.first;
    if(rewriter.ReplaceText(stencilDecl->getSourceRange(),
                            stencilPair.second->Attributes.has(dawn::sir::Attr::AK_NoCodeGen)
                                ? "class " + stencilPair.second->Name + "{}"
                                : DawnTranslationUnit->getStencils().at(stencilPair.second->Name)))
      context_->getDiagnostics().report(Diagnostics::err_fs_error) << dawn::format(
          "unable to replace stencil code at: %s", stencilDecl->getLocation().printToString(SM));
  }

  // Replace globals struct
  if(!globalsParser.isEmpty() && !DawnTranslationUnit->getGlobals().empty()) {
    if(rewriter.ReplaceText(globalsParser.getRecordDecl()->getSourceRange(),
                            DawnTranslationUnit->getGlobals()))
      context_->getDiagnostics().report(Diagnostics::err_fs_error)
          << dawn::format("unable to replace globals code at: %s",
                          globalsParser.getRecordDecl()->getLocation().printToString(SM));
  }

  // Remove the code from stencil-functions
  for(const auto& stencilFunPair : stencilParser.getStencilFunctionMap()) {
    clang::CXXRecordDecl* stencilFunDecl = stencilFunPair.first;
    rewriter.ReplaceText(stencilFunDecl->getSourceRange(),
                         "class " + stencilFunPair.second->Name + "{}");
  }

  std::string code;
  llvm::raw_string_ostream os(code);
  rewriter.getEditBuffer(generatedFileID).write(os);
  os.flush();

  // Format the file
  if(context_->getOptions().ClangFormat) {
    ClangFormat clangformat(context_);
    code = clangformat.format(code);
  }

  // Write file to disk
  DAWN_LOG(INFO) << "Writing file to disk... ";
  std::error_code ec;
  llvm::sys::fs::OpenFlags flags = llvm::sys::fs::OpenFlags::F_RW;
  llvm::raw_fd_ostream fout(generatedFilename, ec, flags);

  // Print a header
  fout << dawn::format("// gtclang (%s)\n// based on LLVM/Clang (%s), Dawn (%s)\n",
                       GTCLANG_FULL_VERSION_STR, LLVM_VERSION_STRING, DAWN_VERSION_STR);
  fout << "// Generated on " << currentDateTime() << "\n\n";

  // Add the macro definitions
  for(const auto& macroDefine : DawnTranslationUnit->getPPDefines())
    fout << macroDefine << "\n";

  fout.write(code.data(), code.size());
  if(ec.value())
    context_->getDiagnostics().report(Diagnostics::err_fs_error) << ec.message();
}

} // namespace gtclang
<|endoftext|>


<commit_before>//===-- Debug.cpp - An easy way to add debug output to your code ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a handle way of adding debugging information to your
// code, without it being enabled all of the time, and without having to add
// command line options to enable it.
//
// In particular, just wrap your code with the DEBUG() macro, and it will be
// enabled automatically if you specify '-debug' on the command-line.
// Alternatively, you can also use the SET_DEBUG_TYPE("foo") macro to specify
// that your debug code belongs to class "foo".  Then, on the command line, you
// can specify '-debug-only=foo' to enable JUST the debug information for the
// foo class.
//
// When compiling in release mode, the -debug-* options and all code in DEBUG()
// statements disappears, so it does not effect the runtime of the code.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/circular_raw_ostream.h"
#include "llvm/System/Signals.h"

using namespace llvm;

// All Debug.h functionality is a no-op in NDEBUG mode.
#ifndef NDEBUG
bool llvm::DebugFlag;  // DebugFlag - Exported boolean set by the -debug option

// -debug - Command line option to enable the DEBUG statements in the passes.
// This flag may only be enabled in debug builds.
static cl::opt<bool, true>
Debug("debug", cl::desc("Enable debug output"), cl::Hidden,
      cl::location(DebugFlag));

// -debug-buffer-size - Buffer the last N characters of debug output
//until program termination.
static cl::opt<unsigned>
DebugBufferSize("debug-buffer-size",
                cl::desc("Buffer the last N characters of debug output"
                         "until program termination. "
                         "[default 0 -- immediate print-out]"),
                cl::Hidden,
                cl::init(0));

static std::string CurrentDebugType;
static struct DebugOnlyOpt {
  void operator=(const std::string &Val) const {
    DebugFlag |= !Val.empty();
    CurrentDebugType = Val;
  }
} DebugOnlyOptLoc;

static cl::opt<DebugOnlyOpt, true, cl::parser<std::string> >
DebugOnly("debug-only", cl::desc("Enable a specific type of debug output"),
          cl::Hidden, cl::value_desc("debug string"),
          cl::location(DebugOnlyOptLoc), cl::ValueRequired);

// Signal handlers - dump debug output on termination.
static void debug_user_sig_handler(void *Cookie)
{
  // This is a bit sneaky.  Since this is under #ifndef NDEBUG, we
  // know that debug mode is enabled and dbgs() really is a
  // circular_raw_ostream.  If NDEBUG is defined, then dbgs() ==
  // errs() but this will never be invoked.
  llvm::circular_raw_ostream *dbgout =
    static_cast<llvm::circular_raw_ostream *>(&llvm::dbgs());
  dbgout->flushBufferWithBanner();
}

// isCurrentDebugType - Return true if the specified string is the debug type
// specified on the command line, or if none was specified on the command line
// with the -debug-only=X option.
//
bool llvm::isCurrentDebugType(const char *DebugType) {
  return CurrentDebugType.empty() || DebugType == CurrentDebugType;
}

/// SetCurrentDebugType - Set the current debug type, as if the -debug-only=X
/// option were specified.  Note that DebugFlag also needs to be set to true for
/// debug output to be produced.
///
void llvm::SetCurrentDebugType(const char *Type) {
  CurrentDebugType = Type;
}

/// dbgs - Return a circular-buffered debug stream.
raw_ostream &llvm::dbgs() {
  // Do one-time initialization in a thread-safe way.
  static struct dbgstream {
    circular_raw_ostream strm;

    dbgstream() :
        strm(errs(), "*** Debug Log Output ***\n",
             (!EnableDebugBuffering || !DebugFlag) ? 0 : DebugBufferSize) {
      if (EnableDebugBuffering && DebugFlag && DebugBufferSize != 0)
        // TODO: Add a handler for SIGUSER1-type signals so the user can
        // force a debug dump.
        sys::AddSignalHandler(&debug_user_sig_handler, 0);
      // Otherwise we've already set the debug stream buffer size to
      // zero, disabling buffering.
    }
  } thestrm;

  return thestrm.strm;
}

#else
// Avoid "has no symbols" warning.
namespace llvm {
  /// dbgs - Return dbgs().
  raw_ostream &dbgs() {
    return dbgs();
  }
}

#endif

/// EnableDebugBuffering - Turn on signal handler installation.
///
bool llvm::EnableDebugBuffering = false;
<commit_msg><commit_after>//===-- Debug.cpp - An easy way to add debug output to your code ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a handle way of adding debugging information to your
// code, without it being enabled all of the time, and without having to add
// command line options to enable it.
//
// In particular, just wrap your code with the DEBUG() macro, and it will be
// enabled automatically if you specify '-debug' on the command-line.
// Alternatively, you can also use the SET_DEBUG_TYPE("foo") macro to specify
// that your debug code belongs to class "foo".  Then, on the command line, you
// can specify '-debug-only=foo' to enable JUST the debug information for the
// foo class.
//
// When compiling in release mode, the -debug-* options and all code in DEBUG()
// statements disappears, so it does not effect the runtime of the code.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/circular_raw_ostream.h"
#include "llvm/System/Signals.h"

using namespace llvm;

// All Debug.h functionality is a no-op in NDEBUG mode.
#ifndef NDEBUG
bool llvm::DebugFlag;  // DebugFlag - Exported boolean set by the -debug option

// -debug - Command line option to enable the DEBUG statements in the passes.
// This flag may only be enabled in debug builds.
static cl::opt<bool, true>
Debug("debug", cl::desc("Enable debug output"), cl::Hidden,
      cl::location(DebugFlag));

// -debug-buffer-size - Buffer the last N characters of debug output
//until program termination.
static cl::opt<unsigned>
DebugBufferSize("debug-buffer-size",
                cl::desc("Buffer the last N characters of debug output"
                         "until program termination. "
                         "[default 0 -- immediate print-out]"),
                cl::Hidden,
                cl::init(0));

static std::string CurrentDebugType;
static struct DebugOnlyOpt {
  void operator=(const std::string &Val) const {
    DebugFlag |= !Val.empty();
    CurrentDebugType = Val;
  }
} DebugOnlyOptLoc;

static cl::opt<DebugOnlyOpt, true, cl::parser<std::string> >
DebugOnly("debug-only", cl::desc("Enable a specific type of debug output"),
          cl::Hidden, cl::value_desc("debug string"),
          cl::location(DebugOnlyOptLoc), cl::ValueRequired);

// Signal handlers - dump debug output on termination.
static void debug_user_sig_handler(void *Cookie)
{
  // This is a bit sneaky.  Since this is under #ifndef NDEBUG, we
  // know that debug mode is enabled and dbgs() really is a
  // circular_raw_ostream.  If NDEBUG is defined, then dbgs() ==
  // errs() but this will never be invoked.
  llvm::circular_raw_ostream *dbgout =
    static_cast<llvm::circular_raw_ostream *>(&llvm::dbgs());
  dbgout->flushBufferWithBanner();
}

// isCurrentDebugType - Return true if the specified string is the debug type
// specified on the command line, or if none was specified on the command line
// with the -debug-only=X option.
//
bool llvm::isCurrentDebugType(const char *DebugType) {
  return CurrentDebugType.empty() || DebugType == CurrentDebugType;
}

/// SetCurrentDebugType - Set the current debug type, as if the -debug-only=X
/// option were specified.  Note that DebugFlag also needs to be set to true for
/// debug output to be produced.
///
void llvm::SetCurrentDebugType(const char *Type) {
  CurrentDebugType = Type;
}

/// dbgs - Return a circular-buffered debug stream.
raw_ostream &llvm::dbgs() {
  // Do one-time initialization in a thread-safe way.
  static struct dbgstream {
    circular_raw_ostream strm;

    dbgstream() :
        strm(errs(), "*** Debug Log Output ***\n",
             (!EnableDebugBuffering || !DebugFlag) ? 0 : DebugBufferSize) {
      if (EnableDebugBuffering && DebugFlag && DebugBufferSize != 0)
        // TODO: Add a handler for SIGUSER1-type signals so the user can
        // force a debug dump.
        sys::AddSignalHandler(&debug_user_sig_handler, 0);
      // Otherwise we've already set the debug stream buffer size to
      // zero, disabling buffering so it will output directly to errs().
    }
  } thestrm;

  return thestrm.strm;
}

#else
// Avoid "has no symbols" warning.
namespace llvm {
  /// dbgs - Return dbgs().
  raw_ostream &dbgs() {
    return dbgs();
  }
}

#endif

/// EnableDebugBuffering - Turn on signal handler installation.
///
bool llvm::EnableDebugBuffering = false;
<|endoftext|>