<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: databaseobjectview.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2006-10-05 13:05:24 $
 *
 *  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 DBACCESS_DATABASE_OBJECT_VIEW_HXX
#define DBACCESS_DATABASE_OBJECT_VIEW_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_APPLICATION_XDATABASEDOCUMENTUI_HPP_
#include <com/sun/star/sdb/application/XDatabaseDocumentUI.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#include <boost/shared_ptr.hpp>

// .........................................................................
namespace dbaui
{
// .........................................................................
    /** encapsulates access to the view of a database object.

        @todo
            this is to be merged with the OLinkedDocumentAccess class
    */
    class DatabaseObjectView
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                        m_xORB;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XComponentLoader >
                        m_xFrameLoader;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >
                        m_xApplication;
        ::rtl::OUString m_sComponentURL;

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
                doDispatch(
                    const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments
                );

    protected:
        /** creates the desired view

            The default implementation will call <member>fillDispatchArgs</member>, followed
            by <member>doDispatch</member>.

            @param _rDataSource
                the data source, as passed to the <member>createNew</member> or <member>openExisting</member> method.
            @param _rObjectName
                the name of the object for which the view is to be opened,
                or an empty string if a view for a new object should be created.
            @param _rCreationArgs
                the arguments for the view's creation
        */
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > doCreateView(
            const ::com::sun::star::uno::Any& _rDataSource,
            const ::rtl::OUString& _rObjectName,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rCreationArgs
        );

        virtual void fillDispatchArgs(
                    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
                    const ::com::sun::star::uno::Any& _rDataSource,
                    const ::rtl::OUString& _rObjectName
                );

        const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >&
                getApplicationUI() const { return m_xApplication; }
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                getConnection() const;

    public:
        DatabaseObjectView(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            const ::rtl::OUString& _rComponentURL
        );
        virtual ~DatabaseObjectView(){}

        /** sets the target frame into which the view should be loaded.

            By default, the view is loaded into a top-level frame not being part of the
            Desktop.
        */
        void setTargetFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame )
        {
            m_xFrameLoader.set( _rxFrame, ::com::sun::star::uno::UNO_QUERY );
        }

        /** opens a view for a to-be-created object

            @param _xDataSource
                the data source for which a new object is to be created
            @return
                the controller of the newly created document
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
            createNew(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource >& _xDataSource
            );

        /** opens a view for an existent object

            @param _xDataSource
                the data source for which a new object is to be created
            @param _rObjectName
                the name of the object to be edited
            @param  _rArgs
                Additional settings which should be forwarded to the frame
            @return
                the frame into which the view has been loaded
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
            openExisting(
                const ::com::sun::star::uno::Any& _aDataSource,
                const ::rtl::OUString& _rName,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArgs
            );
    };

    //======================================================================
    //= QueryDesigner
    //======================================================================
    class QueryDesigner : public DatabaseObjectView
    {
    protected:
        sal_Bool    m_bCreateView;
        sal_Bool    m_bPreferSQLView;

    protected:
        virtual void fillDispatchArgs(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
            const ::com::sun::star::uno::Any& _aDataSource,
            const ::rtl::OUString& _rObjectName
        );

    public:
        QueryDesigner(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            sal_Bool _bCreateView,
            sal_Bool _bPreferSQLView
        );
    };

    //======================================================================
    //= TableDesigner
    //======================================================================
    class TableDesigner : public DatabaseObjectView
    {
    protected:
        virtual void fillDispatchArgs(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
            const ::com::sun::star::uno::Any& _aDataSource,
            const ::rtl::OUString& _rObjectName
        );

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > doCreateView(
            const ::com::sun::star::uno::Any& _rDataSource,
            const ::rtl::OUString& _rObjectName,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rCreationArgs
        );

    public:
        TableDesigner(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication
        );

    private:
        /** retrieves the table designer component as provided by the connection, if any
            @param  _rTableName
                the name of the table for which a designer is to be obtained
            @return
                the designer component, as provided by the connection, or <NULL/>, if the connection
                does not provide a specialized designer.
            @see com::sun::star::sdb::application::XTableUIProvider
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                impl_getConnectionProvidedDesigner_nothrow( const ::rtl::OUString& _rTableName );
    };

    //======================================================================
    //= ResultSetBrowser
    //======================================================================
    class ResultSetBrowser : public DatabaseObjectView
    {
    private:
        sal_Bool    m_bTable;

    protected:
        virtual void fillDispatchArgs(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
            const ::com::sun::star::uno::Any& _aDataSource,
            const ::rtl::OUString& _rQualifiedName
        );

    public:
        ResultSetBrowser(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            sal_Bool _bTable
        );

    };
    //======================================================================
    //= RelationDesigner
    //======================================================================
    class RelationDesigner : public DatabaseObjectView
    {
    public:
        RelationDesigner(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication
        );
    };

// .........................................................................
}   // namespace dbaui
// .........................................................................

#endif // DBACCESS_DATABASE_OBJECT_VIEW_HXX

<commit_msg>INTEGRATION: CWS fwkdbdesign01 (1.2.70); FILE MERGED 2007/02/26 11:42:54 as 1.2.70.1: #i74541# create designer as sub frames of db-model-frame<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: databaseobjectview.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ihi $ $Date: 2007-04-16 16:27:23 $
 *
 *  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 DBACCESS_DATABASE_OBJECT_VIEW_HXX
#define DBACCESS_DATABASE_OBJECT_VIEW_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_APPLICATION_XDATABASEDOCUMENTUI_HPP_
#include <com/sun/star/sdb/application/XDatabaseDocumentUI.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#include <boost/shared_ptr.hpp>

// .........................................................................
namespace dbaui
{
// .........................................................................
    /** encapsulates access to the view of a database object.

        @todo
            this is to be merged with the OLinkedDocumentAccess class
    */
    class DatabaseObjectView
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                        m_xORB;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >
                        m_xParentFrame;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XComponentLoader >
                        m_xFrameLoader;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >
                        m_xApplication;
        ::rtl::OUString m_sComponentURL;

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
                doDispatch(
                    const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments
                );

    protected:
        /** creates the desired view

            The default implementation will call <member>fillDispatchArgs</member>, followed
            by <member>doDispatch</member>.

            @param _rDataSource
                the data source, as passed to the <member>createNew</member> or <member>openExisting</member> method.
            @param _rObjectName
                the name of the object for which the view is to be opened,
                or an empty string if a view for a new object should be created.
            @param _rCreationArgs
                the arguments for the view's creation
        */
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > doCreateView(
            const ::com::sun::star::uno::Any& _rDataSource,
            const ::rtl::OUString& _rObjectName,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rCreationArgs
        );

        virtual void fillDispatchArgs(
                    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
                    const ::com::sun::star::uno::Any& _rDataSource,
                    const ::rtl::OUString& _rObjectName
                );

        const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >&
                getApplicationUI() const { return m_xApplication; }
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                getConnection() const;

    public:
        DatabaseObjectView(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxParentFrame,
            const ::rtl::OUString& _rComponentURL
        );
        virtual ~DatabaseObjectView(){}

        /** sets the target frame into which the view should be loaded.

            By default, the view is loaded into a top-level frame not being part of the
            Desktop.
        */
        void setTargetFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame )
        {
            m_xFrameLoader.set( _rxFrame, ::com::sun::star::uno::UNO_QUERY );
        }

        /** opens a view for a to-be-created object

            @param _xDataSource
                the data source for which a new object is to be created
            @return
                the controller of the newly created document
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
            createNew(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource >& _xDataSource
            );

        /** opens a view for an existent object

            @param _xDataSource
                the data source for which a new object is to be created
            @param _rObjectName
                the name of the object to be edited
            @param  _rArgs
                Additional settings which should be forwarded to the frame
            @return
                the frame into which the view has been loaded
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
            openExisting(
                const ::com::sun::star::uno::Any& _aDataSource,
                const ::rtl::OUString& _rName,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArgs
            );
    };

    //======================================================================
    //= QueryDesigner
    //======================================================================
    class QueryDesigner : public DatabaseObjectView
    {
    protected:
        sal_Bool    m_bCreateView;
        sal_Bool    m_bPreferSQLView;

    protected:
        virtual void fillDispatchArgs(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
            const ::com::sun::star::uno::Any& _aDataSource,
            const ::rtl::OUString& _rObjectName
        );

    public:
        QueryDesigner(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxParentFrame,
            sal_Bool _bCreateView,
            sal_Bool _bPreferSQLView
        );
    };

    //======================================================================
    //= TableDesigner
    //======================================================================
    class TableDesigner : public DatabaseObjectView
    {
    protected:
        virtual void fillDispatchArgs(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
            const ::com::sun::star::uno::Any& _aDataSource,
            const ::rtl::OUString& _rObjectName
        );

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > doCreateView(
            const ::com::sun::star::uno::Any& _rDataSource,
            const ::rtl::OUString& _rObjectName,
            const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rCreationArgs
        );

    public:
        TableDesigner(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxParentFrame
        );

    private:
        /** retrieves the table designer component as provided by the connection, if any
            @param  _rTableName
                the name of the table for which a designer is to be obtained
            @return
                the designer component, as provided by the connection, or <NULL/>, if the connection
                does not provide a specialized designer.
            @see com::sun::star::sdb::application::XTableUIProvider
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                impl_getConnectionProvidedDesigner_nothrow( const ::rtl::OUString& _rTableName );
    };

    //======================================================================
    //= ResultSetBrowser
    //======================================================================
    class ResultSetBrowser : public DatabaseObjectView
    {
    private:
        sal_Bool    m_bTable;

    protected:
        virtual void fillDispatchArgs(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rDispatchArguments,
            const ::com::sun::star::uno::Any& _aDataSource,
            const ::rtl::OUString& _rQualifiedName
        );

    public:
        ResultSetBrowser(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxParentFrame,
            sal_Bool _bTable
        );

    };
    //======================================================================
    //= RelationDesigner
    //======================================================================
    class RelationDesigner : public DatabaseObjectView
    {
    public:
        RelationDesigner(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::application::XDatabaseDocumentUI >& _rxApplication,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxParentFrame
        );
    };

// .........................................................................
}   // namespace dbaui
// .........................................................................

#endif // DBACCESS_DATABASE_OBJECT_VIEW_HXX

<|endoftext|>


<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once

#ifndef ORK_ORK_HPP
#	error This header can only be included from ork/ork.hpp!
#endif

#if defined _MSC_VER
#	define ORK_MSC _MSC_VER
#	define ORK_GCC 0
#elif define __GNUC__
#	define ORK_MSC 0
#	define ORK_GCC (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#else
#	error Compiler not supported!
#endif

#if defined _WIN32 && !ORK_MSC//We only support native compilers
#error Cygwin not supported
#endif

#if ORK_MSC && ORK_MSC < 1800
#	error Visual Studio 2012 or greater required
#endif
#if ORK_GCC && ORK_GCC < 40300
#	error GCC 4.3 or greater required
#endif

#if !defined ORK_DEBUG
#	if defined DEBUG || defined _DEBUG
#		if defined NDEBUG  || defined _NDEBUG
#			error Cannot define debug and not debug
#		endif
#		define ORK_DEBUG 1
#		define ORK_NDEBUG 0
#	else
#		define ORK_DEBUG 0
#		define ORK_NDEBUG 1
#	endif
#endif

#ifndef ORK_CALL
#	if ORK_MSC
#		define ORK_CALL __fastcall//Default for x64, __cdecl is default for x86
#	elif ORK_GCC
#		define ORK_CALL
#	else
#		error Compiler not supported
#	endif
#endif

/*
ORK_ORK versions are for internal use by ork
Plain versions are for use by clients
*/
#ifndef ORK_ORK_API
#	if !ORK_ORK_DLL
#		define ORK_ORK_API
#		define ORK_ORK_LOCAL
#	elif ORK_MSC
#		if ORK_BUILD_ORK//Define to compile Ork DLL
#			define ORK_ORK_API __declspec(dllexport)
#		else//Default for using DLL
#			define ORK_ORK_API __declspec(dllimport)
#		endif
#		define ORK_ORK_LOCAL//Default in VS
#	elif ORK_GCC
#		define ORK_ORK_API __attribute__ ((visibility ("default")))
#		define ORK_ORK_LOCAL  __attribute__ ((visibility ("hidden")))//Too bad this is not default
#	else
#		error Compiler not supported
#	endif
#endif
#ifndef ORK_API
#	if !ORK_DLL
#		define ORK_API
#		define ORK_LOCAL
#	elif ORK_MSC
#		if ORK_BUILD_DLL//Define to compile client DLL
#			define ORK_API __declspec(dllexport)
#		else//Default for using DLL
#			define ORK_API __declspec(dllimport)
#		endif
#		define ORK_LOCAL//Default in VS
#	elif ORK_GCC
#		define ORK_API __attribute__ ((visibility ("default")))
#		define ORK_LOCAL  __attribute__ ((visibility ("hidden")))//Too bad this is not default
#	else
#		error Compiler not supported
#	endif
#endif

/*
For template exports
*/
#ifndef ORK_EXT_TEMP
#	if ORK_ORK_DLL && !ORK_BUILD_ORK && ORK_MSC
#		define ORK_EXT_TEMP extern template
#	else
#		define ORK_EXT_TEMP template
#	endif
#endif

/*
Convenience macro for functions
*/
#ifndef ORK_ORK_EXT//External
#	define ORK_ORK_EXT(RETVAL) ORK_ORK_API RETVAL ORK_CALL
#endif
#ifndef ORK_ORK_INT//Internal
#	define ORK_ORK_INT(RETVAL) ORK_ORK_LOCAL RETVAL ORK_CALL
#endif
#ifndef ORK_EXT//External
#	define ORK_EXT(RETVAL) ORK_API RETVAL ORK_CALL
#endif
#ifndef ORK_INT//Internal
#	define ORK_INT(RETVAL) ORK_LOCAL RETVAL ORK_CALL
#endif

namespace ork {

}//namespace ork
<commit_msg>Added a macro for extern variables<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once

#ifndef ORK_ORK_HPP
#	error This header can only be included from ork/ork.hpp!
#endif

#if defined _MSC_VER
#	define ORK_MSC _MSC_VER
#	define ORK_GCC 0
#elif define __GNUC__
#	define ORK_MSC 0
#	define ORK_GCC (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#else
#	error Compiler not supported!
#endif

#if defined _WIN32 && !ORK_MSC//We only support native compilers
#error Cygwin not supported
#endif

#if ORK_MSC && ORK_MSC < 1800
#	error Visual Studio 2012 or greater required
#endif
#if ORK_GCC && ORK_GCC < 40300
#	error GCC 4.3 or greater required
#endif

#if !defined ORK_DEBUG
#	if defined DEBUG || defined _DEBUG
#		if defined NDEBUG  || defined _NDEBUG
#			error Cannot define debug and not debug
#		endif
#		define ORK_DEBUG 1
#		define ORK_NDEBUG 0
#	else
#		define ORK_DEBUG 0
#		define ORK_NDEBUG 1
#	endif
#endif

#ifndef ORK_CALL
#	if ORK_MSC
#		define ORK_CALL __fastcall//Default for x64, __cdecl is default for x86
#	elif ORK_GCC
#		define ORK_CALL
#	else
#		error Compiler not supported
#	endif
#endif

/*
ORK_ORK versions are for internal use by ork
Plain versions are for use by clients
*/
#ifndef ORK_ORK_API
#	if !ORK_ORK_DLL
#		define ORK_ORK_API
#		define ORK_ORK_LOCAL
#	elif ORK_MSC
#		if ORK_BUILD_ORK//Define to compile Ork DLL
#			define ORK_ORK_API __declspec(dllexport)
#		else//Default for using DLL
#			define ORK_ORK_API __declspec(dllimport)
#		endif
#		define ORK_ORK_LOCAL//Default in VS
#	elif ORK_GCC
#		define ORK_ORK_API __attribute__ ((visibility ("default")))
#		define ORK_ORK_LOCAL  __attribute__ ((visibility ("hidden")))//Too bad this is not default
#	else
#		error Compiler not supported
#	endif
#endif
#ifndef ORK_API
#	if !ORK_DLL
#		define ORK_API
#		define ORK_LOCAL
#	elif ORK_MSC
#		if ORK_BUILD_DLL//Define to compile client DLL
#			define ORK_API __declspec(dllexport)
#		else//Default for using DLL
#			define ORK_API __declspec(dllimport)
#		endif
#		define ORK_LOCAL//Default in VS
#	elif ORK_GCC
#		define ORK_API __attribute__ ((visibility ("default")))
#		define ORK_LOCAL  __attribute__ ((visibility ("hidden")))//Too bad this is not default
#	else
#		error Compiler not supported
#	endif
#endif

/*
For global exports
*/
#ifndef ORK_EXTERN
#	define ORK_EXTERN extern ORK_API
#endif

/*
For template exports
*/
#ifndef ORK_EXT_TEMP
#	if !ORK_BUILD_ORK && ORK_MSC
#		define ORK_EXT_TEMP extern template
#	else
#		define ORK_EXT_TEMP template
#	endif
#endif

/*
Convenience macro for functions
*/
#ifndef ORK_ORK_EXT//External
#	define ORK_ORK_EXT(RETVAL) ORK_ORK_API RETVAL ORK_CALL
#endif
#ifndef ORK_ORK_INT//Internal
#	define ORK_ORK_INT(RETVAL) ORK_ORK_LOCAL RETVAL ORK_CALL
#endif
#ifndef ORK_EXT//External
#	define ORK_EXT(RETVAL) ORK_API RETVAL ORK_CALL
#endif
#ifndef ORK_INT//Internal
#	define ORK_INT(RETVAL) ORK_LOCAL RETVAL ORK_CALL
#endif

namespace ork {

}//namespace ork
<|endoftext|>


<commit_before>
#include "svc_createstringtable.h"
#include "base/bitfile.h"
#include "base/jsonfile.h"
#include "netmath.h"
#include "netcontants.h"

namespace NetHandlers
{
    bool SVC_CreateStringTable_BitRead_Internal(BitRead& bitbuf, SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        if (bitbuf.PeekUBitLong(8) == ':')
        {
            data->isFileNames = true;
            bitbuf.ReadByte();
        }
        else
        {
            data->isFileNames = false;
        }
        bitbuf.ReadString(data->tableName, sizeof(data->tableName));
        data->maxEntries = bitbuf.ReadWord();
        data->numEntries = bitbuf.ReadUBitLong(math::log2(data->maxEntries) + 1);
        if (context.protocol > 23)
        {
            data->dataLengthInBits = bitbuf.ReadVarInt32();
        }
        else
        {
            data->dataLengthInBits = bitbuf.ReadUBitLong(NET_MAX_PAYLOAD_BITS + 1);
        }
        data->isUserDataFixedSize = bitbuf.ReadOneBit() != 0;
        if (data->isUserDataFixedSize)
        {
            data->userDataSize = bitbuf.ReadUBitLong(12);
            data->userDataSizeBits = bitbuf.ReadUBitLong(4);
        }
        else
        {
            data->userDataSize = 0;
            data->userDataSizeBits = 0;
        }
        if (context.protocol > 14)
        {
            data->unk1 = bitbuf.ReadOneBit() != 0;
        }
        data->data.reset(new uint8_t[math::BitsToBytes(data->dataLengthInBits)]);
        bitbuf.ReadBits(data->data.get(), data->dataLengthInBits);
        return !bitbuf.IsOverflowed();
    }

    bool SVC_CreateStringTable_BitWrite_Internal(BitWrite& bitbuf, const SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        if (data->isFileNames)
        {
            bitbuf.WriteByte(':');
        }
        bitbuf.WriteString(data->tableName);
        bitbuf.WriteWord(data->maxEntries);
        bitbuf.WriteUBitLong(data->numEntries, math::log2(data->maxEntries) + 1);
        if (context.protocol > 23)
        {
            bitbuf.WriteVarInt32(data->dataLengthInBits);
        }
        else
        {
            bitbuf.WriteUBitLong(data->dataLengthInBits, NET_MAX_PAYLOAD_BITS + 1);
        }
        bitbuf.WriteOneBit(data->isUserDataFixedSize);
        if (data->isUserDataFixedSize)
        {
            bitbuf.WriteUBitLong(data->userDataSize, 12);
            bitbuf.WriteUBitLong(data->userDataSizeBits, 4);
        }
        if (context.protocol > 14)
        {
            bitbuf.WriteOneBit(data->unk1);
        }
        bitbuf.WriteBits(data->data.get(), data->dataLengthInBits);
        return !bitbuf.IsOverflowed();
    }

    bool SVC_CreateStringTable_JsonRead_Internal(JsonRead& jsonbuf, SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        base::JsonReaderObject reader = jsonbuf.ParseObject();
        assert(!reader.HasReadError());
        data->isFileNames = reader.ReadBool("isFilenames");
        reader.ReadString("tableName", data->tableName, sizeof(data->tableName));
        data->maxEntries = reader.ReadUInt32("maxEntries");
        data->numEntries = reader.ReadUInt32("numEntries");
        data->dataLengthInBits = reader.ReadInt32("dataLengthInBits");
        data->isUserDataFixedSize = reader.ReadBool("isUserDataFixedSize");
        data->userDataSize = reader.ReadUInt32("userDataSize");
        data->userDataSizeBits = reader.ReadUInt32("userDataSizeBits");
        if (context.protocol > 14)
        {
            data->unk1 = reader.ReadBool("unk1");
        }
        data->data.reset(new uint8_t[math::BitsToBytes(data->dataLengthInBits)]);
        reader.ReadBits("data", data->data.get(), data->dataLengthInBits);
        return !reader.HasReadError();
    }

    bool SVC_CreateStringTable_JsonWrite_Internal(JsonWrite& jsonbuf, const SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        jsonbuf.Reset();
        jsonbuf.StartObject();
        jsonbuf.WriteBool("isFilenames", data->isFileNames);
        jsonbuf.WriteString("tableName", data->tableName);
        jsonbuf.WriteUInt32("maxEntries", data->maxEntries);
        jsonbuf.WriteUInt32("numEntries", data->numEntries);
        jsonbuf.WriteInt32("dataLengthInBits", data->dataLengthInBits);
        jsonbuf.WriteBool("isUserDataFixedSize", data->isUserDataFixedSize);
        jsonbuf.WriteUInt32("userDataSize", data->userDataSize);
        jsonbuf.WriteUInt32("userDataSizeBits", data->userDataSizeBits);
        if (context.protocol > 14)
        {
            jsonbuf.WriteBool("unk1", data->unk1);
        }
        jsonbuf.WriteBits("data", data->data.get(), data->dataLengthInBits);
        jsonbuf.EndObject();
        return jsonbuf.IsComplete();
    }

    void SVC_CreateStringTable_ToString_Internal(std::ostringstream& out, NetMsg::SVC_CreateStringTable* data)
    {
        out << "svc_CreateStringTable: table " << data->tableName
            << ", entries " << data->numEntries
            << ", bytes " << math::BitsToBytes(data->dataLengthInBits)
            << " userdatasize " << data->userDataSize
            << " userdatabits " << static_cast<uint32_t>(data->userDataSizeBits);
    }
}
<commit_msg>Use old NET_MAX_PAYLOAD_BITS constant for SVC_CreateStringTable<commit_after>
#include "svc_createstringtable.h"
#include "base/bitfile.h"
#include "base/jsonfile.h"
#include "netmath.h"
#include "netcontants.h"

namespace NetHandlers
{
    bool SVC_CreateStringTable_BitRead_Internal(BitRead& bitbuf, SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        if (bitbuf.PeekUBitLong(8) == ':')
        {
            data->isFileNames = true;
            bitbuf.ReadByte();
        }
        else
        {
            data->isFileNames = false;
        }
        bitbuf.ReadString(data->tableName, sizeof(data->tableName));
        data->maxEntries = bitbuf.ReadWord();
        data->numEntries = bitbuf.ReadUBitLong(math::log2(data->maxEntries) + 1);
        if (context.protocol > 23)
        {
            data->dataLengthInBits = bitbuf.ReadVarInt32();
        }
        else
        {
            data->dataLengthInBits = bitbuf.ReadUBitLong(NET_MAX_PAYLOAD_BITS_OLD + 3);
        }
        data->isUserDataFixedSize = bitbuf.ReadOneBit() != 0;
        if (data->isUserDataFixedSize)
        {
            data->userDataSize = bitbuf.ReadUBitLong(12);
            data->userDataSizeBits = bitbuf.ReadUBitLong(4);
        }
        else
        {
            data->userDataSize = 0;
            data->userDataSizeBits = 0;
        }
        if (context.protocol > 14)
        {
            data->unk1 = bitbuf.ReadOneBit() != 0;
        }
        data->data.reset(new uint8_t[math::BitsToBytes(data->dataLengthInBits)]);
        bitbuf.ReadBits(data->data.get(), data->dataLengthInBits);
        return !bitbuf.IsOverflowed();
    }

    bool SVC_CreateStringTable_BitWrite_Internal(BitWrite& bitbuf, const SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        if (data->isFileNames)
        {
            bitbuf.WriteByte(':');
        }
        bitbuf.WriteString(data->tableName);
        bitbuf.WriteWord(data->maxEntries);
        bitbuf.WriteUBitLong(data->numEntries, math::log2(data->maxEntries) + 1);
        if (context.protocol > 23)
        {
            bitbuf.WriteVarInt32(data->dataLengthInBits);
        }
        else
        {
            bitbuf.WriteUBitLong(data->dataLengthInBits, NET_MAX_PAYLOAD_BITS_OLD + 3);
        }
        bitbuf.WriteOneBit(data->isUserDataFixedSize);
        if (data->isUserDataFixedSize)
        {
            bitbuf.WriteUBitLong(data->userDataSize, 12);
            bitbuf.WriteUBitLong(data->userDataSizeBits, 4);
        }
        if (context.protocol > 14)
        {
            bitbuf.WriteOneBit(data->unk1);
        }
        bitbuf.WriteBits(data->data.get(), data->dataLengthInBits);
        return !bitbuf.IsOverflowed();
    }

    bool SVC_CreateStringTable_JsonRead_Internal(JsonRead& jsonbuf, SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        base::JsonReaderObject reader = jsonbuf.ParseObject();
        assert(!reader.HasReadError());
        data->isFileNames = reader.ReadBool("isFilenames");
        reader.ReadString("tableName", data->tableName, sizeof(data->tableName));
        data->maxEntries = reader.ReadUInt32("maxEntries");
        data->numEntries = reader.ReadUInt32("numEntries");
        data->dataLengthInBits = reader.ReadInt32("dataLengthInBits");
        data->isUserDataFixedSize = reader.ReadBool("isUserDataFixedSize");
        data->userDataSize = reader.ReadUInt32("userDataSize");
        data->userDataSizeBits = reader.ReadUInt32("userDataSizeBits");
        if (context.protocol > 14)
        {
            data->unk1 = reader.ReadBool("unk1");
        }
        data->data.reset(new uint8_t[math::BitsToBytes(data->dataLengthInBits)]);
        reader.ReadBits("data", data->data.get(), data->dataLengthInBits);
        return !reader.HasReadError();
    }

    bool SVC_CreateStringTable_JsonWrite_Internal(JsonWrite& jsonbuf, const SourceGameContext& context, NetMsg::SVC_CreateStringTable* data)
    {
        jsonbuf.Reset();
        jsonbuf.StartObject();
        jsonbuf.WriteBool("isFilenames", data->isFileNames);
        jsonbuf.WriteString("tableName", data->tableName);
        jsonbuf.WriteUInt32("maxEntries", data->maxEntries);
        jsonbuf.WriteUInt32("numEntries", data->numEntries);
        jsonbuf.WriteInt32("dataLengthInBits", data->dataLengthInBits);
        jsonbuf.WriteBool("isUserDataFixedSize", data->isUserDataFixedSize);
        jsonbuf.WriteUInt32("userDataSize", data->userDataSize);
        jsonbuf.WriteUInt32("userDataSizeBits", data->userDataSizeBits);
        if (context.protocol > 14)
        {
            jsonbuf.WriteBool("unk1", data->unk1);
        }
        jsonbuf.WriteBits("data", data->data.get(), data->dataLengthInBits);
        jsonbuf.EndObject();
        return jsonbuf.IsComplete();
    }

    void SVC_CreateStringTable_ToString_Internal(std::ostringstream& out, NetMsg::SVC_CreateStringTable* data)
    {
        out << "svc_CreateStringTable: table " << data->tableName
            << ", entries " << data->numEntries
            << ", bytes " << math::BitsToBytes(data->dataLengthInBits)
            << " userdatasize " << data->userDataSize
            << " userdatabits " << static_cast<uint32_t>(data->userDataSizeBits);
    }
}
<|endoftext|>


<commit_before>#include <allegro.h>

#include <iostream>
#include "util/file-system.h"
#include "mugen/character.h"
#include "mugen/mugen_exception.h"

using namespace std;

int main(int argc, char ** argv){
    install_allegro(SYSTEM_NONE, &errno, atexit);
    set_color_depth(16);
    set_color_conversion(COLORCONV_NONE);

    // for (int i = 0; i < 3; i++){
        try{
            Mugen::Character kfm(Filesystem::find("mugen/chars/kfm/kfm.def"));
            kfm.load();
            Global::debug(0, "test") << "Success" << endl;
        } catch (const MugenException & e){
            Global::debug(0, "test") << "Test failure!: " << e.getReason() << endl;
        }
    // }
}
<commit_msg>time the test<commit_after>#include <allegro.h>

#include <iostream>
#include "util/file-system.h"
#include "mugen/character.h"
#include "mugen/mugen_exception.h"
#include "util/timedifference.h"

using namespace std;

int main(int argc, char ** argv){
    install_allegro(SYSTEM_NONE, &errno, atexit);
    set_color_depth(16);
    set_color_conversion(COLORCONV_NONE);

    // for (int i = 0; i < 3; i++){
        try{
            TimeDifference diff;
            diff.startTime();
            Mugen::Character kfm(Filesystem::find("mugen/chars/kfm/kfm.def"));
            kfm.load();
            diff.endTime();
            Global::debug(0, "test") << "Success! Took " << diff.printTime() << endl;
        } catch (const MugenException & e){
            Global::debug(0, "test") << "Test failure!: " << e.getReason() << endl;
        }
    // }
}
<|endoftext|>


<commit_before>// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file defines BugReporter, a utility class for generating
//  PathDiagnostics for analyses based on GRSimpleVals.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/BugReporter.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CFG.h"
#include "clang/AST/Expr.h"
#include "clang/Analysis/ProgramPoint.h"
#include "clang/Analysis/PathDiagnostic.h"
#include <sstream>

using namespace clang;

BugReporter::~BugReporter() {}

static inline Stmt* GetStmt(const ProgramPoint& P) {
  if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
    return PS->getStmt();
  }
  else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
    return BE->getSrc()->getTerminator();
  }
  else if (const BlockEntrance* BE = dyn_cast<BlockEntrance>(&P)) {
    return BE->getFirstStmt();
  }

  assert (false && "Unsupported ProgramPoint.");
  return NULL;
}

PathDiagnosticPiece*
BugDescription::getEndPath(ASTContext& Ctx,
                           ExplodedNode<ValueState> *N) const {

  Stmt* S = GetStmt(N->getLocation());

  if (!S)
    return NULL;

  FullSourceLoc L(S->getLocStart(), Ctx.getSourceManager());
  PathDiagnosticPiece* P = new PathDiagnosticPiece(L, getDescription());

  if (Expr* E = dyn_cast<Expr>(S))
    P->addRange(E->getSourceRange());

  return P;
}

void BugReporter::GeneratePathDiagnostic(PathDiagnostic& PD, ASTContext& Ctx,
                                         const BugDescription& B,
                                         ExplodedGraph<GRExprEngine>& G,
                                         ExplodedNode<ValueState>* N) {
  PD.push_back(B.getEndPath(Ctx, N));

  SourceManager& SMgr = Ctx.getSourceManager();

  llvm::OwningPtr<ExplodedGraph<GRExprEngine> > GTrim(G.Trim(&N, &N+1));

  // Find the sink in the trimmed graph.
  // FIXME: Should we eventually have a sink iterator?

  ExplodedNode<ValueState>* NewN = 0;

  for (ExplodedGraph<GRExprEngine>::node_iterator
        I = GTrim->nodes_begin(), E = GTrim->nodes_end(); I != E; ++I) {

    if (I->isSink()) {
      NewN = &*I;
      break;
    }
  }

  assert (NewN);
  assert (NewN->getLocation() == N->getLocation());

  N = NewN;

  while (!N->pred_empty()) {

    ExplodedNode<ValueState>* LastNode = N;
    N = *(N->pred_begin());

    ProgramPoint P = N->getLocation();

    if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {

      CFGBlock* Src = BE->getSrc();
      CFGBlock* Dst = BE->getDst();

      Stmt* T = Src->getTerminator();

      if (!T)
        continue;

      FullSourceLoc L(T->getLocStart(), SMgr);

      switch (T->getStmtClass()) {
        default:
          break;

        case Stmt::GotoStmtClass:
        case Stmt::IndirectGotoStmtClass: {

          Stmt* S = GetStmt(LastNode->getLocation());

          if (!S)
            continue;

          std::ostringstream os;

          os << "Control jumps to line "
          << SMgr.getLogicalLineNumber(S->getLocStart()) << ".\n";

          PD.push_front(new PathDiagnosticPiece(L, os.str()));
          break;
        }

        case Stmt::SwitchStmtClass: {

          // Figure out what case arm we took.

          Stmt* S = Dst->getLabel();

          if (!S)
            continue;

          std::ostringstream os;

          switch (S->getStmtClass()) {
            default:
              continue;

            case Stmt::DefaultStmtClass: {

              os << "Control jumps to the 'default' case at line "
              << SMgr.getLogicalLineNumber(S->getLocStart()) << ".\n";

              break;
            }

            case Stmt::CaseStmtClass: {

              os << "Control jumps to 'case ";

              Expr* CondE = cast<SwitchStmt>(T)->getCond();
              unsigned bits = Ctx.getTypeSize(CondE->getType());

              llvm::APSInt V1(bits, false);

              CaseStmt* Case = cast<CaseStmt>(S);

              if (!Case->getLHS()->isIntegerConstantExpr(V1, Ctx, 0, true)) {
                assert (false &&
                        "Case condition must evaluate to an integer constant.");
                continue;
              }

              os << V1.toString();

              // Get the RHS of the case, if it exists.

              if (Expr* E = Case->getRHS()) {

                llvm::APSInt V2(bits, false);

                if (!E->isIntegerConstantExpr(V2, Ctx, 0, true)) {
                  assert (false &&
                  "Case condition (RHS) must evaluate to an integer constant.");
                  continue;
                }

                os << " .. " << V2.toString();
              }

              os << ":'  at line "
              << SMgr.getLogicalLineNumber(S->getLocStart()) << ".\n";

              break;

            }
          }

          PD.push_front(new PathDiagnosticPiece(L, os.str()));
          break;
        }

        case Stmt::DoStmtClass:
        case Stmt::WhileStmtClass:
        case Stmt::ForStmtClass:
        case Stmt::IfStmtClass: {

          if (*(Src->succ_begin()+1) == Dst)
            PD.push_front(new PathDiagnosticPiece(L, "Taking false branch."));
          else
            PD.push_front(new PathDiagnosticPiece(L, "Taking true branch."));

          break;
        }
      }
    }
  }
}

bool BugReporter::IsCached(ExplodedNode<ValueState>* N) {

  // HACK: Cache the location of the error.  Don't emit the same
  // warning for the same error type that occurs at the same program
  // location but along a different path.

  void* p = N->getLocation().getRawData();

  if (CachedErrors.count(p))
    return true;

  CachedErrors.insert(p);

  return false;
}

void BugReporter::EmitPathWarning(Diagnostic& Diag,
                                  PathDiagnosticClient* PDC,
                                  ASTContext& Ctx,
                                  const BugDescription& B,
                                  ExplodedGraph<GRExprEngine>& G,
                                  ExplodedNode<ValueState>* N) {

  if (!PDC) {
    EmitWarning(Diag, Ctx, B, N);
    return;
  }

  if (IsCached(N))
    return;

  PathDiagnostic D(B.getName());
  GeneratePathDiagnostic(D, Ctx, B, G, N);
  PDC->HandlePathDiagnostic(D);
}

void BugReporter::EmitWarning(Diagnostic& Diag, ASTContext& Ctx,
                              const BugDescription& B,
                              ExplodedNode<ValueState>* N) {
  if (IsCached(N))
    return;

  std::ostringstream os;
  os << "[CHECKER] " << B.getName();

  unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
                                            os.str().c_str());

  // FIXME: Add support for multiple ranges.

  Stmt* S = GetStmt(N->getLocation());

  if (!S)
    return;

  SourceRange R = S->getSourceRange();

  Diag.Report(FullSourceLoc(S->getLocStart(), Ctx.getSourceManager()),
              ErrorDiag, NULL, 0, &R, 1);
}
<commit_msg>Handle the case when getEndPath() returns NULL.<commit_after>// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file defines BugReporter, a utility class for generating
//  PathDiagnostics for analyses based on GRSimpleVals.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/BugReporter.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CFG.h"
#include "clang/AST/Expr.h"
#include "clang/Analysis/ProgramPoint.h"
#include "clang/Analysis/PathDiagnostic.h"
#include <sstream>

using namespace clang;

BugReporter::~BugReporter() {}

static inline Stmt* GetStmt(const ProgramPoint& P) {
  if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
    return PS->getStmt();
  }
  else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
    return BE->getSrc()->getTerminator();
  }
  else if (const BlockEntrance* BE = dyn_cast<BlockEntrance>(&P)) {
    return BE->getFirstStmt();
  }

  assert (false && "Unsupported ProgramPoint.");
  return NULL;
}

PathDiagnosticPiece*
BugDescription::getEndPath(ASTContext& Ctx,
                           ExplodedNode<ValueState> *N) const {

  Stmt* S = GetStmt(N->getLocation());

  if (!S)
    return NULL;

  FullSourceLoc L(S->getLocStart(), Ctx.getSourceManager());
  PathDiagnosticPiece* P = new PathDiagnosticPiece(L, getDescription());

  if (Expr* E = dyn_cast<Expr>(S))
    P->addRange(E->getSourceRange());

  return P;
}

void BugReporter::GeneratePathDiagnostic(PathDiagnostic& PD, ASTContext& Ctx,
                                         const BugDescription& B,
                                         ExplodedGraph<GRExprEngine>& G,
                                         ExplodedNode<ValueState>* N) {

  if (PathDiagnosticPiece* Piece = B.getEndPath(Ctx,N))
    PD.push_back(Piece);
  else
    return;

  SourceManager& SMgr = Ctx.getSourceManager();

  llvm::OwningPtr<ExplodedGraph<GRExprEngine> > GTrim(G.Trim(&N, &N+1));

  // Find the sink in the trimmed graph.
  // FIXME: Should we eventually have a sink iterator?

  ExplodedNode<ValueState>* NewN = 0;

  for (ExplodedGraph<GRExprEngine>::node_iterator
        I = GTrim->nodes_begin(), E = GTrim->nodes_end(); I != E; ++I) {

    if (I->isSink()) {
      NewN = &*I;
      break;
    }
  }

  assert (NewN);
  assert (NewN->getLocation() == N->getLocation());

  N = NewN;

  while (!N->pred_empty()) {

    ExplodedNode<ValueState>* LastNode = N;
    N = *(N->pred_begin());

    ProgramPoint P = N->getLocation();

    if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {

      CFGBlock* Src = BE->getSrc();
      CFGBlock* Dst = BE->getDst();

      Stmt* T = Src->getTerminator();

      if (!T)
        continue;

      FullSourceLoc L(T->getLocStart(), SMgr);

      switch (T->getStmtClass()) {
        default:
          break;

        case Stmt::GotoStmtClass:
        case Stmt::IndirectGotoStmtClass: {

          Stmt* S = GetStmt(LastNode->getLocation());

          if (!S)
            continue;

          std::ostringstream os;

          os << "Control jumps to line "
          << SMgr.getLogicalLineNumber(S->getLocStart()) << ".\n";

          PD.push_front(new PathDiagnosticPiece(L, os.str()));
          break;
        }

        case Stmt::SwitchStmtClass: {

          // Figure out what case arm we took.

          Stmt* S = Dst->getLabel();

          if (!S)
            continue;

          std::ostringstream os;

          switch (S->getStmtClass()) {
            default:
              continue;

            case Stmt::DefaultStmtClass: {

              os << "Control jumps to the 'default' case at line "
              << SMgr.getLogicalLineNumber(S->getLocStart()) << ".\n";

              break;
            }

            case Stmt::CaseStmtClass: {

              os << "Control jumps to 'case ";

              Expr* CondE = cast<SwitchStmt>(T)->getCond();
              unsigned bits = Ctx.getTypeSize(CondE->getType());

              llvm::APSInt V1(bits, false);

              CaseStmt* Case = cast<CaseStmt>(S);

              if (!Case->getLHS()->isIntegerConstantExpr(V1, Ctx, 0, true)) {
                assert (false &&
                        "Case condition must evaluate to an integer constant.");
                continue;
              }

              os << V1.toString();

              // Get the RHS of the case, if it exists.

              if (Expr* E = Case->getRHS()) {

                llvm::APSInt V2(bits, false);

                if (!E->isIntegerConstantExpr(V2, Ctx, 0, true)) {
                  assert (false &&
                  "Case condition (RHS) must evaluate to an integer constant.");
                  continue;
                }

                os << " .. " << V2.toString();
              }

              os << ":'  at line "
              << SMgr.getLogicalLineNumber(S->getLocStart()) << ".\n";

              break;

            }
          }

          PD.push_front(new PathDiagnosticPiece(L, os.str()));
          break;
        }

        case Stmt::DoStmtClass:
        case Stmt::WhileStmtClass:
        case Stmt::ForStmtClass:
        case Stmt::IfStmtClass: {

          if (*(Src->succ_begin()+1) == Dst)
            PD.push_front(new PathDiagnosticPiece(L, "Taking false branch."));
          else
            PD.push_front(new PathDiagnosticPiece(L, "Taking true branch."));

          break;
        }
      }
    }
  }
}

bool BugReporter::IsCached(ExplodedNode<ValueState>* N) {

  // HACK: Cache the location of the error.  Don't emit the same
  // warning for the same error type that occurs at the same program
  // location but along a different path.

  void* p = N->getLocation().getRawData();

  if (CachedErrors.count(p))
    return true;

  CachedErrors.insert(p);

  return false;
}

void BugReporter::EmitPathWarning(Diagnostic& Diag,
                                  PathDiagnosticClient* PDC,
                                  ASTContext& Ctx,
                                  const BugDescription& B,
                                  ExplodedGraph<GRExprEngine>& G,
                                  ExplodedNode<ValueState>* N) {

  if (!PDC) {
    EmitWarning(Diag, Ctx, B, N);
    return;
  }

  if (IsCached(N))
    return;

  PathDiagnostic D(B.getName());
  GeneratePathDiagnostic(D, Ctx, B, G, N);

  if (!D.empty())
    PDC->HandlePathDiagnostic(D);
}

void BugReporter::EmitWarning(Diagnostic& Diag, ASTContext& Ctx,
                              const BugDescription& B,
                              ExplodedNode<ValueState>* N) {
  if (IsCached(N))
    return;

  std::ostringstream os;
  os << "[CHECKER] " << B.getName();

  unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
                                            os.str().c_str());

  // FIXME: Add support for multiple ranges.

  Stmt* S = GetStmt(N->getLocation());

  if (!S)
    return;

  SourceRange R = S->getSourceRange();

  Diag.Report(FullSourceLoc(S->getLocStart(), Ctx.getSourceManager()),
              ErrorDiag, NULL, 0, &R, 1);
}
<|endoftext|>


<commit_before>//===-- MachineInstr.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Methods common to all machine instructions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>

using namespace llvm;

// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class TargetInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
namespace llvm {
  extern const TargetInstrDescriptor *TargetInstrDescriptors;
}

/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them.  It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(short opcode, unsigned numOperands)
  : Opcode(opcode), parent(0) {
  Operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
}

/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
                           unsigned numOperands)
  : Opcode(opcode), parent(0) {
  assert(MBB && "Cannot use inserting ctor with null basic block!");
  Operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
  MBB->push_back(this);  // Add instruction to end of basic block!
}

/// MachineInstr ctor - Copies MachineInstr arg exactly
///
MachineInstr::MachineInstr(const MachineInstr &MI) {
  Opcode = MI.getOpcode();
  Operands.reserve(MI.getNumOperands());

  // Add operands
  for (unsigned i = 0; i != MI.getNumOperands(); ++i)
    Operands.push_back(MI.getOperand(i));

  // Set parent, next, and prev to null
  parent = 0;
  prev = 0;
  next = 0;
}

MachineInstr::~MachineInstr() {
  LeakDetector::removeGarbageObject(this);
}

/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, and returns it, but does not delete it.
MachineInstr *MachineInstr::removeFromParent() {
  assert(getParent() && "Not embedded in a basic block!");
  getParent()->remove(this);
  return this;
}

/// OperandComplete - Return true if it's illegal to add a new operand
///
bool MachineInstr::OperandsComplete() const {
  int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
  if ((TargetInstrDescriptors[Opcode].Flags & M_VARIABLE_OPS) == 0 &&
      getNumOperands() >= (unsigned)NumOperands)
    return true;  // Broken: we have all the operands of this instruction!
  return false;
}

/// isIdenticalTo - Return true if this operand is identical to the specified
/// operand.
bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
  if (getType() != Other.getType()) return false;

  switch (getType()) {
  default: assert(0 && "Unrecognized operand type");
  case MachineOperand::MO_Register:
    return getReg() == Other.getReg() && isDef() == Other.isDef();
  case MachineOperand::MO_Immediate:
    return getImm() == Other.getImm();
  case MachineOperand::MO_MachineBasicBlock:
    return getMBB() == Other.getMBB();
  case MachineOperand::MO_FrameIndex:
    return getFrameIndex() == Other.getFrameIndex();
  case MachineOperand::MO_ConstantPoolIndex:
    return getConstantPoolIndex() == Other.getConstantPoolIndex() &&
           getOffset() == Other.getOffset();
  case MachineOperand::MO_JumpTableIndex:
    return getJumpTableIndex() == Other.getJumpTableIndex();
  case MachineOperand::MO_GlobalAddress:
    return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
  case MachineOperand::MO_ExternalSymbol:
    return getSymbolName() == Other.getSymbolName() &&
           getOffset() == Other.getOffset();
  }
}

void MachineInstr::dump() const {
  std::cerr << "  " << *this;
}

static inline void OutputReg(std::ostream &os, unsigned RegNo,
                             const MRegisterInfo *MRI = 0) {
  if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
    if (MRI)
      os << "%" << MRI->get(RegNo).Name;
    else
      os << "%mreg(" << RegNo << ")";
  } else
    os << "%reg" << RegNo;
}

static void print(const MachineOperand &MO, std::ostream &OS,
                  const TargetMachine *TM) {
  const MRegisterInfo *MRI = 0;

  if (TM) MRI = TM->getRegisterInfo();

  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    OutputReg(OS, MO.getReg(), MRI);
    break;
  case MachineOperand::MO_Immediate:
    OS << MO.getImmedValue();
    break;
  case MachineOperand::MO_MachineBasicBlock:
    OS << "mbb<"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "," << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_JumpTableIndex:
    OS << "<jt#" << MO.getJumpTableIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
  }
}

void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
  unsigned StartOp = 0;

   // Specialize printing if op#0 is definition
  if (getNumOperands() && getOperand(0).isReg() && getOperand(0).isDef()) {
    ::print(getOperand(0), OS, TM);
    OS << " = ";
    ++StartOp;   // Don't print this operand again!
  }

  // Must check if Target machine is not null because machine BB could not
  // be attached to a Machine function yet
  if (TM)
    OS << TM->getInstrInfo()->getName(getOpcode());

  for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
    const MachineOperand& mop = getOperand(i);
    if (i != StartOp)
      OS << ",";
    OS << " ";
    ::print(mop, OS, TM);

    if (mop.isReg() && mop.isDef())
      OS << "<def>";
  }

  OS << "\n";
}

std::ostream &llvm::operator<<(std::ostream &os, const MachineInstr &MI) {
  // If the instruction is embedded into a basic block, we can find the target
  // info for the instruction.
  if (const MachineBasicBlock *MBB = MI.getParent()) {
    const MachineFunction *MF = MBB->getParent();
    if (MF)
      MI.print(os, &MF->getTarget());
    else
      MI.print(os, 0);
    return os;
  }

  // Otherwise, print it out in the "raw" format without symbolic register names
  // and such.
  os << TargetInstrDescriptors[MI.getOpcode()].Name;

  for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
    os << "\t" << MI.getOperand(i);
    if (MI.getOperand(i).isReg() && MI.getOperand(i).isDef())
      os << "<d>";
  }

  return os << "\n";
}

std::ostream &llvm::operator<<(std::ostream &OS, const MachineOperand &MO) {
  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    OutputReg(OS, MO.getReg());
    break;
  case MachineOperand::MO_Immediate:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_MachineBasicBlock:
    OS << "<mbb:"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "@" << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_JumpTableIndex:
    OS << "<jt#" << MO.getJumpTableIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName() << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
    break;
  }

  return OS;
}
<commit_msg>be more aggressive about matching identical instructions.<commit_after>//===-- MachineInstr.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Methods common to all machine instructions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>

using namespace llvm;

// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class TargetInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
namespace llvm {
  extern const TargetInstrDescriptor *TargetInstrDescriptors;
}

/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them.  It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(short opcode, unsigned numOperands)
  : Opcode(opcode), parent(0) {
  Operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
}

/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
                           unsigned numOperands)
  : Opcode(opcode), parent(0) {
  assert(MBB && "Cannot use inserting ctor with null basic block!");
  Operands.reserve(numOperands);
  // Make sure that we get added to a machine basicblock
  LeakDetector::addGarbageObject(this);
  MBB->push_back(this);  // Add instruction to end of basic block!
}

/// MachineInstr ctor - Copies MachineInstr arg exactly
///
MachineInstr::MachineInstr(const MachineInstr &MI) {
  Opcode = MI.getOpcode();
  Operands.reserve(MI.getNumOperands());

  // Add operands
  for (unsigned i = 0; i != MI.getNumOperands(); ++i)
    Operands.push_back(MI.getOperand(i));

  // Set parent, next, and prev to null
  parent = 0;
  prev = 0;
  next = 0;
}

MachineInstr::~MachineInstr() {
  LeakDetector::removeGarbageObject(this);
}

/// removeFromParent - This method unlinks 'this' from the containing basic
/// block, and returns it, but does not delete it.
MachineInstr *MachineInstr::removeFromParent() {
  assert(getParent() && "Not embedded in a basic block!");
  getParent()->remove(this);
  return this;
}

/// OperandComplete - Return true if it's illegal to add a new operand
///
bool MachineInstr::OperandsComplete() const {
  int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
  if ((TargetInstrDescriptors[Opcode].Flags & M_VARIABLE_OPS) == 0 &&
      getNumOperands() >= (unsigned)NumOperands)
    return true;  // Broken: we have all the operands of this instruction!
  return false;
}

/// isIdenticalTo - Return true if this operand is identical to the specified
/// operand.
bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
  if (getType() != Other.getType()) return false;

  switch (getType()) {
  default: assert(0 && "Unrecognized operand type");
  case MachineOperand::MO_Register:
    return getReg() == Other.getReg() && isDef() == Other.isDef();
  case MachineOperand::MO_Immediate:
    return getImm() == Other.getImm();
  case MachineOperand::MO_MachineBasicBlock:
    return getMBB() == Other.getMBB();
  case MachineOperand::MO_FrameIndex:
    return getFrameIndex() == Other.getFrameIndex();
  case MachineOperand::MO_ConstantPoolIndex:
    return getConstantPoolIndex() == Other.getConstantPoolIndex() &&
           getOffset() == Other.getOffset();
  case MachineOperand::MO_JumpTableIndex:
    return getJumpTableIndex() == Other.getJumpTableIndex();
  case MachineOperand::MO_GlobalAddress:
    return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
  case MachineOperand::MO_ExternalSymbol:
    return !strcmp(getSymbolName(), Other.getSymbolName()) &&
           getOffset() == Other.getOffset();
  }
}

void MachineInstr::dump() const {
  std::cerr << "  " << *this;
}

static inline void OutputReg(std::ostream &os, unsigned RegNo,
                             const MRegisterInfo *MRI = 0) {
  if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
    if (MRI)
      os << "%" << MRI->get(RegNo).Name;
    else
      os << "%mreg(" << RegNo << ")";
  } else
    os << "%reg" << RegNo;
}

static void print(const MachineOperand &MO, std::ostream &OS,
                  const TargetMachine *TM) {
  const MRegisterInfo *MRI = 0;

  if (TM) MRI = TM->getRegisterInfo();

  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    OutputReg(OS, MO.getReg(), MRI);
    break;
  case MachineOperand::MO_Immediate:
    OS << MO.getImmedValue();
    break;
  case MachineOperand::MO_MachineBasicBlock:
    OS << "mbb<"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "," << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_JumpTableIndex:
    OS << "<jt#" << MO.getJumpTableIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName();
    if (MO.getOffset()) OS << "+" << MO.getOffset();
    OS << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
  }
}

void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
  unsigned StartOp = 0;

   // Specialize printing if op#0 is definition
  if (getNumOperands() && getOperand(0).isReg() && getOperand(0).isDef()) {
    ::print(getOperand(0), OS, TM);
    OS << " = ";
    ++StartOp;   // Don't print this operand again!
  }

  // Must check if Target machine is not null because machine BB could not
  // be attached to a Machine function yet
  if (TM)
    OS << TM->getInstrInfo()->getName(getOpcode());

  for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
    const MachineOperand& mop = getOperand(i);
    if (i != StartOp)
      OS << ",";
    OS << " ";
    ::print(mop, OS, TM);

    if (mop.isReg() && mop.isDef())
      OS << "<def>";
  }

  OS << "\n";
}

std::ostream &llvm::operator<<(std::ostream &os, const MachineInstr &MI) {
  // If the instruction is embedded into a basic block, we can find the target
  // info for the instruction.
  if (const MachineBasicBlock *MBB = MI.getParent()) {
    const MachineFunction *MF = MBB->getParent();
    if (MF)
      MI.print(os, &MF->getTarget());
    else
      MI.print(os, 0);
    return os;
  }

  // Otherwise, print it out in the "raw" format without symbolic register names
  // and such.
  os << TargetInstrDescriptors[MI.getOpcode()].Name;

  for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
    os << "\t" << MI.getOperand(i);
    if (MI.getOperand(i).isReg() && MI.getOperand(i).isDef())
      os << "<d>";
  }

  return os << "\n";
}

std::ostream &llvm::operator<<(std::ostream &OS, const MachineOperand &MO) {
  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    OutputReg(OS, MO.getReg());
    break;
  case MachineOperand::MO_Immediate:
    OS << (long)MO.getImmedValue();
    break;
  case MachineOperand::MO_MachineBasicBlock:
    OS << "<mbb:"
       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
       << "@" << (void*)MO.getMachineBasicBlock() << ">";
    break;
  case MachineOperand::MO_FrameIndex:
    OS << "<fi#" << MO.getFrameIndex() << ">";
    break;
  case MachineOperand::MO_ConstantPoolIndex:
    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
    break;
  case MachineOperand::MO_JumpTableIndex:
    OS << "<jt#" << MO.getJumpTableIndex() << ">";
    break;
  case MachineOperand::MO_GlobalAddress:
    OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
    break;
  case MachineOperand::MO_ExternalSymbol:
    OS << "<es:" << MO.getSymbolName() << ">";
    break;
  default:
    assert(0 && "Unrecognized operand type");
    break;
  }

  return OS;
}
<|endoftext|>


<commit_before>#include "Server.h"

#include <QDir>
#include <QCoreApplication>

#include <cmath>

Server::Server(QUrl connection_info) :
    m_connection_info(connection_info),
    m_socket_thread(NULL),
    m_parser(NULL),
    m_position_update_timer(NULL),
    m_login_state(Disconnected)
{
    // we run in m_socket_thread
    m_socket_thread = new QThread(this);
    m_socket_thread->start();
    this->moveToThread(m_socket_thread);

    bool success;
    success = QMetaObject::invokeMethod(this, "initialize", Qt::QueuedConnection);
    Q_ASSERT(success);
}

Server::~Server()
{
    delete m_parser;
    delete m_position_update_timer;
}

void Server::initialize()
{
    Q_ASSERT(QThread::currentThread() == m_socket_thread);

    m_socket = new QTcpSocket(this);

    bool success;

    success = connect(m_socket, SIGNAL(connected()), this, SLOT(handleConnected()));
    Q_ASSERT(success);

    success = connect(m_socket, SIGNAL(disconnected()), this, SLOT(cleanUpAfterDisconnect()));
    Q_ASSERT(success);

    success = connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleSocketError(QAbstractSocket::SocketError)));
    Q_ASSERT(success);
}

void Server::socketConnect()
{
    if (QThread::currentThread() != m_socket_thread) {
        bool success = QMetaObject::invokeMethod(this, "socketConnect", Qt::QueuedConnection);
        Q_ASSERT(success);
        return;
    }
    Q_ASSERT(m_socket);

    changeLoginState(Connecting);
    m_socket->connectToHost(m_connection_info.host(), m_connection_info.port(25565));
}

void Server::socketDisconnect()
{
    if (QThread::currentThread() != m_socket_thread) {
        bool success = QMetaObject::invokeMethod(this, "socketDisconnect", Qt::QueuedConnection);
        Q_ASSERT(success);
        return;
    }

    if (m_socket->isOpen())
        m_socket->disconnectFromHost();
}

void Server::sendMessage(QSharedPointer<OutgoingRequest> msg)
{
    if (msg.data()->messageType == Message::DummyDisconnect) {
        socketDisconnect();
        return;
    }
    if (m_socket->isOpen()) {
        QDataStream stream(m_socket);
        msg.data()->writeToStream(stream);
    }
}

void Server::handleConnected()
{
    delete m_parser;
    m_parser = new IncomingMessageParser(m_socket);

    bool success;
    success = connect(m_parser, SIGNAL(messageReceived(QSharedPointer<IncomingResponse>)), this, SLOT(processIncomingMessage(QSharedPointer<IncomingResponse>)));
    Q_ASSERT(success);

    changeLoginState(WaitingForHandshakeResponse);
    sendMessage(QSharedPointer<OutgoingRequest>(new HandshakeRequest(m_connection_info.userName())));
}

void Server::cleanUpAfterDisconnect()
{
    qDebug() << "Cleaning up, disconnected";
    m_socket_thread->exit();
    this->moveToThread(QCoreApplication::instance()->thread());
    bool success;
    success = QMetaObject::invokeMethod(this, "terminate", Qt::QueuedConnection);
    Q_ASSERT(success);
}

void Server::terminate()
{
    Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
    m_socket_thread->exit();
    m_socket_thread->wait();

    changeLoginState(Disconnected);
    emit socketDisconnected();
}

void Server::processIncomingMessage(QSharedPointer<IncomingResponse> incomingMessage)
{
    // possibly handle the message (only for the initial setup)
    switch (incomingMessage.data()->messageType) {
        case Message::Handshake: {
            HandshakeResponse * message = (HandshakeResponse *)incomingMessage.data();
            Q_ASSERT(m_login_state == WaitingForHandshakeResponse);
            // we don't support authenticated logging in yet.
            Q_ASSERT_X(message->connectionHash == HandshakeResponse::AuthenticationNotRequired, "",
                       (QString("unexpected connection hash: ") + message->connectionHash).toStdString().c_str());
            changeLoginState(WaitingForLoginResponse);
            changeLoginState(WaitingForPlayerPositionAndLook);
            sendMessage(QSharedPointer<OutgoingRequest>(new LoginRequest(m_connection_info.userName(), m_connection_info.password())));
            break;
        }
        case Message::PlayerPositionAndLook: {
            PlayerPositionAndLookResponse * message = (PlayerPositionAndLookResponse *) incomingMessage.data();
            fromNotchianXyz(player_position, message->x, message->z, message->y);
            player_position.stance = message->stance;
            fromNotchianYawPitch(player_position, message->yaw, message->pitch);
            player_position.roll = 0.0f;
            player_position.on_ground = message->on_ground;
            if (m_login_state == WaitingForPlayerPositionAndLook)
                gotFirstPlayerPositionAndLookResponse();
            break;
        }
        case Message::MapChunk: {
            MapChunkResponse * message = (MapChunkResponse *) incomingMessage.data();

            QByteArray tmp = message->compressed_data;
            // prepend a guess at the final size... or just 0.
            tmp.prepend(QByteArray("\0\0\0\0", 4));
            QByteArray decompressed = qUncompress(tmp);

            Chunk::Int3D position;
            fromNotchianXyz(position, message->x, message->y, message->z);
            Chunk::Int3D notchian_size;
            notchian_size.x = message->size_x_minus_one + 1;
            notchian_size.y = message->size_y_minus_one + 1;
            notchian_size.z = message->size_z_minus_one + 1;
            Chunk::Int3D size;
            fromNotchianXyz(size, notchian_size.x, notchian_size.y, notchian_size.z);

            Chunk * chunk = new Chunk(position, size);

            int array_index = 0;
            Chunk::Int3D notchian_relative_pos;
            for (notchian_relative_pos.x = 0; notchian_relative_pos.x < notchian_size.x; notchian_relative_pos.x++) {
                for (notchian_relative_pos.z = 0; notchian_relative_pos.z < notchian_size.z; notchian_relative_pos.z++) {
                    for (notchian_relative_pos.y = 0; notchian_relative_pos.y < notchian_size.y; notchian_relative_pos.y++) {
                        int block_type = decompressed.at(array_index++);
                        Chunk::Int3D relative_pos;
                        fromNotchianXyz(relative_pos, notchian_relative_pos.x, notchian_relative_pos.y, notchian_relative_pos.z);
                        chunk->getBlock(relative_pos).data()->type = block_type;
                    }
                }
            }
            // ... and then just ignore the other two arrays.
            emit mapChunkUpdated(QSharedPointer<Chunk>(chunk));
            break;
        }
        case Message::DisconnectOrKick: {
            DisconnectOrKickResponse * message = (DisconnectOrKickResponse *)incomingMessage.data();
            qDebug() << "got disconnected: " << message->reason;
            finishWritingAndDisconnect();
            break;
        }
        default: {
            // qDebug() << "ignoring message type: 0x" << QString::number(incomingMessage.data()->messageType, 16).toStdString().c_str();
            break;
        }
    }
}

void Server::fromNotchianXyz(EntityPosition &destination, double notchian_x, double notchian_y, double notchian_z)
{
    // east
    destination.x = notchian_z;
    // north
    destination.y = -notchian_x;
    // up
    destination.z = notchian_y;
}
void Server::fromNotchianXyz(Chunk::Int3D &destination, int notchian_x, int notchian_y, int notchian_z)
{
    // east
    destination.x = notchian_z;
    // north
    destination.y = -notchian_x;
    // up
    destination.z = notchian_y;
}

void Server::toNotchianXyz(const EntityPosition &source, double &destination_notchian_x, double &destination_notchian_y, double &destination_notchian_z)
{
    // east
    destination_notchian_z = source.x;
    // north
    destination_notchian_x = -source.y;
    // up
    destination_notchian_y = source.z;
}

void Server::fromNotchianYawPitch(EntityPosition &destination, float notchian_yaw, float notchian_pitch)
{
    // amazingly, yaw is oriented properly.
    destination.yaw = euclideanMod(degreesToRadians(notchian_yaw), c_2pi);
    // TODO: check pitch
    destination.pitch = euclideanMod(degreesToRadians(notchian_pitch) + c_pi, c_2pi) - c_2pi;
}

void Server::toNotchianYawPitch(const EntityPosition &source, float &destination_notchian_yaw, float &destination_notchian_pitch)
{
    destination_notchian_yaw = radiansToDegrees(source.yaw);
    // TODO: check pitch
    destination_notchian_pitch = radiansToDegrees(source.pitch);
}

const float Server::c_pi = 3.14159265f;
const float Server::c_2pi = 6.28318531f;
const float Server::c_degrees_per_radian = 57.2957795f;
const float Server::c_radians_per_degree = 0.0174532925f;

float Server::degreesToRadians(float degrees)
{
    return degrees * c_radians_per_degree;
}

float Server::radiansToDegrees(float radians)
{
    return radians * c_degrees_per_radian;
}

float Server::euclideanMod(float numerator, float denominator)
{
    float result = std::fmod(numerator, denominator);
    if (result < 0)
        result += denominator;
    return result;
}

void Server::gotFirstPlayerPositionAndLookResponse()
{
    delete m_position_update_timer;
    m_position_update_timer = new QTimer();
    m_position_update_timer->setInterval(200);

    bool success;
    success = connect(m_position_update_timer, SIGNAL(timeout()), this, SLOT(sendPosition()));
    Q_ASSERT(success);

    m_position_update_timer->start();

    changeLoginState(Success);
}

void Server::sendPosition()
{
    PlayerPositionAndLookRequest * request = new PlayerPositionAndLookRequest;
    toNotchianXyz(player_position, request->x, request->y, request->z);
    request->stance = player_position.stance;
    toNotchianYawPitch(player_position, request->yaw, request->pitch);
    request->on_ground = player_position.on_ground;
    sendMessage(QSharedPointer<OutgoingRequest>(request));
}

void Server::changeLoginState(LoginStatus state)
{
    m_login_state = state;
    emit loginStatusUpdated(state);
}

void Server::handleSocketError(QAbstractSocket::SocketError error)
{
    qDebug() << "Socket error: " << error;
    changeLoginState(SocketError);
}

void Server::finishWritingAndDisconnect()
{
    // put a dummy message on the queue
    this->sendMessage(QSharedPointer<OutgoingRequest>(new DummyDisconnectRequest()));
}

Server::LoginStatus Server::loginStatus()
{
    return m_login_state;
}
<commit_msg>parsing all block data from MapChunk. waiting for setBlock method in Chunk<commit_after>#include "Server.h"

#include <QDir>
#include <QCoreApplication>

#include <cmath>

Server::Server(QUrl connection_info) :
    m_connection_info(connection_info),
    m_socket_thread(NULL),
    m_parser(NULL),
    m_position_update_timer(NULL),
    m_login_state(Disconnected)
{
    // we run in m_socket_thread
    m_socket_thread = new QThread(this);
    m_socket_thread->start();
    this->moveToThread(m_socket_thread);

    bool success;
    success = QMetaObject::invokeMethod(this, "initialize", Qt::QueuedConnection);
    Q_ASSERT(success);
}

Server::~Server()
{
    delete m_parser;
    delete m_position_update_timer;
}

void Server::initialize()
{
    Q_ASSERT(QThread::currentThread() == m_socket_thread);

    m_socket = new QTcpSocket(this);

    bool success;

    success = connect(m_socket, SIGNAL(connected()), this, SLOT(handleConnected()));
    Q_ASSERT(success);

    success = connect(m_socket, SIGNAL(disconnected()), this, SLOT(cleanUpAfterDisconnect()));
    Q_ASSERT(success);

    success = connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleSocketError(QAbstractSocket::SocketError)));
    Q_ASSERT(success);
}

void Server::socketConnect()
{
    if (QThread::currentThread() != m_socket_thread) {
        bool success = QMetaObject::invokeMethod(this, "socketConnect", Qt::QueuedConnection);
        Q_ASSERT(success);
        return;
    }
    Q_ASSERT(m_socket);

    changeLoginState(Connecting);
    m_socket->connectToHost(m_connection_info.host(), m_connection_info.port(25565));
}

void Server::socketDisconnect()
{
    if (QThread::currentThread() != m_socket_thread) {
        bool success = QMetaObject::invokeMethod(this, "socketDisconnect", Qt::QueuedConnection);
        Q_ASSERT(success);
        return;
    }

    if (m_socket->isOpen())
        m_socket->disconnectFromHost();
}

void Server::sendMessage(QSharedPointer<OutgoingRequest> msg)
{
    if (msg.data()->messageType == Message::DummyDisconnect) {
        socketDisconnect();
        return;
    }
    if (m_socket->isOpen()) {
        QDataStream stream(m_socket);
        msg.data()->writeToStream(stream);
    }
}

void Server::handleConnected()
{
    delete m_parser;
    m_parser = new IncomingMessageParser(m_socket);

    bool success;
    success = connect(m_parser, SIGNAL(messageReceived(QSharedPointer<IncomingResponse>)), this, SLOT(processIncomingMessage(QSharedPointer<IncomingResponse>)));
    Q_ASSERT(success);

    changeLoginState(WaitingForHandshakeResponse);
    sendMessage(QSharedPointer<OutgoingRequest>(new HandshakeRequest(m_connection_info.userName())));
}

void Server::cleanUpAfterDisconnect()
{
    qDebug() << "Cleaning up, disconnected";
    m_socket_thread->exit();
    this->moveToThread(QCoreApplication::instance()->thread());
    bool success;
    success = QMetaObject::invokeMethod(this, "terminate", Qt::QueuedConnection);
    Q_ASSERT(success);
}

void Server::terminate()
{
    Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
    m_socket_thread->exit();
    m_socket_thread->wait();

    changeLoginState(Disconnected);
    emit socketDisconnected();
}

void Server::processIncomingMessage(QSharedPointer<IncomingResponse> incomingMessage)
{
    // possibly handle the message (only for the initial setup)
    switch (incomingMessage.data()->messageType) {
        case Message::Handshake: {
            HandshakeResponse * message = (HandshakeResponse *)incomingMessage.data();
            Q_ASSERT(m_login_state == WaitingForHandshakeResponse);
            // we don't support authenticated logging in yet.
            Q_ASSERT_X(message->connectionHash == HandshakeResponse::AuthenticationNotRequired, "",
                       (QString("unexpected connection hash: ") + message->connectionHash).toStdString().c_str());
            changeLoginState(WaitingForLoginResponse);
            changeLoginState(WaitingForPlayerPositionAndLook);
            sendMessage(QSharedPointer<OutgoingRequest>(new LoginRequest(m_connection_info.userName(), m_connection_info.password())));
            break;
        }
        case Message::PlayerPositionAndLook: {
            PlayerPositionAndLookResponse * message = (PlayerPositionAndLookResponse *) incomingMessage.data();
            fromNotchianXyz(player_position, message->x, message->z, message->y);
            player_position.stance = message->stance;
            fromNotchianYawPitch(player_position, message->yaw, message->pitch);
            player_position.roll = 0.0f;
            player_position.on_ground = message->on_ground;
            if (m_login_state == WaitingForPlayerPositionAndLook)
                gotFirstPlayerPositionAndLookResponse();
            break;
        }
        case Message::MapChunk: {
            MapChunkResponse * message = (MapChunkResponse *) incomingMessage.data();

            QByteArray tmp = message->compressed_data;
            // prepend a guess at the final size... or just 0.
            tmp.prepend(QByteArray("\0\0\0\0", 4));
            QByteArray decompressed = qUncompress(tmp);

            Chunk::Int3D position;
            fromNotchianXyz(position, message->x, message->y, message->z);
            Chunk::Int3D notchian_size;
            notchian_size.x = message->size_x_minus_one + 1;
            notchian_size.y = message->size_y_minus_one + 1;
            notchian_size.z = message->size_z_minus_one + 1;
            Chunk::Int3D size;
            fromNotchianXyz(size, notchian_size.x, notchian_size.y, notchian_size.z);

            Chunk * chunk = new Chunk(position, size);

            int volume = size.x * size.y * size.z;
            int metadata_offset = volume;
            int light_offset = volume * 3 / 2;
            int sky_light_offest = volume * 2;
            int array_index = 0;
            int nibble_shifter = 0; // start with low nibble
            Chunk::Int3D notchian_relative_pos;
            // traversal order is x,z,y in notchian coordinates
            for (notchian_relative_pos.x = 0; notchian_relative_pos.x < notchian_size.x; notchian_relative_pos.x++) {
                for (notchian_relative_pos.z = 0; notchian_relative_pos.z < notchian_size.z; notchian_relative_pos.z++) {
                    for (notchian_relative_pos.y = 0; notchian_relative_pos.y < notchian_size.y; notchian_relative_pos.y++) {
                        Chunk::Block block;
                        block.type = decompressed.at(array_index);
                        block.metadata  = (decompressed.at( metadata_offset + array_index / 2) >> nibble_shifter) & 0xf;
                        block.light     = (decompressed.at(    light_offset + array_index / 2) >> nibble_shifter) & 0xf;
                        block.sky_light = (decompressed.at(sky_light_offest + array_index / 2) >> nibble_shifter) & 0xf;

                        array_index++;
                        nibble_shifter = 4 - nibble_shifter;

                        Chunk::Int3D relative_pos;
                        fromNotchianXyz(relative_pos, notchian_relative_pos.x, notchian_relative_pos.y, notchian_relative_pos.z);
                        // TODO: chunk->setBlock(relative_pos, block);
                    }
                }
            }
            emit mapChunkUpdated(QSharedPointer<Chunk>(chunk));
            break;
        }
        case Message::DisconnectOrKick: {
            DisconnectOrKickResponse * message = (DisconnectOrKickResponse *)incomingMessage.data();
            qDebug() << "got disconnected: " << message->reason;
            finishWritingAndDisconnect();
            break;
        }
        default: {
            // qDebug() << "ignoring message type: 0x" << QString::number(incomingMessage.data()->messageType, 16).toStdString().c_str();
            break;
        }
    }
}

void Server::fromNotchianXyz(EntityPosition &destination, double notchian_x, double notchian_y, double notchian_z)
{
    // east
    destination.x = notchian_z;
    // north
    destination.y = -notchian_x;
    // up
    destination.z = notchian_y;
}
void Server::fromNotchianXyz(Chunk::Int3D &destination, int notchian_x, int notchian_y, int notchian_z)
{
    // east
    destination.x = notchian_z;
    // north
    destination.y = -notchian_x;
    // up
    destination.z = notchian_y;
}

void Server::toNotchianXyz(const EntityPosition &source, double &destination_notchian_x, double &destination_notchian_y, double &destination_notchian_z)
{
    // east
    destination_notchian_z = source.x;
    // north
    destination_notchian_x = -source.y;
    // up
    destination_notchian_y = source.z;
}

void Server::fromNotchianYawPitch(EntityPosition &destination, float notchian_yaw, float notchian_pitch)
{
    // amazingly, yaw is oriented properly.
    destination.yaw = euclideanMod(degreesToRadians(notchian_yaw), c_2pi);
    // TODO: check pitch
    destination.pitch = euclideanMod(degreesToRadians(notchian_pitch) + c_pi, c_2pi) - c_2pi;
}

void Server::toNotchianYawPitch(const EntityPosition &source, float &destination_notchian_yaw, float &destination_notchian_pitch)
{
    destination_notchian_yaw = radiansToDegrees(source.yaw);
    // TODO: check pitch
    destination_notchian_pitch = radiansToDegrees(source.pitch);
}

const float Server::c_pi = 3.14159265f;
const float Server::c_2pi = 6.28318531f;
const float Server::c_degrees_per_radian = 57.2957795f;
const float Server::c_radians_per_degree = 0.0174532925f;

float Server::degreesToRadians(float degrees)
{
    return degrees * c_radians_per_degree;
}

float Server::radiansToDegrees(float radians)
{
    return radians * c_degrees_per_radian;
}

float Server::euclideanMod(float numerator, float denominator)
{
    float result = std::fmod(numerator, denominator);
    if (result < 0)
        result += denominator;
    return result;
}

void Server::gotFirstPlayerPositionAndLookResponse()
{
    delete m_position_update_timer;
    m_position_update_timer = new QTimer();
    m_position_update_timer->setInterval(200);

    bool success;
    success = connect(m_position_update_timer, SIGNAL(timeout()), this, SLOT(sendPosition()));
    Q_ASSERT(success);

    m_position_update_timer->start();

    changeLoginState(Success);
}

void Server::sendPosition()
{
    PlayerPositionAndLookRequest * request = new PlayerPositionAndLookRequest;
    toNotchianXyz(player_position, request->x, request->y, request->z);
    request->stance = player_position.stance;
    toNotchianYawPitch(player_position, request->yaw, request->pitch);
    request->on_ground = player_position.on_ground;
    sendMessage(QSharedPointer<OutgoingRequest>(request));
}

void Server::changeLoginState(LoginStatus state)
{
    m_login_state = state;
    emit loginStatusUpdated(state);
}

void Server::handleSocketError(QAbstractSocket::SocketError error)
{
    qDebug() << "Socket error: " << error;
    changeLoginState(SocketError);
}

void Server::finishWritingAndDisconnect()
{
    // put a dummy message on the queue
    this->sendMessage(QSharedPointer<OutgoingRequest>(new DummyDisconnectRequest()));
}

Server::LoginStatus Server::loginStatus()
{
    return m_login_state;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "TinyCL.hpp"

int main()
{
	auto device = tcl::information.GetGPU();

	tcl::CLSource source("test.cl", "test", tcl::SourceType::Text);

	tcl::CLExecute exec(source, device);

	const size_t N = 10;
	std::vector<float> input(N), output(N);
	for (int i = 0; i < N; ++i)
	{
		input[i] = i + 1;
		output[i] = 0;
	}

	tcl::CLReadWriteBuffer x(exec, sizeof(float) * N);

	x.Write(input);

	auto settings = tcl::CLWorkGroupSettings(1, { 0 }, { N }, { N }).Optimize(device);
	exec.SetArg(x());
	clSetKernelArg(exec.Kernel(), 0, sizeof(cl_mem), &x());
	exec.Run(settings);

	//clSetKernelArg(exec.Kernel(), 0, sizeof(cl_mem), &x.Memory());
	//size_t of[3] = { 0 };
	//size_t gw[3] = { N };
	//size_t lw[3] = { N };
	//clEnqueueNDRangeKernel(exec.CommandQueue(), exec.Kernel(), 1, of, gw, lw, 0, NULL, NULL);

	x.Read(output);

	for (int i = 0; i < N; ++i)
		std::cout << input[i] << "," << output[i] << std::endl;

	char a;
	std::cin >> a;
}<commit_msg>完成版コードに直す<commit_after>#include <iostream>
#include "TinyCL.hpp"

int main()
{
	auto device = tcl::information.GetGPU();

	tcl::CLSource source("test.cl", "test", tcl::SourceType::Text);

	tcl::CLExecute exec(source, device);

	const size_t N = 10;
	std::vector<float> input(N), output(N);
	for (int i = 0; i < N; ++i)
	{
		input[i] = i + 1;
		output[i] = 0;
	}

	tcl::CLReadWriteBuffer x(exec, sizeof(float) * N);

	x.Write(input);

	auto settings = tcl::CLWorkGroupSettings(1, { 0 }, { N }, { N }).Optimize(device);

	exec.SetArg(x());
	exec.Run(settings);

	x.Read(output);

	for (int i = 0; i < N; ++i)
		std::cout << input[i] << "," << output[i] << std::endl;

	char a;
	std::cin >> a;
}<|endoftext|>