<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

// INCLUDE FILES
#include "bluetoothlinkmanagerdevicediscoverer.h"
#include "qbluetoothaddress.h"
#include "qbluetoothdeviceinfo.h"
#include "qbluetoothuuid.h"

#include <qstring.h>
#ifdef EIR_SUPPORTED
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#include "utils_symbian_p.h"
#include <qdebug.h>

QTM_BEGIN_NAMESPACE

/*! \internal
    \class BluetoothLinkManagerDeviceDiscoverer
    \brief The BluetoothLinkManagerDeviceDiscoverer class searches other bluetooth devices.

    \ingroup connectivity-bluetooth
    \inmodule QtConnectivity
    \internal

    BluetoothLinkManagerDeviceDiscoverer is an Symbian ActiveObject derived class that discovers
    other Bluetooth devices using "BTLinkManager" protocol.

    When Bluetoothdevices are found signal deviceDiscovered(QBluetoothDeviceInfo &) is emitted. When
    all devices are found (or none) signal deviceDiscoveryComplete() is emitted.

    In case of an error signal linkManagerError(int error) is emitted. In the case of errorSignal
    one should consider deleting this class and creating it again.
*/

_LIT(KBTLinkManagerTxt,"BTLinkManager");

BluetoothLinkManagerDeviceDiscoverer::BluetoothLinkManagerDeviceDiscoverer(RSocketServ &socketServer,QObject *parent)
    : QObject(parent)
    , CActive(CActive::EPriorityStandard)
    , m_socketServer(socketServer)
    , m_pendingCancel(false), m_pendingStart(false), m_discoveryType (0)
{
    TInt result;

    /* find Bluetooth protocol */
    TProtocolDesc protocol;
    result = m_socketServer.FindProtocol(KBTLinkManagerTxt(),protocol);
    if (result == KErrNone) {
        /* Create and initialise an RHostResolver */
        result = m_hostResolver.Open(m_socketServer, protocol.iAddrFamily, protocol.iProtocol);
    }
    // check possible error
    if (result != KErrNone) {
        setError(result);
    }

    //add this active object to scheduler
    CActiveScheduler::Add(this);
}

BluetoothLinkManagerDeviceDiscoverer::~BluetoothLinkManagerDeviceDiscoverer()
{
    // cancel active object
    Cancel();
    m_hostResolver.Close();
}
/*!
    Starts up device discovery. When devices are discovered signal deviceDiscovered is emitted.
    After signal deviceDiscoveryComplete() is emitted new discovery request can be made.
*/
void BluetoothLinkManagerDeviceDiscoverer::startDiscovery(const uint discoveryType)
{
    m_discoveryType = discoveryType;

    if(m_pendingCancel == true) {
        m_pendingStart = true;
        m_pendingCancel = false;
        return;
    }
    if (!IsActive()) {
        m_addr.SetIAC( discoveryType );
#ifdef EIR_SUPPORTED
        m_addr.SetAction(KHostResInquiry | KHostResName | KHostResIgnoreCache | KHostResEir);
#else
        m_addr.SetAction(KHostResInquiry | KHostResName | KHostResIgnoreCache);
#endif
        m_hostResolver.GetByAddress(m_addr, m_entry, iStatus);
        SetActive();
    }
}

void BluetoothLinkManagerDeviceDiscoverer::stopDiscovery()
{
    m_pendingStart = false;
    if (IsActive() && !m_pendingCancel) {
        m_pendingCancel = true;
        m_hostResolver.Cancel();
    }
}

/*!
  Informs that our request has been prosessed and the data is available to be used.
*/
void BluetoothLinkManagerDeviceDiscoverer::RunL()
{
    qDebug() << __PRETTY_FUNCTION__ << iStatus.Int();
    switch (iStatus.Int()) {
    case KErrNone:  // found device
        if (m_pendingCancel && !m_pendingStart) {
            m_pendingCancel = false;
            emit canceled();
        } else {
            m_pendingCancel = false;
            m_pendingStart = false;
            // get next (possible) discovered device
            m_hostResolver.Next(m_entry, iStatus);
            SetActive();
            emit deviceDiscovered(currentDeviceDataToQBluetoothDeviceInfo());
        }
        break;
    case KErrHostResNoMoreResults:  // done with search
        if (m_pendingCancel && !m_pendingStart){  // search was canceled prior to finishing
            m_pendingCancel = false;
            m_pendingStart = false;
            emit canceled();
        }
        else if (m_pendingStart){  // search was restarted just prior to finishing
            m_pendingStart = false;
            m_pendingCancel = false;
            startDiscovery(m_discoveryType);
        } else {  // search completed normally
            m_pendingStart = false;
            m_pendingCancel = false;
            emit deviceDiscoveryComplete();
        }
        break;
    case KErrCancel:  // user canceled search
        if (m_pendingStart){  // user activated search after cancel
            m_pendingStart = false;
            m_pendingCancel = false;
            startDiscovery(m_discoveryType);
        } else {  // standard user cancel case
            m_pendingCancel = false;
            emit canceled();
        }
        break;
    default:
        m_pendingStart = false;
        m_pendingCancel = false;
        setError(iStatus.Int());
    }
}
/*!
  Cancel current request.
*/
void BluetoothLinkManagerDeviceDiscoverer::DoCancel()
{
    m_hostResolver.Cancel();
}

TInt BluetoothLinkManagerDeviceDiscoverer::RunError(TInt aError)
{
    setError(aError);
    return KErrNone;
}

bool BluetoothLinkManagerDeviceDiscoverer::isReallyActive() const
{
    if(m_pendingStart)
        return true;
    if(m_pendingCancel)
        return false;
    return IsActive();
}

/*!
    Transforms Symbian device name, address and service classes to QBluetootDeviceInfo.
*/
QBluetoothDeviceInfo BluetoothLinkManagerDeviceDiscoverer::currentDeviceDataToQBluetoothDeviceInfo() const
{
    // extract device information from results and map them to QBluetoothDeviceInfo
#ifdef EIR_SUPPORTED
    TBluetoothNameRecordWrapper eir(m_entry());
    TInt bufferlength = 0;
    QString deviceName;
    bufferlength = eir.GetDeviceNameLength();

    if (bufferlength > 0) {
        TBool nameComplete;
        HBufC *deviceNameBuffer = HBufC::NewLC(bufferlength);
        TPtr ptr = deviceNameBuffer->Des();
        TInt error = eir.GetDeviceName(ptr,nameComplete);
        if (error == KErrNone && nameComplete)
            deviceName = QString::fromUtf16(ptr.Ptr(), ptr.Length()).toUpper();
        CleanupStack::PopAndDestroy(deviceNameBuffer);
    }

    QList<QBluetoothUuid> serviceUidList;
    RExtendedInquiryResponseUUIDContainer uuidContainer;
    QBluetoothDeviceInfo::DataCompleteness completenes = QBluetoothDeviceInfo::DataUnavailable;

    if (eir.GetServiceClassUuids(uuidContainer) == KErrNone) {
        TInt uuidCount = uuidContainer.UUIDs().Count();
        if (uuidCount > 0) {
            for (int i = 0; i < uuidCount; ++i) {
                TPtrC8 shortFormUUid(uuidContainer.UUIDs()[i].ShortestForm());
                if (shortFormUUid.Size() == 2) {
                    QBluetoothUuid uuid(ntohs(*reinterpret_cast<const quint16 *>(shortFormUUid.Ptr())));
                    if (uuidContainer.GetCompleteness(RExtendedInquiryResponseUUIDContainer::EUUID16))
                        completenes = QBluetoothDeviceInfo::DataComplete;
                    else
                        completenes = QBluetoothDeviceInfo::DataIncomplete;
                    serviceUidList.append(uuid);
                }else if (shortFormUUid.Size() == 4) {
                    QBluetoothUuid uuid(ntohl(*reinterpret_cast<const quint32 *>(shortFormUUid.Ptr())));
                    if (uuidContainer.GetCompleteness(RExtendedInquiryResponseUUIDContainer::EUUID32))
                        completenes = QBluetoothDeviceInfo::DataComplete;
                    else
                        completenes = QBluetoothDeviceInfo::DataIncomplete;
                    serviceUidList.append(uuid);
                }else if (shortFormUUid.Size() == 16) {
                    QBluetoothUuid uuid(*reinterpret_cast<const quint128 *>(shortFormUUid.Ptr()));
                    if (uuidContainer.GetCompleteness(RExtendedInquiryResponseUUIDContainer::EUUID128))
                        completenes = QBluetoothDeviceInfo::DataComplete;
                    else
                        completenes = QBluetoothDeviceInfo::DataIncomplete;
                    serviceUidList.append(uuid);
                }
            }
        }
    }
    uuidContainer.Close();

    bufferlength = 0;
    QByteArray manufacturerData;
    bufferlength = eir.GetVendorSpecificDataLength();

    if (bufferlength > 0) {
        HBufC8 *msd = HBufC8::NewLC(bufferlength);
        TPtr8 temp = msd->Des();
        if (eir.GetVendorSpecificData(temp))
            manufacturerData = s60Desc8ToQByteArray(temp);
        CleanupStack::PopAndDestroy(msd);
    }

    // Get transmission power level
    TInt8 transmissionPowerLevel = 0;
    eir.GetTxPowerLevel(transmissionPowerLevel);

    // unique address of the device
    const TBTDevAddr symbianDeviceAddress = static_cast<TBTSockAddr> (m_entry().iAddr).BTAddr();
    QBluetoothAddress bluetoothAddress = qTBTDevAddrToQBluetoothAddress(symbianDeviceAddress);

    // format symbian major/minor numbers
    quint32 deviceClass = qTPackSymbianDeviceClass(m_addr);

    QBluetoothDeviceInfo deviceInfo(bluetoothAddress, deviceName, deviceClass);

    deviceInfo.setRssi(transmissionPowerLevel);
    deviceInfo.setServiceUuids(serviceUidList, completenes);
    deviceInfo.setManufacturerSpecificData(manufacturerData);
#else
    // device name
    THostName symbianDeviceName = m_entry().iName;
    QString deviceName = QString::fromUtf16(symbianDeviceName.Ptr(), symbianDeviceName.Length()).toUpper();

    // unique address of the device
    const TBTDevAddr symbianDeviceAddress = static_cast<TBTSockAddr> (m_entry().iAddr).BTAddr();
    QBluetoothAddress bluetoothAddress = qTBTDevAddrToQBluetoothAddress(symbianDeviceAddress);

    // format symbian major/minor numbers
    quint32 deviceClass = qTPackSymbianDeviceClass(m_addr);

    QBluetoothDeviceInfo deviceInfo(bluetoothAddress, deviceName, deviceClass);

    if (m_addr.Rssi())
        deviceInfo.setRssi(m_addr.Rssi());
#endif
    if (!deviceInfo.rssi())
        deviceInfo.setRssi(1);

    deviceInfo.setCached(false);  //TODO cache support missing from devicediscovery API
    //qDebug()<< "Discovered device: name="<< deviceName <<", address=" << bluetoothAddress.toString() <<", class=" << deviceClass;
    return deviceInfo;
}

void BluetoothLinkManagerDeviceDiscoverer::setError(int errorCode)
{
    qDebug() << __PRETTY_FUNCTION__ << "errorCode=" << errorCode;
    QString errorString;
    switch (errorCode) {
        case KLinkManagerErrBase:
            errorString.append("Link manager base error value or Insufficient baseband resources error value");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrProxyWriteNotAvailable:
            errorString.append("Proxy write not available error value");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrReflexiveBluetoothLink:
            errorString.append("Reflexive BT link error value");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrPendingPhysicalLink:
            errorString.append("Physical link connection already pending when trying to connect the physical link");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrNotReady:
            errorString.append("KErrNotReady");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
        case KErrCancel:
            errorString.append("KErrCancel");
            qDebug() << "emitting canceled";
            emit canceled();
            break;
        case KErrNone:
            // do nothing
            break;
        default:
            errorString.append("Symbian errorCode =") + errorCode;
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
    }
}
#include "moc_bluetoothlinkmanagerdevicediscoverer.cpp"

QTM_END_NAMESPACE
<commit_msg>Fix device discovery in Symbian Bluetooth backend<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

// INCLUDE FILES
#include "bluetoothlinkmanagerdevicediscoverer.h"
#include "qbluetoothaddress.h"
#include "qbluetoothdeviceinfo.h"
#include "qbluetoothuuid.h"

#include <qstring.h>
#ifdef EIR_SUPPORTED
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#include "utils_symbian_p.h"
#include <qdebug.h>

QTM_BEGIN_NAMESPACE

/*! \internal
    \class BluetoothLinkManagerDeviceDiscoverer
    \brief The BluetoothLinkManagerDeviceDiscoverer class searches other bluetooth devices.

    \ingroup connectivity-bluetooth
    \inmodule QtConnectivity
    \internal

    BluetoothLinkManagerDeviceDiscoverer is an Symbian ActiveObject derived class that discovers
    other Bluetooth devices using "BTLinkManager" protocol.

    When Bluetoothdevices are found signal deviceDiscovered(QBluetoothDeviceInfo &) is emitted. When
    all devices are found (or none) signal deviceDiscoveryComplete() is emitted.

    In case of an error signal linkManagerError(int error) is emitted. In the case of errorSignal
    one should consider deleting this class and creating it again.
*/

_LIT(KBTLinkManagerTxt,"BTLinkManager");

BluetoothLinkManagerDeviceDiscoverer::BluetoothLinkManagerDeviceDiscoverer(RSocketServ &socketServer,QObject *parent)
    : QObject(parent)
    , CActive(CActive::EPriorityStandard)
    , m_socketServer(socketServer)
    , m_pendingCancel(false), m_pendingStart(false), m_discoveryType (0)
{
    TInt result;

    /* find Bluetooth protocol */
    TProtocolDesc protocol;
    result = m_socketServer.FindProtocol(KBTLinkManagerTxt(),protocol);
    if (result == KErrNone) {
        /* Create and initialise an RHostResolver */
        result = m_hostResolver.Open(m_socketServer, protocol.iAddrFamily, protocol.iProtocol);
    }
    // check possible error
    if (result != KErrNone) {
        setError(result);
    }

    //add this active object to scheduler
    CActiveScheduler::Add(this);
}

BluetoothLinkManagerDeviceDiscoverer::~BluetoothLinkManagerDeviceDiscoverer()
{
    // cancel active object
    Cancel();
    m_hostResolver.Close();
}
/*!
    Starts up device discovery. When devices are discovered signal deviceDiscovered is emitted.
    After signal deviceDiscoveryComplete() is emitted new discovery request can be made.
*/
void BluetoothLinkManagerDeviceDiscoverer::startDiscovery(const uint discoveryType)
{
    m_discoveryType = discoveryType;

    if(m_pendingCancel == true) {
        m_pendingStart = true;
        m_pendingCancel = false;
        return;
    }
    if (!IsActive()) {
        m_addr.SetIAC( discoveryType );
#ifdef EIR_SUPPORTED
        m_addr.SetAction(KHostResInquiry | KHostResName | KHostResIgnoreCache | KHostResEir);
#else
        m_addr.SetAction(KHostResInquiry | KHostResName | KHostResIgnoreCache);
#endif
        m_hostResolver.GetByAddress(m_addr, m_entry, iStatus);
        SetActive();
    }
}

void BluetoothLinkManagerDeviceDiscoverer::stopDiscovery()
{
    m_pendingStart = false;
    if (IsActive() && !m_pendingCancel) {
        m_pendingCancel = true;
        m_hostResolver.Cancel();
    }
}

/*!
  Informs that our request has been prosessed and the data is available to be used.
*/
void BluetoothLinkManagerDeviceDiscoverer::RunL()
{
    qDebug() << __PRETTY_FUNCTION__ << iStatus.Int();
    switch (iStatus.Int()) {
    case KErrNone:  // found device
        if (m_pendingCancel && !m_pendingStart) {
            m_pendingCancel = false;
            emit canceled();
        } else {
            m_pendingCancel = false;
            m_pendingStart = false;
            // get next (possible) discovered device
            m_hostResolver.Next(m_entry, iStatus);
            SetActive();
            emit deviceDiscovered(currentDeviceDataToQBluetoothDeviceInfo());
        }
        break;
    case KErrHostResNoMoreResults:  // done with search
        if (m_pendingCancel && !m_pendingStart){  // search was canceled prior to finishing
            m_pendingCancel = false;
            m_pendingStart = false;
            emit canceled();
        }
        else if (m_pendingStart){  // search was restarted just prior to finishing
            m_pendingStart = false;
            m_pendingCancel = false;
            startDiscovery(m_discoveryType);
        } else {  // search completed normally
            m_pendingStart = false;
            m_pendingCancel = false;
            emit deviceDiscoveryComplete();
        }
        break;
    case KErrCancel:  // user canceled search
        if (m_pendingStart){  // user activated search after cancel
            m_pendingStart = false;
            m_pendingCancel = false;
            startDiscovery(m_discoveryType);
        } else {  // standard user cancel case
            m_pendingCancel = false;
            emit canceled();
        }
        break;
    default:
        m_pendingStart = false;
        m_pendingCancel = false;
        setError(iStatus.Int());
    }
}
/*!
  Cancel current request.
*/
void BluetoothLinkManagerDeviceDiscoverer::DoCancel()
{
    m_hostResolver.Cancel();
}

TInt BluetoothLinkManagerDeviceDiscoverer::RunError(TInt aError)
{
    setError(aError);
    return KErrNone;
}

bool BluetoothLinkManagerDeviceDiscoverer::isReallyActive() const
{
    if(m_pendingStart)
        return true;
    if(m_pendingCancel)
        return false;
    return IsActive();
}

/*!
    Transforms Symbian device name, address and service classes to QBluetootDeviceInfo.
*/
QBluetoothDeviceInfo BluetoothLinkManagerDeviceDiscoverer::currentDeviceDataToQBluetoothDeviceInfo() const
{
    // extract device information from results and map them to QBluetoothDeviceInfo
#ifdef EIR_SUPPORTED
    TBluetoothNameRecordWrapper eir(m_entry());
    TInt bufferlength = 0;
    TInt err = KErrNone;
    QString deviceName;
    bufferlength = eir.GetDeviceNameLength();

    if (bufferlength > 0) {
        TBool nameComplete;
        HBufC *deviceNameBuffer = 0;
        TRAP(err,deviceNameBuffer = HBufC::NewLC(bufferlength));
        if(err)
            deviceName = QString();
        else
            {
            TPtr ptr = deviceNameBuffer->Des();
            err = eir.GetDeviceName(ptr,nameComplete);
            if (err == KErrNone /*&& nameComplete*/)
                {
                if(!nameComplete)
                    qWarning() << "device name incomplete";
                // isn't it better to get an incomplete name than getting nothing?
                deviceName = QString::fromUtf16(ptr.Ptr(), ptr.Length()).toUpper();
                }
            else
                deviceName = QString();
            CleanupStack::PopAndDestroy(deviceNameBuffer);
            }
    }

    QList<QBluetoothUuid> serviceUidList;
    RExtendedInquiryResponseUUIDContainer uuidContainer;
    QBluetoothDeviceInfo::DataCompleteness completenes = QBluetoothDeviceInfo::DataUnavailable;

    if (eir.GetServiceClassUuids(uuidContainer) == KErrNone) {
        TInt uuidCount = uuidContainer.UUIDs().Count();
        if (uuidCount > 0) {
            for (int i = 0; i < uuidCount; ++i) {
                TPtrC8 shortFormUUid(uuidContainer.UUIDs()[i].ShortestForm());
                if (shortFormUUid.Size() == 2) {
                    QBluetoothUuid uuid(ntohs(*reinterpret_cast<const quint16 *>(shortFormUUid.Ptr())));
                    if (uuidContainer.GetCompleteness(RExtendedInquiryResponseUUIDContainer::EUUID16))
                        completenes = QBluetoothDeviceInfo::DataComplete;
                    else
                        completenes = QBluetoothDeviceInfo::DataIncomplete;
                    serviceUidList.append(uuid);
                }else if (shortFormUUid.Size() == 4) {
                    QBluetoothUuid uuid(ntohl(*reinterpret_cast<const quint32 *>(shortFormUUid.Ptr())));
                    if (uuidContainer.GetCompleteness(RExtendedInquiryResponseUUIDContainer::EUUID32))
                        completenes = QBluetoothDeviceInfo::DataComplete;
                    else
                        completenes = QBluetoothDeviceInfo::DataIncomplete;
                    serviceUidList.append(uuid);
                }else if (shortFormUUid.Size() == 16) {
                    QBluetoothUuid uuid(*reinterpret_cast<const quint128 *>(shortFormUUid.Ptr()));
                    if (uuidContainer.GetCompleteness(RExtendedInquiryResponseUUIDContainer::EUUID128))
                        completenes = QBluetoothDeviceInfo::DataComplete;
                    else
                        completenes = QBluetoothDeviceInfo::DataIncomplete;
                    serviceUidList.append(uuid);
                }
            }
        }
    }
    uuidContainer.Close();

    bufferlength = 0;
    QByteArray manufacturerData;
    bufferlength = eir.GetVendorSpecificDataLength();

    if (bufferlength > 0) {
        HBufC8 *msd = 0;
        TRAP(err,HBufC8::NewLC(bufferlength));
        if(err)
            manufacturerData = QByteArray();
        else
            {
            TPtr8 temp = msd->Des();
            if (eir.GetVendorSpecificData(temp))
                manufacturerData = s60Desc8ToQByteArray(temp);
            else
                manufacturerData = QByteArray();
            CleanupStack::PopAndDestroy(msd);
            }
    }

    // Get transmission power level
    TInt8 transmissionPowerLevel = 0;
    eir.GetTxPowerLevel(transmissionPowerLevel);

    // unique address of the device
    const TBTDevAddr symbianDeviceAddress = static_cast<TBTSockAddr> (m_entry().iAddr).BTAddr();
    QBluetoothAddress bluetoothAddress = qTBTDevAddrToQBluetoothAddress(symbianDeviceAddress);

    // format symbian major/minor numbers
    quint32 deviceClass = qTPackSymbianDeviceClass(m_addr);

    QBluetoothDeviceInfo deviceInfo(bluetoothAddress, deviceName, deviceClass);

    deviceInfo.setRssi(transmissionPowerLevel);
    deviceInfo.setServiceUuids(serviceUidList, completenes);
    deviceInfo.setManufacturerSpecificData(manufacturerData);
#else
    // device name
    THostName symbianDeviceName = m_entry().iName;
    QString deviceName = QString::fromUtf16(symbianDeviceName.Ptr(), symbianDeviceName.Length()).toUpper();

    // unique address of the device
    const TBTDevAddr symbianDeviceAddress = static_cast<TBTSockAddr> (m_entry().iAddr).BTAddr();
    QBluetoothAddress bluetoothAddress = qTBTDevAddrToQBluetoothAddress(symbianDeviceAddress);

    // format symbian major/minor numbers
    quint32 deviceClass = qTPackSymbianDeviceClass(m_addr);

    QBluetoothDeviceInfo deviceInfo(bluetoothAddress, deviceName, deviceClass);

    if (m_addr.Rssi())
        deviceInfo.setRssi(m_addr.Rssi());
#endif
    if (!deviceInfo.rssi())
        deviceInfo.setRssi(1);

    deviceInfo.setCached(false);  //TODO cache support missing from devicediscovery API
    //qDebug()<< "Discovered device: name="<< deviceName <<", address=" << bluetoothAddress.toString() <<", class=" << deviceClass;
    return deviceInfo;
}

void BluetoothLinkManagerDeviceDiscoverer::setError(int errorCode)
{
    qDebug() << __PRETTY_FUNCTION__ << "errorCode=" << errorCode;
    QString errorString;
    switch (errorCode) {
        case KLinkManagerErrBase:
            errorString.append("Link manager base error value or Insufficient baseband resources error value");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrProxyWriteNotAvailable:
            errorString.append("Proxy write not available error value");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrReflexiveBluetoothLink:
            errorString.append("Reflexive BT link error value");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrPendingPhysicalLink:
            errorString.append("Physical link connection already pending when trying to connect the physical link");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
        case KErrNotReady:
            errorString.append("KErrNotReady");
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
        case KErrCancel:
            errorString.append("KErrCancel");
            qDebug() << "emitting canceled";
            emit canceled();
            break;
        case KErrNone:
            // do nothing
            break;
        default:
            errorString = QString("Symbian errorCode = %1").arg(errorCode);
            emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError, errorString);
            break;
    }
}
#include "moc_bluetoothlinkmanagerdevicediscoverer.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>#pragma once

#include "types/json_unmarshal_error.hpp"
#include <unordered_set>

namespace krbn {
namespace manipulator {
namespace modifier_definition {
enum class modifier {
  any,
  caps_lock,
  command,
  control,
  fn,
  left_command,
  left_control,
  left_option,
  left_shift,
  option,
  right_command,
  right_control,
  right_option,
  right_shift,
  shift,
  end_,
};

inline void to_json(nlohmann::json& json, const modifier& value) {
  switch (value) {
    case modifier::any:
      json = "any";
      break;
    case modifier::caps_lock:
      json = "caps_lock";
      break;
    case modifier::command:
      json = "command";
      break;
    case modifier::control:
      json = "control";
      break;
    case modifier::fn:
      json = "fn";
      break;
    case modifier::left_command:
      json = "left_command";
      break;
    case modifier::left_control:
      json = "left_control";
      break;
    case modifier::left_option:
      json = "left_option";
      break;
    case modifier::left_shift:
      json = "left_shift";
      break;
    case modifier::option:
      json = "option";
      break;
    case modifier::right_command:
      json = "right_command";
      break;
    case modifier::right_control:
      json = "right_control";
      break;
    case modifier::right_option:
      json = "right_option";
      break;
    case modifier::right_shift:
      json = "right_shift";
      break;
    case modifier::shift:
      json = "shift";
      break;
    case modifier::end_:
      json = "end_";
      break;
    default:
      json = nullptr;
  }
}

inline void from_json(const nlohmann::json& json, modifier& value) {
  if (!json.is_string()) {
    throw json_unmarshal_error(fmt::format("modifier must be string, but is `{0}`", json.dump()));
  }

  auto name = json.get<std::string>();
  if (name == "any") {
    value = modifier::any;
  } else if (name == "caps_lock") {
    value = modifier::caps_lock;
  } else if (name == "command") {
    value = modifier::command;
  } else if (name == "control") {
    value = modifier::control;
  } else if (name == "fn") {
    value = modifier::fn;
  } else if (name == "left_command") {
    value = modifier::left_command;
  } else if (name == "left_control") {
    value = modifier::left_control;
  } else if (name == "left_option") {
    value = modifier::left_option;
  } else if (name == "left_shift") {
    value = modifier::left_shift;
  } else if (name == "option") {
    value = modifier::option;
  } else if (name == "right_command") {
    value = modifier::right_command;
  } else if (name == "right_control") {
    value = modifier::right_control;
  } else if (name == "right_option") {
    value = modifier::right_option;
  } else if (name == "right_shift") {
    value = modifier::right_shift;
  } else if (name == "shift") {
    value = modifier::shift;
  } else if (name == "end_") {
    value = modifier::end_;
  } else {
    throw json_unmarshal_error(fmt::format("unknown modifier: `{0}`", name));
  }
}

inline std::ostream& operator<<(std::ostream& stream, const modifier& value) {
  return stream << nlohmann::json(value);
}

template <template <class T, class A> class container>
inline std::ostream& operator<<(std::ostream& stream, const container<modifier, std::allocator<modifier>>& values) {
  return stream << nlohmann::json(values);
}

template <template <class T, class H, class K, class A> class container>
inline std::ostream& operator<<(std::ostream& stream,
                                const container<modifier,
                                                std::hash<modifier>,
                                                std::equal_to<modifier>,
                                                std::allocator<modifier>>& values) {
  return stream << nlohmann::json(values);
}
} // namespace modifier_definition
} // namespace manipulator
} // namespace krbn
<commit_msg>update #include<commit_after>#pragma once

#include "types/json_unmarshal_error.hpp"
#include <nlohmann/json.hpp>
#include <unordered_set>

namespace krbn {
namespace manipulator {
namespace modifier_definition {
enum class modifier {
  any,
  caps_lock,
  command,
  control,
  fn,
  left_command,
  left_control,
  left_option,
  left_shift,
  option,
  right_command,
  right_control,
  right_option,
  right_shift,
  shift,
  end_,
};

inline void to_json(nlohmann::json& json, const modifier& value) {
  switch (value) {
    case modifier::any:
      json = "any";
      break;
    case modifier::caps_lock:
      json = "caps_lock";
      break;
    case modifier::command:
      json = "command";
      break;
    case modifier::control:
      json = "control";
      break;
    case modifier::fn:
      json = "fn";
      break;
    case modifier::left_command:
      json = "left_command";
      break;
    case modifier::left_control:
      json = "left_control";
      break;
    case modifier::left_option:
      json = "left_option";
      break;
    case modifier::left_shift:
      json = "left_shift";
      break;
    case modifier::option:
      json = "option";
      break;
    case modifier::right_command:
      json = "right_command";
      break;
    case modifier::right_control:
      json = "right_control";
      break;
    case modifier::right_option:
      json = "right_option";
      break;
    case modifier::right_shift:
      json = "right_shift";
      break;
    case modifier::shift:
      json = "shift";
      break;
    case modifier::end_:
      json = "end_";
      break;
    default:
      json = nullptr;
  }
}

inline void from_json(const nlohmann::json& json, modifier& value) {
  if (!json.is_string()) {
    throw json_unmarshal_error(fmt::format("modifier must be string, but is `{0}`", json.dump()));
  }

  auto name = json.get<std::string>();
  if (name == "any") {
    value = modifier::any;
  } else if (name == "caps_lock") {
    value = modifier::caps_lock;
  } else if (name == "command") {
    value = modifier::command;
  } else if (name == "control") {
    value = modifier::control;
  } else if (name == "fn") {
    value = modifier::fn;
  } else if (name == "left_command") {
    value = modifier::left_command;
  } else if (name == "left_control") {
    value = modifier::left_control;
  } else if (name == "left_option") {
    value = modifier::left_option;
  } else if (name == "left_shift") {
    value = modifier::left_shift;
  } else if (name == "option") {
    value = modifier::option;
  } else if (name == "right_command") {
    value = modifier::right_command;
  } else if (name == "right_control") {
    value = modifier::right_control;
  } else if (name == "right_option") {
    value = modifier::right_option;
  } else if (name == "right_shift") {
    value = modifier::right_shift;
  } else if (name == "shift") {
    value = modifier::shift;
  } else if (name == "end_") {
    value = modifier::end_;
  } else {
    throw json_unmarshal_error(fmt::format("unknown modifier: `{0}`", name));
  }
}

inline std::ostream& operator<<(std::ostream& stream, const modifier& value) {
  return stream << nlohmann::json(value);
}

template <template <class T, class A> class container>
inline std::ostream& operator<<(std::ostream& stream, const container<modifier, std::allocator<modifier>>& values) {
  return stream << nlohmann::json(values);
}

template <template <class T, class H, class K, class A> class container>
inline std::ostream& operator<<(std::ostream& stream,
                                const container<modifier,
                                                std::hash<modifier>,
                                                std::equal_to<modifier>,
                                                std::allocator<modifier>>& values) {
  return stream << nlohmann::json(values);
}
} // namespace modifier_definition
} // namespace manipulator
} // namespace krbn
<|endoftext|>


<commit_before>#include "SymbianCallInitiator.h"
#include "SymbianCallInitiatorPrivate.h"
#include "SymbianCallObserverPrivate.h"
#include "SymbianDTMFPrivate.h"

SymbianCallInitiator::SymbianCallInitiator (QObject *parent)
: CalloutInitiator(parent)
, dialer (NULL)
, observer (NULL)
, dtmfSender (NULL)
{
    iTelephony = CTelephony::NewL();
    dtmfSender = new SymbianDTMFPrivate (this);
    if (NULL != iTelephony) {
        delete iTelephony;
    }
}//SymbianCallInitiator::SymbianCallInitiator

SymbianCallInitiator::~SymbianCallInitiator()
{
    if (NULL != observer) {
        delete observer;
    }
    if (NULL != dialer) {
        delete dialer;
    }
    if (NULL != dtmfSender) {
        delete dtmfSender;
    }
}//SymbianCallInitiator::~SymbianCallInitiator

QString
SymbianCallInitiator::name ()
{
    return "Phone";
}//SymbianCallInitiator::name

QString
SymbianCallInitiator::selfNumber ()
{
    return "This phone's MSISDN";
}//SymbianCallInitiator::selfNumber

bool
SymbianCallInitiator::isValid ()
{
    return true;
}//SymbianCallInitiator::isValid

void
SymbianCallInitiator::initiateCall (const QString &strDestination,
                                    void *ctx /*= NULL*/)
{
    bool bOk = false;
    m_Context = ctx;
    do { // Begin cleanup block (not a loop)
        if (NULL != dialer) {
            qWarning ("Call in progress. Ask again later.");
            break;  // false
        }
        if (NULL != observer) {
            qWarning ("observer was still alive. WTF?");
            delete observer;
        }
        observer = SymbianCallObserverPrivate::NewL (this);

        QMutexLocker locker(&mutex);
        strObservedNumber = strDestination;

        dialer = SymbianCallInitiatorPrivate::NewL (this, strDestination);
        if (NULL == dialer) {
            qWarning ("Could not dial out.");
            break;  // false
        }
        bOk = true;
    } while (0); // End cleanup block (not a loop)
    if (!bOk) {
        emit callInitiated (false, m_Context);
    }
}//SymbianCallInitiator::initiateCall

void
SymbianCallInitiator::callDone (SymbianCallInitiatorPrivate *self, int status)
{
    delete self;

    QMutexLocker locker(&mutex);
    strObservedNumber.clear ();

    if (dialer == self) {
        dialer = NULL;

        if (NULL != observer) {
            delete observer;
            observer = NULL;
        }
    } else {
        qWarning ("Dialer does not match!!!");
    }

    emit callInitiated ((status == KErrNone), m_Context);
}//SymbianCallInitiator::callDone

void
SymbianCallInitiator::onCallInitiated ()
{
    bool bObserving = false;
    {
        QMutexLocker locker(&mutex);
        if (!strObservedNumber.isEmpty ()) {
            bObserving = true;
        }
    }

    if (bObserving) {
        emit callDialed();
    }
}//SymbianCallInitiator::onCallInitiated

bool
SymbianCallInitiator::sendDTMF (const QString &strTones)
{
    arrTones.clear ();
    arrTones = strTones.split ('p');

    nextDtmf ();
    return true;
}//SymbianCallInitiator::sendDTMF

void
SymbianCallInitiator::onDtmfSent (SymbianDTMFPrivate *self, bool bSuccess)
{
    qDebug() << "Send DTMF " << (bSuccess ? "suceeded" : "failed");
    QTimer::singleShot (1000, this, SLOT(nextDtmf ()));
}//SymbianCallInitiator::onDtmfSent

void
SymbianCallInitiator::nextDtmf()
{
    if (arrTones.isEmpty ()) {
        qDebug ("No more tones");
        return;
    }

    QString strTones = arrTones.first ();
    arrTones.pop_front ();

    if (strTones.isEmpty ()) {
        qDebug ("Blank tone");
        QTimer::singleShot (1000, this, SLOT(nextDtmf ()));
    } else {
        qDebug () << "Current tone =" << strTones;

        dtmfSender->sendDTMF (strTones);
    }
}//SymbianCallInitiator::nextDtmf
<commit_msg>Bug: CTelephony object was freed immediately after being allocated.<commit_after>#include "SymbianCallInitiator.h"
#include "SymbianCallInitiatorPrivate.h"
#include "SymbianCallObserverPrivate.h"
#include "SymbianDTMFPrivate.h"

SymbianCallInitiator::SymbianCallInitiator (QObject *parent)
: CalloutInitiator(parent)
, dialer (NULL)
, observer (NULL)
, dtmfSender (NULL)
{
    iTelephony = CTelephony::NewL();
    dtmfSender = new SymbianDTMFPrivate (this);
}//SymbianCallInitiator::SymbianCallInitiator

SymbianCallInitiator::~SymbianCallInitiator()
{
    if (NULL != observer) {
        delete observer;
    }
    if (NULL != dialer) {
        delete dialer;
    }
    if (NULL != dtmfSender) {
        delete dtmfSender;
    }
    if (NULL != iTelephony) {
        delete iTelephony;
    }
}//SymbianCallInitiator::~SymbianCallInitiator

QString
SymbianCallInitiator::name ()
{
    return "Phone";
}//SymbianCallInitiator::name

QString
SymbianCallInitiator::selfNumber ()
{
    return "This phone's MSISDN";
}//SymbianCallInitiator::selfNumber

bool
SymbianCallInitiator::isValid ()
{
    return true;
}//SymbianCallInitiator::isValid

void
SymbianCallInitiator::initiateCall (const QString &strDestination,
                                    void *ctx /*= NULL*/)
{
    bool bOk = false;
    m_Context = ctx;
    do { // Begin cleanup block (not a loop)
        if (NULL != dialer) {
            qWarning ("Call in progress. Ask again later.");
            break;  // false
        }
        if (NULL != observer) {
            qWarning ("observer was still alive. WTF?");
            delete observer;
        }
        observer = SymbianCallObserverPrivate::NewL (this);

        QMutexLocker locker(&mutex);
        strObservedNumber = strDestination;

        dialer = SymbianCallInitiatorPrivate::NewL (this, strDestination);
        if (NULL == dialer) {
            delete observer;
            observer = NULL;
            qWarning ("Could not dial out.");
            break;  // false
        }
        bOk = true;
    } while (0); // End cleanup block (not a loop)
    if (!bOk) {
        emit callInitiated (false, m_Context);
    }
}//SymbianCallInitiator::initiateCall

void
SymbianCallInitiator::callDone (SymbianCallInitiatorPrivate *self, int status)
{
    delete self;

    QMutexLocker locker(&mutex);
    strObservedNumber.clear ();

    if (dialer == self) {
        dialer = NULL;

        if (NULL != observer) {
            delete observer;
            observer = NULL;
        }
    } else {
        qWarning ("Dialer does not match!!!");
    }

    emit callInitiated ((status == KErrNone), m_Context);
}//SymbianCallInitiator::callDone

void
SymbianCallInitiator::onCallInitiated ()
{
    bool bObserving = false;
    {
        QMutexLocker locker(&mutex);
        if (!strObservedNumber.isEmpty ()) {
            bObserving = true;
        }
    }

    if (bObserving) {
        emit callDialed();
    }
}//SymbianCallInitiator::onCallInitiated

bool
SymbianCallInitiator::sendDTMF (const QString &strTones)
{
    arrTones.clear ();
    arrTones = strTones.split ('p');

    nextDtmf ();
    return true;
}//SymbianCallInitiator::sendDTMF

void
SymbianCallInitiator::onDtmfSent (SymbianDTMFPrivate *self, bool bSuccess)
{
    qDebug() << "Send DTMF " << (bSuccess ? "suceeded" : "failed");
    QTimer::singleShot (1000, this, SLOT(nextDtmf ()));
}//SymbianCallInitiator::onDtmfSent

void
SymbianCallInitiator::nextDtmf()
{
    if (arrTones.isEmpty ()) {
        qDebug ("No more tones");
        return;
    }

    QString strTones = arrTones.first ();
    arrTones.pop_front ();

    if (strTones.isEmpty ()) {
        qDebug ("Blank tone");
        QTimer::singleShot (1000, this, SLOT(nextDtmf ()));
    } else {
        qDebug () << "Current tone =" << strTones;

        dtmfSender->sendDTMF (strTones);
    }
}//SymbianCallInitiator::nextDtmf
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XOBJECTFACTORY_HEADER_GUARD_1357924680)
#define XOBJECTFACTORY_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <algorithm>
#include <cassert>
#include <set>

#include <XPath/XObject.hpp>

class XalanNode;
class MutableNodeRefList;
class NodeRefListBase;
class ResultTreeFragBase;
class XObject;

/**
 * This class handles the creation of XObjects and manages their lifetime.
 */
class XALAN_XPATH_EXPORT XObjectFactory
{
public:

	XObjectFactory();

	virtual
	~XObjectFactory();

	/**
	 * Return an XObject to the factory.
	 *
	 * @param theXObject The XObject to be returned
	 * @return true if the object belongs to the factory, false if not.
	 */
	bool
	returnObject(const XObject*		theXObject)
	{
		return doReturnObject(theXObject);
	}

	/**
	 * Reset the instance.  This invalidates all existing instances created
	 * with this XObjectFactory.
	 */
	virtual void
	reset() = 0;

	/**
	 * Clone an XObject instance, and hold in the factory.
	 *
	 * @param theXObject the instance to clone
	 * @return a clone of the instance.
	 */
	virtual XObject*
	clone(const XObject&	theXObject) = 0;

	/**
	 * Create a boolean XObject from a boolean value.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize true to use static objects rather than creating new
	 *                  instances, default true
	 * @return pointer to new object
	 */
	virtual XObject*
	createBoolean(
			bool	theValue,
			bool	fOptimize = true) = 0;

	/**
	 * Create a node set XObject from a node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNodeSet(
			const NodeRefListBase&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create a node set XObject from a mutable node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNodeSet(
			const MutableNodeRefList&	theValue,
			bool						fOptimize = true) = 0;

	/**
	 * Create a node set XObject from a DOM node.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNodeSet(
			XalanNode&	theValue,
			bool		fOptimize = true) = 0;

	/**
	 * Create a null XObject.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize true to use static objects rather than creating new
	 *                  instances, default true
	 * @return pointer to new object
	 */
	virtual XObject*
	createNull(bool	fOptimize = true) = 0;

	/**
	 * Create a numeric XObject from a number.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNumber(
			double	theValue,
			bool	fOptimize = true) = 0;

	/**
	 * Create a string XObject from a string.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createString(
			const XalanDOMString&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create an "unknown" XObject from a string.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createUnknown(
			const XalanDOMString&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create a result tree fragment XObject from a result tree fragment.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createResultTreeFrag(
			const ResultTreeFragBase&	theValue,
			bool						fOptimize = true) = 0;

	/**
	 * Create a span XObject from a node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createSpan(
			const NodeRefListBase&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create a span XObject from a mutable node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createSpan(
			const MutableNodeRefList&	theValue,
			bool						fOptimize = true) = 0;

	/**
	 * Create a span XObject from a DOM node.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createSpan(
			XalanNode&	theValue,
			bool		fOptimize = true) = 0;

	/**
	 *
	 * A public functor for use with stl algorithms.
	 *
	 */
#if defined(XALAN_NO_NAMESPACES)
	struct DeleteXObjectFunctor : public unary_function<const XObject*, void>
#else
	struct DeleteXObjectFunctor : public std::unary_function<const XObject*, void>
#endif
	{
	public:

		DeleteXObjectFunctor(XObjectFactory&	theFactoryInstance) :
			m_factoryInstance(theFactoryInstance)
		{
		}

		result_type
		operator()(argument_type	theXObject) const
		{
			m_factoryInstance.returnObject(theXObject);
		}

	private:

		XObjectFactory&		m_factoryInstance;
	};

protected:

	/**
	 * Delete a FactoryObject instance.
	 *
	 * @param theXObject the XObject instance to delete.
	 */
	void
	deleteObject(const XObject*		theXObject) const
	{
		delete theXObject;
	}

	/**
	 * Return an XObject to the factory.
	 *
	 * @param theXObject XObject to be returned
	 * @param fInReset true when called during reset().
	 */

	virtual bool
	doReturnObject(
			const XObject*	theXObject,
			bool			fInReset = false) = 0;

	/**
	 *
	 * A functor for use with stl algorithms.
	 *
	 */
#if defined(XALAN_NO_NAMESPACES)
	struct ProtectedDeleteXObjectFunctor : public unary_function<const XObject*, void>
#else
	struct ProtectedDeleteXObjectFunctor : public std::unary_function<const XObject*, void>
#endif
	{
	public:

		ProtectedDeleteXObjectFunctor(
			XObjectFactory&		theFactoryInstance,
			bool				fInReset) :
			m_factoryInstance(theFactoryInstance),
			m_fInReset(fInReset)
		{
		}

		result_type
		operator()(argument_type	theXObject) const
		{
			m_factoryInstance.doReturnObject(theXObject,
											 m_fInReset);
		}

	private:

		XObjectFactory&		m_factoryInstance;

		const bool			m_fInReset;
	};

	friend struct ProtectedDeleteXObjectFunctor;

private:

	// Not implemented...
	XObjectFactory(const XObjectFactory&);

	XObjectFactory&
	operator=(const XObjectFactory&);

	bool
	operator==(const XObjectFactory&) const;
};

/**
 * Manages the lifetime of an XObject instance.
 */
class XObjectGuard
{
public:

	/**
	 * Construct an XObjectGuard instance from a factory object and an XObject.
	 *
	 * @param theFactory object that manages lifetime of XObjects
	 * @param theXObject pointer to XObject managed
	 */
	XObjectGuard(
			XObjectFactory&		theFactory,
			XObject*			theXObject) :
		m_factory(&theFactory),
		m_object(theXObject)
	{
	}

	// Note that copy construction transfers ownership, just
	// as std::auto_ptr.
	XObjectGuard(XObjectGuard&	theRHS)
	{
		// Release the current object...
		release();

		// Copy the factory and object pointers...
		m_factory = theRHS.m_factory;
		m_object = theRHS.m_object;

		// The source object no longer points to
		// the object...
		theRHS.m_factory = 0;
		theRHS.m_object = 0;
	}

	~XObjectGuard()
	{
		reset();
	}

	/**
	 * Retrieve the object pointer (must not be null)
	 *
	 * @return pointer to XObject
	 */
	XObject*
	operator->() const
	{
		assert(m_object != 0);

		return m_object;
	}

	/**
	 * Retrieve the object pointer (may be null)
	 *
	 * @return pointer to XObject
	 */
	XObject*
	get() const
	{
		return m_object;
	}

	/**
	 * Return the referenced object to the factory and set pointers to null.
	 */
	void
	reset()
	{
		if (m_object != 0)
		{
			assert(m_factory != 0);

			m_factory->returnObject(m_object);

			m_object = 0;
		}

		m_factory = 0;
	}

	/**
	 * Transfers ownership of XObject to caller
	 *
	 * @return pointer to XObject
	 */
	XObject*
	release()
	{
		XObject* const	theTemp = m_object;

		m_object = 0;

		return theTemp;
	}

private:

	XObjectGuard&
	operator=(const XObjectGuard&);

	bool
	operator==(const XObjectGuard&) const;

	// Data members...
	XObjectFactory*		m_factory;
    XObject*			m_object;
};

#endif	// XOBJECTFACTORY_HEADER_GUARD_1357924680
<commit_msg>Enhancements to XObjectGuard.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XOBJECTFACTORY_HEADER_GUARD_1357924680)
#define XOBJECTFACTORY_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <algorithm>
#include <cassert>
#include <set>

#include <XPath/XObject.hpp>

class XalanNode;
class MutableNodeRefList;
class NodeRefListBase;
class ResultTreeFragBase;
class XObject;

/**
 * This class handles the creation of XObjects and manages their lifetime.
 */
class XALAN_XPATH_EXPORT XObjectFactory
{
public:

	XObjectFactory();

	virtual
	~XObjectFactory();

	/**
	 * Return an XObject to the factory.
	 *
	 * @param theXObject The XObject to be returned
	 * @return true if the object belongs to the factory, false if not.
	 */
	bool
	returnObject(const XObject*		theXObject)
	{
		return doReturnObject(theXObject);
	}

	/**
	 * Reset the instance.  This invalidates all existing instances created
	 * with this XObjectFactory.
	 */
	virtual void
	reset() = 0;

	/**
	 * Clone an XObject instance, and hold in the factory.
	 *
	 * @param theXObject the instance to clone
	 * @return a clone of the instance.
	 */
	virtual XObject*
	clone(const XObject&	theXObject) = 0;

	/**
	 * Create a boolean XObject from a boolean value.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize true to use static objects rather than creating new
	 *                  instances, default true
	 * @return pointer to new object
	 */
	virtual XObject*
	createBoolean(
			bool	theValue,
			bool	fOptimize = true) = 0;

	/**
	 * Create a node set XObject from a node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNodeSet(
			const NodeRefListBase&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create a node set XObject from a mutable node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNodeSet(
			const MutableNodeRefList&	theValue,
			bool						fOptimize = true) = 0;

	/**
	 * Create a node set XObject from a DOM node.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNodeSet(
			XalanNode&	theValue,
			bool		fOptimize = true) = 0;

	/**
	 * Create a null XObject.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize true to use static objects rather than creating new
	 *                  instances, default true
	 * @return pointer to new object
	 */
	virtual XObject*
	createNull(bool	fOptimize = true) = 0;

	/**
	 * Create a numeric XObject from a number.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createNumber(
			double	theValue,
			bool	fOptimize = true) = 0;

	/**
	 * Create a string XObject from a string.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createString(
			const XalanDOMString&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create an "unknown" XObject from a string.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createUnknown(
			const XalanDOMString&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create a result tree fragment XObject from a result tree fragment.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createResultTreeFrag(
			const ResultTreeFragBase&	theValue,
			bool						fOptimize = true) = 0;

	/**
	 * Create a span XObject from a node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createSpan(
			const NodeRefListBase&	theValue,
			bool					fOptimize = true) = 0;

	/**
	 * Create a span XObject from a mutable node list.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createSpan(
			const MutableNodeRefList&	theValue,
			bool						fOptimize = true) = 0;

	/**
	 * Create a span XObject from a DOM node.
	 *
	 * @param theValue  value used to create object
	 * @param fOptimize not used
	 * @return pointer to new object
	 */
	virtual XObject*
	createSpan(
			XalanNode&	theValue,
			bool		fOptimize = true) = 0;

	/**
	 *
	 * A public functor for use with stl algorithms.
	 *
	 */
#if defined(XALAN_NO_NAMESPACES)
	struct DeleteXObjectFunctor : public unary_function<const XObject*, void>
#else
	struct DeleteXObjectFunctor : public std::unary_function<const XObject*, void>
#endif
	{
	public:

		DeleteXObjectFunctor(XObjectFactory&	theFactoryInstance) :
			m_factoryInstance(theFactoryInstance)
		{
		}

		result_type
		operator()(argument_type	theXObject) const
		{
			m_factoryInstance.returnObject(theXObject);
		}

	private:

		XObjectFactory&		m_factoryInstance;
	};

protected:

	/**
	 * Delete a FactoryObject instance.
	 *
	 * @param theXObject the XObject instance to delete.
	 */
	void
	deleteObject(const XObject*		theXObject) const
	{
		delete theXObject;
	}

	/**
	 * Return an XObject to the factory.
	 *
	 * @param theXObject XObject to be returned
	 * @param fInReset true when called during reset().
	 */

	virtual bool
	doReturnObject(
			const XObject*	theXObject,
			bool			fInReset = false) = 0;

	/**
	 *
	 * A functor for use with stl algorithms.
	 *
	 */
#if defined(XALAN_NO_NAMESPACES)
	struct ProtectedDeleteXObjectFunctor : public unary_function<const XObject*, void>
#else
	struct ProtectedDeleteXObjectFunctor : public std::unary_function<const XObject*, void>
#endif
	{
	public:

		ProtectedDeleteXObjectFunctor(
			XObjectFactory&		theFactoryInstance,
			bool				fInReset) :
			m_factoryInstance(theFactoryInstance),
			m_fInReset(fInReset)
		{
		}

		result_type
		operator()(argument_type	theXObject) const
		{
			m_factoryInstance.doReturnObject(theXObject,
											 m_fInReset);
		}

	private:

		XObjectFactory&		m_factoryInstance;

		const bool			m_fInReset;
	};

	friend struct ProtectedDeleteXObjectFunctor;

private:

	// Not implemented...
	XObjectFactory(const XObjectFactory&);

	XObjectFactory&
	operator=(const XObjectFactory&);

	bool
	operator==(const XObjectFactory&) const;
};

/**
 * Manages the lifetime of an XObject instance.
 */
class XObjectGuard
{
public:

	/**
	 * Construct an XObjectGuard instance from a factory object and an XObject.
	 *
	 * @param theFactory object that manages lifetime of XObjects
	 * @param theXObject pointer to XObject managed
	 */
	XObjectGuard(
			XObjectFactory&		theFactory,
			XObject*			theXObject) :
		m_factory(&theFactory),
		m_object(theXObject)
	{
	}

	explicit
	XObjectGuard() :
		m_factory(0),
		m_object(0)
	{
	}

	// Note that copy construction transfers ownership, just
	// as std::auto_ptr.
	XObjectGuard(XObjectGuard&	theRHS)
	{
		// Release the current object...
		release();

		// Copy the factory and object pointers...
		m_factory = theRHS.m_factory;
		m_object = theRHS.m_object;

		// The source object no longer points to
		// the object...
		theRHS.m_factory = 0;
		theRHS.m_object = 0;
	}

	~XObjectGuard()
	{
		reset();
	}

	// Note that assignment transfers ownership, just
	// as std::auto_ptr.
	XObjectGuard&
	operator=(XObjectGuard&		theRHS)
	{
		if (&theRHS != this)
		{
			// Release the current object...
			release();

			// Copy the factory and object pointers...
			m_factory = theRHS.m_factory;
			m_object = theRHS.m_object;

			// The source object no longer points to
			// the object...
			theRHS.m_factory = 0;
			theRHS.m_object = 0;
		}

		return *this;
	}

	/**
	 * Retrieve the object pointer (must not be null)
	 *
	 * @return pointer to XObject
	 */
	XObject*
	operator->() const
	{
		assert(m_object != 0);

		return m_object;
	}

	/**
	 * Retrieve the object pointer (may be null)
	 *
	 * @return pointer to XObject
	 */
	XObject*
	get() const
	{
		return m_object;
	}

	/**
	 * Return the referenced object to the factory and set the pointers to null.
	 */
	void
	reset()
	{
		if (m_object != 0)
		{
			assert(m_factory != 0);

			m_factory->returnObject(m_object);

			m_object = 0;
		}

		m_factory = 0;
	}

	/**
	 * Return the referenced object to the factory, if there is one,
	 * and set the pointers to the new object and factory.
	 */
	void
	reset(
			XObjectFactory&		theFactory,
			XObject*			theXObject)
	{
		if (m_object != 0)
		{
			assert(m_factory != 0);

			m_factory->returnObject(m_object);
		}

		m_object = theXObject;
		m_factory = &theFactory;
	}

	/**
	 * Transfers ownership of XObject to caller
	 *
	 * @return pointer to XObject
	 */
	XObject*
	release()
	{
		XObject* const	theTemp = m_object;

		m_object = 0;

		return theTemp;
	}

private:

	bool
	operator==(const XObjectGuard&) const;

	// Data members...
	XObjectFactory*		m_factory;
    XObject*			m_object;
};

#endif	// XOBJECTFACTORY_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck -strict-whitespace %s

void testArrayInitExpr()
{
    int a[10];
    auto l = [a]{
    };
    // CHECK: |-ArrayInitLoopExpr 0x{{[^ ]*}} <col:15> 'int [10]'
    // CHECK: | `-ArrayInitIndexExpr 0x{{[^ ]*}} <<invalid sloc>> 'unsigned long'
}
<commit_msg>Fix whitespace<commit_after>// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck -strict-whitespace %s

void testArrayInitExpr()
{
    int a[10];
    auto l = [a]{
    };
    // CHECK: |-ArrayInitLoopExpr 0x{{[^ ]*}} <col:15> 'int [10]'
    // CHECK: |     `-ArrayInitIndexExpr 0x{{[^ ]*}} <<invalid sloc>> 'unsigned long'
}
<|endoftext|>


<commit_before>// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y %s -o -
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y %s -fdefine-sized-deallocation -o -
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -fsized-deallocation %s -o -
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -fsized-deallocation -fdefine-sized-deallocation %s -o -
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 %s -o -

// CHECK-UNSIZED-NOT: _ZdlPvm
// CHECK-UNSIZED-NOT: _ZdaPvm

void operator delete(void*, unsigned long) throw() __attribute__((alias("foo")));
extern "C" void foo(void*, unsigned long) {}

// CHECK-DAG: @_ZdlPvm = alias void (i8*, i64)* @my_delete
<commit_msg>Fix a test case.<commit_after>// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y -o - %s 2>&1 | FileCheck %s
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y -fdefine-sized-deallocation -o - %s 2>&1 | FileCheck %s
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -fsized-deallocation -o - %s 2>&1 | FileCheck %s
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -fsized-deallocation -fdefine-sized-deallocation -o - %s 2>&1 | FileCheck %s
// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -o - %s 2>&1 | FileCheck %s

// CHECK-UNSIZED-NOT: _ZdlPvm
// CHECK-UNSIZED-NOT: _ZdaPvm

void operator delete(void*, unsigned long) throw() __attribute__((alias("foo")));
extern "C" void foo(void*, unsigned long) {}

// CHECK-DAG: @_ZdlPvm = alias void (i8*, i64)* @foo
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -triple x86_64-pc-linux -std=c++11 -ast-dump -ast-dump-filter Test %s | FileCheck --strict-whitespace %s

int TestLocation
__attribute__((unused));
// CHECK:      VarDecl{{.*}}TestLocation
// CHECK-NEXT:   UnusedAttr 0x{{[^ ]*}} <line:[[@LINE-2]]:16>

int TestIndent
__attribute__((unused));
// CHECK:      {{^}}VarDecl{{.*TestIndent[^()]*$}}
// CHECK-NEXT: {{^}}`-UnusedAttr{{[^()]*$}}

void TestAttributedStmt() {
  switch (1) {
  case 1:
    [[clang::fallthrough]];
  case 2:
    ;
  }
}
// CHECK:      FunctionDecl{{.*}}TestAttributedStmt
// CHECK:      AttributedStmt
// CHECK-NEXT:   FallThroughAttr
// CHECK-NEXT:   NullStmt

[[clang::warn_unused_result]] int TestCXX11DeclAttr();
// CHECK:      FunctionDecl{{.*}}TestCXX11DeclAttr
// CHECK-NEXT:   WarnUnusedResultAttr

int TestAlignedNull __attribute__((aligned));
// CHECK:      VarDecl{{.*}}TestAlignedNull
// CHECK-NEXT:   AlignedAttr {{.*}} aligned
// CHECK-NEXT:     <<<NULL>>>

int TestAlignedExpr __attribute__((aligned(4)));
// CHECK:      VarDecl{{.*}}TestAlignedExpr
// CHECK-NEXT:   AlignedAttr {{.*}} aligned
// CHECK-NEXT:     IntegerLiteral

int TestEnum __attribute__((visibility("default")));
// CHECK:      VarDecl{{.*}}TestEnum
// CHECK-NEXT:   VisibilityAttr{{.*}} Default

class __attribute__((lockable)) Mutex {
} mu1, mu2;
int TestExpr __attribute__((guarded_by(mu1)));
// CHECK:      VarDecl{{.*}}TestExpr
// CHECK-NEXT:   GuardedByAttr
// CHECK-NEXT:     DeclRefExpr{{.*}}mu1

class Mutex TestVariadicExpr __attribute__((acquired_after(mu1, mu2)));
// CHECK:      VarDecl{{.*}}TestVariadicExpr
// CHECK:        AcquiredAfterAttr
// CHECK-NEXT:     DeclRefExpr{{.*}}mu1
// CHECK-NEXT:     DeclRefExpr{{.*}}mu2

void function1(void *) {
  int TestFunction __attribute__((cleanup(function1)));
}
// CHECK:      VarDecl{{.*}}TestFunction
// CHECK-NEXT:   CleanupAttr{{.*}} Function{{.*}}function1

void TestIdentifier(void *, int)
__attribute__((pointer_with_type_tag(ident1,1,2)));
// CHECK: FunctionDecl{{.*}}TestIdentifier
// CHECK:   ArgumentWithTypeTagAttr{{.*}} pointer_with_type_tag ident1

void TestBool(void *, int)
__attribute__((pointer_with_type_tag(bool1,1,2)));
// CHECK: FunctionDecl{{.*}}TestBool
// CHECK:   ArgumentWithTypeTagAttr{{.*}}pointer_with_type_tag bool1 0 1 IsPointer

void TestUnsigned(void *, int)
__attribute__((pointer_with_type_tag(unsigned1,1,2)));
// CHECK: FunctionDecl{{.*}}TestUnsigned
// CHECK:   ArgumentWithTypeTagAttr{{.*}} pointer_with_type_tag unsigned1 0 1

void TestInt(void) __attribute__((constructor(123)));
// CHECK:      FunctionDecl{{.*}}TestInt
// CHECK-NEXT:   ConstructorAttr{{.*}} 123

int TestString __attribute__((alias("alias1")));
// CHECK:      VarDecl{{.*}}TestString
// CHECK-NEXT:   AliasAttr{{.*}} "alias1"

extern struct s1 TestType
__attribute__((type_tag_for_datatype(ident1,int)));
// CHECK:      VarDecl{{.*}}TestType
// CHECK-NEXT:   TypeTagForDatatypeAttr{{.*}} int

void TestLabel() {
L: __attribute__((unused)) int i;
// CHECK: LabelStmt{{.*}}'L'
// CHECK: VarDecl{{.*}}i 'int'
// CHECK-NEXT: UnusedAttr{{.*}}

M: __attribute(()) int j;
// CHECK: LabelStmt {{.*}} 'M'
// CHECK-NEXT: DeclStmt
// CHECK-NEXT: VarDecl {{.*}} j 'int'

N: __attribute(()) ;
// CHECK: LabelStmt {{.*}} 'N'
// CHECK-NEXT: NullStmt
}

namespace Test {
extern "C" int printf(const char *format, ...);
// CHECK: FunctionDecl{{.*}}printf
// CHECK-NEXT: ParmVarDecl{{.*}}format{{.*}}'const char *'
// CHECK-NEXT: FormatAttr{{.*}}printf 1 2 Implicit
}<commit_msg>Adding a test case to ensure that type attributes applied to the decl-specifier are applied across all declarations in a group.<commit_after>// RUN: %clang_cc1 -triple x86_64-pc-linux -std=c++11 -ast-dump -ast-dump-filter Test %s | FileCheck --strict-whitespace %s

int TestLocation
__attribute__((unused));
// CHECK:      VarDecl{{.*}}TestLocation
// CHECK-NEXT:   UnusedAttr 0x{{[^ ]*}} <line:[[@LINE-2]]:16>

int TestIndent
__attribute__((unused));
// CHECK:      {{^}}VarDecl{{.*TestIndent[^()]*$}}
// CHECK-NEXT: {{^}}`-UnusedAttr{{[^()]*$}}

void TestAttributedStmt() {
  switch (1) {
  case 1:
    [[clang::fallthrough]];
  case 2:
    ;
  }
}
// CHECK:      FunctionDecl{{.*}}TestAttributedStmt
// CHECK:      AttributedStmt
// CHECK-NEXT:   FallThroughAttr
// CHECK-NEXT:   NullStmt

[[clang::warn_unused_result]] int TestCXX11DeclAttr();
// CHECK:      FunctionDecl{{.*}}TestCXX11DeclAttr
// CHECK-NEXT:   WarnUnusedResultAttr

int TestAlignedNull __attribute__((aligned));
// CHECK:      VarDecl{{.*}}TestAlignedNull
// CHECK-NEXT:   AlignedAttr {{.*}} aligned
// CHECK-NEXT:     <<<NULL>>>

int TestAlignedExpr __attribute__((aligned(4)));
// CHECK:      VarDecl{{.*}}TestAlignedExpr
// CHECK-NEXT:   AlignedAttr {{.*}} aligned
// CHECK-NEXT:     IntegerLiteral

int TestEnum __attribute__((visibility("default")));
// CHECK:      VarDecl{{.*}}TestEnum
// CHECK-NEXT:   VisibilityAttr{{.*}} Default

class __attribute__((lockable)) Mutex {
} mu1, mu2;
int TestExpr __attribute__((guarded_by(mu1)));
// CHECK:      VarDecl{{.*}}TestExpr
// CHECK-NEXT:   GuardedByAttr
// CHECK-NEXT:     DeclRefExpr{{.*}}mu1

class Mutex TestVariadicExpr __attribute__((acquired_after(mu1, mu2)));
// CHECK:      VarDecl{{.*}}TestVariadicExpr
// CHECK:        AcquiredAfterAttr
// CHECK-NEXT:     DeclRefExpr{{.*}}mu1
// CHECK-NEXT:     DeclRefExpr{{.*}}mu2

void function1(void *) {
  int TestFunction __attribute__((cleanup(function1)));
}
// CHECK:      VarDecl{{.*}}TestFunction
// CHECK-NEXT:   CleanupAttr{{.*}} Function{{.*}}function1

void TestIdentifier(void *, int)
__attribute__((pointer_with_type_tag(ident1,1,2)));
// CHECK: FunctionDecl{{.*}}TestIdentifier
// CHECK:   ArgumentWithTypeTagAttr{{.*}} pointer_with_type_tag ident1

void TestBool(void *, int)
__attribute__((pointer_with_type_tag(bool1,1,2)));
// CHECK: FunctionDecl{{.*}}TestBool
// CHECK:   ArgumentWithTypeTagAttr{{.*}}pointer_with_type_tag bool1 0 1 IsPointer

void TestUnsigned(void *, int)
__attribute__((pointer_with_type_tag(unsigned1,1,2)));
// CHECK: FunctionDecl{{.*}}TestUnsigned
// CHECK:   ArgumentWithTypeTagAttr{{.*}} pointer_with_type_tag unsigned1 0 1

void TestInt(void) __attribute__((constructor(123)));
// CHECK:      FunctionDecl{{.*}}TestInt
// CHECK-NEXT:   ConstructorAttr{{.*}} 123

int TestString __attribute__((alias("alias1")));
// CHECK:      VarDecl{{.*}}TestString
// CHECK-NEXT:   AliasAttr{{.*}} "alias1"

extern struct s1 TestType
__attribute__((type_tag_for_datatype(ident1,int)));
// CHECK:      VarDecl{{.*}}TestType
// CHECK-NEXT:   TypeTagForDatatypeAttr{{.*}} int

void TestLabel() {
L: __attribute__((unused)) int i;
// CHECK: LabelStmt{{.*}}'L'
// CHECK: VarDecl{{.*}}i 'int'
// CHECK-NEXT: UnusedAttr{{.*}}

M: __attribute(()) int j;
// CHECK: LabelStmt {{.*}} 'M'
// CHECK-NEXT: DeclStmt
// CHECK-NEXT: VarDecl {{.*}} j 'int'

N: __attribute(()) ;
// CHECK: LabelStmt {{.*}} 'N'
// CHECK-NEXT: NullStmt
}

namespace Test {
extern "C" int printf(const char *format, ...);
// CHECK: FunctionDecl{{.*}}printf
// CHECK-NEXT: ParmVarDecl{{.*}}format{{.*}}'const char *'
// CHECK-NEXT: FormatAttr{{.*}}printf 1 2 Implicit
}

int __attribute__((cdecl)) TestOne(void), TestTwo(void);
// CHECK: FunctionDecl{{.*}}TestOne{{.*}}__attribute__((cdecl))
// CHECK: FunctionDecl{{.*}}TestTwo{{.*}}__attribute__((cdecl))
<|endoftext|>


<commit_before>#include <iostream>
#include "benchmark/benchmark.h"
#include "simple_graph/list_graph.hpp"
#include "simple_graph/algorithm/bellman_ford.hpp"

using simple_graph::vertex_index_t;

static void bench_bellman_ford(benchmark::State &state)
{
    simple_graph::ListGraph<true, int, ssize_t> g;
    for (int i = 0; i < state.range_x(); ++i) {
        g.add_vertex(simple_graph::Vertex<int>(i, i));
    }
    for (int i = 0; i < state.range_x() - 1; ++i) {
        g.add_edge(simple_graph::Edge<ssize_t>(i, i + 1, 1));
    }

    while (state.KeepRunning()) {
        std::vector<vertex_index_t> path;
        benchmark::DoNotOptimize(simple_graph::bellman_ford(g, 0, state.range_x() - 1, &path));
    }
}
BENCHMARK(bench_bellman_ford)->Range(1<<10, 1<<16);

static void bench_bellman_ford_reversed(benchmark::State &state)
{
    simple_graph::ListGraph<true, int, ssize_t> g;
    for (int i = 0; i < state.range_x(); ++i) {
        g.add_vertex(simple_graph::Vertex<int>(i, i));
    }
    for (int i = 0; i < state.range_x() - 1; ++i) {
        g.add_edge(simple_graph::Edge<ssize_t>(i + 1, i, 1));
    }

    while (state.KeepRunning()) {
        std::vector<vertex_index_t> path;
        benchmark::DoNotOptimize(simple_graph::bellman_ford(g, state.range_x() - 1, 0, &path));
    }
}
BENCHMARK(bench_bellman_ford_reversed)->Range(1<<10, 1<<16);

BENCHMARK_MAIN()
<commit_msg>Add benchmark test for Bellman-Ford<commit_after>#include <algorithm>
#include <iostream>
#include "benchmark/benchmark.h"
#include "simple_graph/list_graph.hpp"
#include "simple_graph/algorithm/bellman_ford.hpp"

using simple_graph::vertex_index_t;

static void bench_bellman_ford(benchmark::State &state)
{
    simple_graph::ListGraph<true, int, ssize_t> g;
    for (int i = 0; i < state.range_x(); ++i) {
        g.add_vertex(simple_graph::Vertex<int>(i, i));
    }
    for (int i = 0; i < state.range_x() - 1; ++i) {
        g.add_edge(simple_graph::Edge<ssize_t>(i, i + 1, 1));
    }

    while (state.KeepRunning()) {
        std::vector<vertex_index_t> path;
        benchmark::DoNotOptimize(simple_graph::bellman_ford(g, 0, state.range_x() - 1, &path));
    }
}
BENCHMARK(bench_bellman_ford)->Range(1<<10, 1<<16);

static void bench_bellman_ford_reversed(benchmark::State &state)
{
    simple_graph::ListGraph<true, int, ssize_t> g;
    for (int i = 0; i < state.range_x(); ++i) {
        g.add_vertex(simple_graph::Vertex<int>(i, i));
    }
    for (int i = 0; i < state.range_x() - 1; ++i) {
        g.add_edge(simple_graph::Edge<ssize_t>(i + 1, i, 1));
    }

    while (state.KeepRunning()) {
        std::vector<vertex_index_t> path;
        benchmark::DoNotOptimize(simple_graph::bellman_ford(g, state.range_x() - 1, 0, &path));
    }
}
BENCHMARK(bench_bellman_ford_reversed)->Range(1<<10, 1<<16);

static void bench_bellman_ford_random(benchmark::State &state)
{
    std::vector<vertex_index_t> vertices;
    simple_graph::ListGraph<true, int, ssize_t> g;
    for (int i = 0; i < state.range_x(); ++i) {
        g.add_vertex(simple_graph::Vertex<int>(i, i));
        vertices.push_back(i);
    }
    std::random_shuffle(vertices.begin(), vertices.end());
    for (int i = 0; i < state.range_x() - 1; ++i) {
        g.add_edge(simple_graph::Edge<ssize_t>(vertices[i], vertices[i + 1], 1));
    }

    while (state.KeepRunning()) {
        std::vector<vertex_index_t> path;
        benchmark::DoNotOptimize(simple_graph::bellman_ford(g, vertices[0], vertices[state.range_x() - 1], &path));
    }
}
BENCHMARK(bench_bellman_ford_random)->Range(1<<10, 1<<13);

BENCHMARK_MAIN()
<|endoftext|>


<commit_before>#include <stdio.h>
#include "Halide.h"
#include <iostream>

using namespace Halide;

int main(int argc, char **argv) {

    Var x("x"), y("y");
    Func f("f"), g("g"), h("h");

    printf("Defining function...\n");

    f(x, y) = max(x, y);
    g(x, y) = min(x, y);
    h(x, y) = clamp(x+y, 20, 100);

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        // Resolve why OpenCL used 32,1 tiling
        f.gpu_tile(x, y, 8, 8);
        g.gpu_tile(x, y, 8, 8);
        h.gpu_tile(x, y, 8, 8);
    }

    printf("Realizing function...\n");

    Image<int> imf = f.realize(32, 32, target);
    Image<int> img = g.realize(32, 32, target);
    Image<int> imh = h.realize(32, 32, target);

    // Check the result was what we expected
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (imf(i, j) != (i > j ? i : j)) {
                printf("imf[%d, %d] = %d\n", i, j, imf(i, j));
                return -1;
            }
            if (img(i, j) != (i < j ? i : j)) {
                printf("img[%d, %d] = %d\n", i, j, img(i, j));
                return -1;
            }
            int href = i+j;
            if (href < 20) href = 20;
            if (href > 100) href = 100;
            if (imh(i, j) != href) {
                printf("imh[%d, %d] = %d (not %d)\n", i, j, imh(i, j), href);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Added hexagon schedule.<commit_after>#include <stdio.h>
#include "Halide.h"
#include <iostream>

using namespace Halide;

int main(int argc, char **argv) {

    Var x("x"), y("y");
    Func f("f"), g("g"), h("h");

    printf("Defining function...\n");

    f(x, y) = max(x, y);
    g(x, y) = min(x, y);
    h(x, y) = clamp(x+y, 20, 100);

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        // Resolve why OpenCL used 32,1 tiling
        f.gpu_tile(x, y, 8, 8);
        g.gpu_tile(x, y, 8, 8);
        h.gpu_tile(x, y, 8, 8);
    } else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
        f.hexagon().vectorize(x, 32);
        g.hexagon().vectorize(x, 32);
        h.hexagon().vectorize(x, 32);
    }

    printf("Realizing function...\n");

    Image<int> imf = f.realize(32, 32, target);
    Image<int> img = g.realize(32, 32, target);
    Image<int> imh = h.realize(32, 32, target);

    // Check the result was what we expected
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (imf(i, j) != (i > j ? i : j)) {
                printf("imf[%d, %d] = %d\n", i, j, imf(i, j));
                return -1;
            }
            if (img(i, j) != (i < j ? i : j)) {
                printf("img[%d, %d] = %d\n", i, j, img(i, j));
                return -1;
            }
            int href = i+j;
            if (href < 20) href = 20;
            if (href > 100) href = 100;
            if (imh(i, j) != href) {
                printf("imh[%d, %d] = %d (not %d)\n", i, j, imh(i, j), href);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>