<commit_before>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include "sys_net_native.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Net_NetworkInformation_Wireless80211Configuration::GetWireless82011ConfigurationCount___STATIC__I4,
    Library_sys_net_native_System_Net_NetworkInformation_Wireless80211Configuration::GetWireless82011Configuration___STATIC__SystemNetNetworkInformationWireless80211Configuration__I4,
    Library_sys_net_native_System_Net_NetworkInformation_Wireless80211Configuration::UpdateConfiguration___STATIC__VOID,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::InitializeNetworkInterfaceSettings___VOID,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::UpdateConfiguration___VOID__I4,
    NULL,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::GetNetworkInterfaceCount___STATIC__I4,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::GetNetworkInterface___STATIC__SystemNetNetworkInformationNetworkInterface__U4,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::IPAddressFromString___STATIC__U4__STRING,
    Library_sys_net_native_System_Net_Security_SslNative::SecureServerInit___STATIC__I4__I4__I4__SystemSecurityCryptographyX509CertificatesX509Certificate__SZARRAY_SystemSecurityCryptographyX509CertificatesX509Certificate,
    Library_sys_net_native_System_Net_Security_SslNative::SecureClientInit___STATIC__I4__I4__I4__SystemSecurityCryptographyX509CertificatesX509Certificate__SZARRAY_SystemSecurityCryptographyX509CertificatesX509Certificate,
    Library_sys_net_native_System_Net_Security_SslNative::UpdateCertificates___STATIC__VOID__I4__SystemSecurityCryptographyX509CertificatesX509Certificate__SZARRAY_SystemSecurityCryptographyX509CertificatesX509Certificate,
    Library_sys_net_native_System_Net_Security_SslNative::SecureAccept___STATIC__VOID__I4__OBJECT,
    Library_sys_net_native_System_Net_Security_SslNative::SecureConnect___STATIC__VOID__I4__STRING__OBJECT,
    Library_sys_net_native_System_Net_Security_SslNative::SecureRead___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4,
    Library_sys_net_native_System_Net_Security_SslNative::SecureWrite___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4,
    Library_sys_net_native_System_Net_Security_SslNative::SecureCloseSocket___STATIC__I4__OBJECT,
    Library_sys_net_native_System_Net_Security_SslNative::ExitSecureContext___STATIC__I4__I4,
    Library_sys_net_native_System_Net_Security_SslNative::DataAvailable___STATIC__I4__OBJECT,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::socket___STATIC__I4__I4__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::bind___STATIC__VOID__OBJECT__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::connect___STATIC__VOID__OBJECT__SZARRAY_U1__BOOLEAN,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::send___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::recv___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::close___STATIC__I4__OBJECT,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::listen___STATIC__VOID__OBJECT__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::accept___STATIC__I4__OBJECT,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getaddrinfo___STATIC__VOID__STRING__BYREF_STRING__BYREF_SZARRAY_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::shutdown___STATIC__VOID__OBJECT__I4__BYREF_I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::sendto___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::recvfrom___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4__BYREF_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getpeername___STATIC__VOID__OBJECT__BYREF_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getsockname___STATIC__VOID__OBJECT__BYREF_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getsockopt___STATIC__VOID__OBJECT__I4__I4__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::setsockopt___STATIC__VOID__OBJECT__I4__I4__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::poll___STATIC__BOOLEAN__OBJECT__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::ioctl___STATIC__VOID__OBJECT__U4__BYREF_U4,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Security_Cryptography_X509Certificates_X509Certificate::ParseCertificate___STATIC__VOID__SZARRAY_U1__STRING__BYREF_STRING__BYREF_STRING__BYREF_mscorlibSystemDateTime__BYREF_mscorlibSystemDateTime,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Net =
{
    "System.Net",
    0xC58744CD,
    method_lookup,
    { 1, 0, 2, 13 }
};
<commit_msg>Update nanoFramework.System.Net version to 1.0.2-preview-021 ***NO_CI***<commit_after>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include "sys_net_native.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Net_NetworkInformation_Wireless80211Configuration::GetWireless82011ConfigurationCount___STATIC__I4,
    Library_sys_net_native_System_Net_NetworkInformation_Wireless80211Configuration::GetWireless82011Configuration___STATIC__SystemNetNetworkInformationWireless80211Configuration__I4,
    Library_sys_net_native_System_Net_NetworkInformation_Wireless80211Configuration::UpdateConfiguration___STATIC__VOID,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::InitializeNetworkInterfaceSettings___VOID,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::UpdateConfiguration___VOID__I4,
    NULL,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::GetNetworkInterfaceCount___STATIC__I4,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::GetNetworkInterface___STATIC__SystemNetNetworkInformationNetworkInterface__U4,
    Library_sys_net_native_System_Net_NetworkInformation_NetworkInterface::IPAddressFromString___STATIC__U4__STRING,
    Library_sys_net_native_System_Net_Security_SslNative::SecureServerInit___STATIC__I4__I4__I4__SystemSecurityCryptographyX509CertificatesX509Certificate__SZARRAY_SystemSecurityCryptographyX509CertificatesX509Certificate,
    Library_sys_net_native_System_Net_Security_SslNative::SecureClientInit___STATIC__I4__I4__I4__SystemSecurityCryptographyX509CertificatesX509Certificate__SZARRAY_SystemSecurityCryptographyX509CertificatesX509Certificate,
    Library_sys_net_native_System_Net_Security_SslNative::UpdateCertificates___STATIC__VOID__I4__SystemSecurityCryptographyX509CertificatesX509Certificate__SZARRAY_SystemSecurityCryptographyX509CertificatesX509Certificate,
    Library_sys_net_native_System_Net_Security_SslNative::SecureAccept___STATIC__VOID__I4__OBJECT,
    Library_sys_net_native_System_Net_Security_SslNative::SecureConnect___STATIC__VOID__I4__STRING__OBJECT,
    Library_sys_net_native_System_Net_Security_SslNative::SecureRead___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4,
    Library_sys_net_native_System_Net_Security_SslNative::SecureWrite___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4,
    Library_sys_net_native_System_Net_Security_SslNative::SecureCloseSocket___STATIC__I4__OBJECT,
    Library_sys_net_native_System_Net_Security_SslNative::ExitSecureContext___STATIC__I4__I4,
    Library_sys_net_native_System_Net_Security_SslNative::DataAvailable___STATIC__I4__OBJECT,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::socket___STATIC__I4__I4__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::bind___STATIC__VOID__OBJECT__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::connect___STATIC__VOID__OBJECT__SZARRAY_U1__BOOLEAN,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::send___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::recv___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::close___STATIC__I4__OBJECT,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::listen___STATIC__VOID__OBJECT__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::accept___STATIC__I4__OBJECT,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getaddrinfo___STATIC__VOID__STRING__BYREF_STRING__BYREF_SZARRAY_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::shutdown___STATIC__VOID__OBJECT__I4__BYREF_I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::sendto___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::recvfrom___STATIC__I4__OBJECT__SZARRAY_U1__I4__I4__I4__I4__BYREF_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getpeername___STATIC__VOID__OBJECT__BYREF_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getsockname___STATIC__VOID__OBJECT__BYREF_SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::getsockopt___STATIC__VOID__OBJECT__I4__I4__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::setsockopt___STATIC__VOID__OBJECT__I4__I4__SZARRAY_U1,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::poll___STATIC__BOOLEAN__OBJECT__I4__I4,
    Library_sys_net_native_System_Net_Sockets_NativeSocket::ioctl___STATIC__VOID__OBJECT__U4__BYREF_U4,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_net_native_System_Security_Cryptography_X509Certificates_X509Certificate::ParseCertificate___STATIC__VOID__SZARRAY_U1__STRING__BYREF_STRING__BYREF_STRING__BYREF_mscorlibSystemDateTime__BYREF_mscorlibSystemDateTime,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Net =
{
    "System.Net",
    0xC58744CD,
    method_lookup,
    { 1, 0, 2, 21 }
};
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 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/>.
 */

#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"

#include <Include/XalanAutoPtr.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <unicode/coll.h>

const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor		ICUBridgeCollationCompareFunctor::s_defaultFunctor;

ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
	m_isValid(false),
	m_collator(0)
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	m_collator = Collator::createInstance(theStatus);

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		m_isValid = true;
	}
}

ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
	delete m_collator;
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	XalanAutoPtr<Collator>	theCollator(Collator::createInstance(theStatus));

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		assert(theCollator.get() != 0);

#if U_SIZEOF_WCHAR_T==2
		return theCollator->compare(
					(wchar_t*)theLHS,
					length(theLHS),
					(wchar_t*)theRHS,
					length(theRHS));
#else
		return theCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
	else
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale) const
{
	UErrorCode	theStatus = U_ZERO_ERROR;

#if U_SIZEOF_WCHAR_T==2
	XalanAutoPtr<Collator>	theCollator(Collator::createInstance(Locale(UnicodeString(const theLocale)), theStatus));
#else
	XalanAutoPtr<Collator>	theCollator(Collator::createInstance(Locale(UnicodeString(theLocale)), theStatus));
#endif

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		assert(theCollator.get() != 0);

#if U_SIZEOF_WCHAR_T==2
		return theCollator->compare(
					(const wchar_t*)theLHS,
					length(theLHS),
					(const wchar_t*)theRHS,
					length(theRHS));
#else
		return theCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
	else
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS)
{
	if (isValid() == false)
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
	else
	{
		assert(m_collator != 0);
#if U_SIZEOF_WCHAR_T==2
		return m_collator->compare(
					(wchar_t*)theLHS,
					length(theLHS),
					(wchar_t*)theRHS,
					length(theRHS));
#else
		return m_collator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
}
<commit_msg>Fixed typo.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 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/>.
 */

#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"

#include <Include/XalanAutoPtr.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <unicode/coll.h>

const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor		ICUBridgeCollationCompareFunctor::s_defaultFunctor;

ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
	m_isValid(false),
	m_collator(0)
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	m_collator = Collator::createInstance(theStatus);

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		m_isValid = true;
	}
}

ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
	delete m_collator;
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	XalanAutoPtr<Collator>	theCollator(Collator::createInstance(theStatus));

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		assert(theCollator.get() != 0);

#if U_SIZEOF_WCHAR_T==2
		return theCollator->compare(
					(wchar_t*)theLHS,
					length(theLHS),
					(wchar_t*)theRHS,
					length(theRHS));
#else
		return theCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
	else
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale) const
{
	UErrorCode	theStatus = U_ZERO_ERROR;

#if U_SIZEOF_WCHAR_T==2
	XalanAutoPtr<Collator>	theCollator(Collator::createInstance(Locale(UnicodeString((const wchar_t*)theLocale)), theStatus));
#else
	XalanAutoPtr<Collator>	theCollator(Collator::createInstance(Locale(UnicodeString(theLocale)), theStatus));
#endif

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		assert(theCollator.get() != 0);

#if U_SIZEOF_WCHAR_T==2
		return theCollator->compare(
					(const wchar_t*)theLHS,
					length(theLHS),
					(const wchar_t*)theRHS,
					length(theRHS));
#else
		return theCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
	else
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS)
{
	if (isValid() == false)
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
	else
	{
		assert(m_collator != 0);
#if U_SIZEOF_WCHAR_T==2
		return m_collator->compare(
					const (wchar_t*)theLHS,
					length(theLHS),
					const (wchar_t*)theRHS,
					length(theRHS));
#else
		return m_collator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
}
<|endoftext|>


<commit_before>#include "LogicController.h"

LogicController::LogicController() {

  logicState = LOGIC_STATE_INTERRUPT;
  processState = PROCCESS_STATE_SEARCHING;

  ProcessData();

  control_queue = priority_queue<PrioritizedController>();

}

LogicController::~LogicController() {}

void LogicController::Reset() {

  std::cout << "LogicController.Reset()" << std::endl;
  logicState = LOGIC_STATE_INTERRUPT;
  processState = PROCCESS_STATE_SEARCHING;

  ProcessData();

  control_queue = priority_queue<PrioritizedController>();
}

//***********************************************************************************************************************
//This function is called every 1/10th second by the ROSAdapter
//The logical flow if the behaviours is controlled here by using a interrupt, haswork, priority queue system.
Result LogicController::DoWork() {
  Result result;

  //first a loop runs through all the controllers who have a priority of 0 or above witht he largest number being
  //most important. A priority of less than 0 is an ignored controller use -1 for standards sake.
  //if any controller needs and interrupt the logic state is changed to interrupt
  for(PrioritizedController cntrlr : prioritizedControllers) {
    if(cntrlr.controller->ShouldInterrupt() && cntrlr.priority >= 0)
      {
	logicState = LOGIC_STATE_INTERRUPT;
	//do not break all shouldInterupts may need calling in order to properly pre-proccess data.
      }
  }

  //logic state switch
  switch(logicState) {

  //when an interrupt has been thorwn or there are no pending control_queue.top().actions logic controller is in this state.
  case LOGIC_STATE_INTERRUPT: {
    //Reset the control queue
    control_queue = priority_queue<PrioritizedController>();

    //check what controllers have work to do all that say yes will be added to the priority queue.
    for(PrioritizedController cntrlr : prioritizedControllers) {
      if(cntrlr.controller->HasWork()) {
        if (cntrlr.priority < 0) {
          continue;
        }
        else {
          control_queue.push(cntrlr);
        }
      }
    }

    //if no controlers have work report this to ROS Adapter and do nothing.
    if(control_queue.empty()) {
      result.type = behavior;
      result.b = wait;
      break;
    }
    else {
      //default result state if someone has work this safe gaurds against faulty result types
      result.b = noChange;
    }

    //take the top member of the priority queue and run their do work function.
    result = control_queue.top().controller->DoWork();

    //anaylyze the result that was returned and do state changes accordingly
    //behavior types are used to indicate behavior changes of some form
    if(result.type == behavior) {

      //ask for an external reset so the state of the controller is preserved untill after it has returned a result and
      //gotten a chance to communicate with other controllers
      if (result.reset) {
        controllerInterconnect(); //allow controller to communicate state data before it is reset
        control_queue.top().controller->Reset();
      }

      //ask for the procces state to change to the next state or loop around to the begining
      if(result.b == nextProcess) {
        if (processState == _LAST - 1) {
          processState = _FIRST;
        }
        else {
          processState = (ProcessState)((int)processState + 1);
        }
      }
      //ask for the procces state to change to the previouse state or loop around to the end
      else if(result.b == prevProcess) {
        if (processState == _FIRST) {
          processState = (ProcessState)((int)_LAST - 1);
        }
        else {
          processState = (ProcessState)((int)processState - 1);
        }
      }

      //update the priorites of the controllers based upon the new process state.
      if (result.b == nextProcess || result.b == prevProcess) {
        ProcessData();
        result.b = wait;
        driveController.Reset(); //it is assumed that the drive controller may be in a bad state if interrupted so reset it
      }
      break;
    }

    //precision driving result types are when a controller wants direct command of the robots actuators
    //logic controller facilitates the command pass through in the LOGIC_STATE_PRECISION_COMMAND switch case
    else if(result.type == precisionDriving) {

      logicState = LOGIC_STATE_PRECISION_COMMAND;
      break;

    }

    //waypoints are also a pass through facilitated command but with a slightly diffrent overhead
    //they are handled in the LOGIC_STATE_WAITING switch case
    else if(result.type == waypoint) {

      logicState = LOGIC_STATE_WAITING;
      driveController.SetResultData(result);
      //fall through on purpose
    }

  } //end of interupt case***************************************************************************************

    //this case is primarly when logic controller is waiting for drive controller to reach its last waypoint
  case LOGIC_STATE_WAITING: {
    //ask drive controller how to drive
    //commands to be passed the ROS Adapter as left and right wheel PWM values in the result struct are returned
    result = driveController.DoWork();

    //when out of waypoints drive controller will through an interrupt however unlike other controllers
    //drive controller is not on the priority queue so it must be checked here
    if (result.type == behavior) {
      if(driveController.ShouldInterrupt()) {
        logicState = LOGIC_STATE_INTERRUPT;
      }
    }
    break;
  }//end of waiting case*****************************************************************************************

    //used for precision driving pass through
  case LOGIC_STATE_PRECISION_COMMAND: {

    //unlike waypoints precision commands change every update tick so we ask the
    //controller for new commands on every update tick.
    result = control_queue.top().controller->DoWork();

    //pass the driving commands to the drive controller so it can interpret them
    driveController.SetResultData(result);

    //the interoreted commands are turned into properinitial_spiral_offset motor commands to be passed the ROS Adapter
    //as left and right wheel PWM values in the result struct.
    result = driveController.DoWork();
    break;

  }//end of precision case****************************************************************************************
  }//end switch statment******************************************************************************************

   // bad! causes node to crash
   // cout << "logic state " << logicState << " top controller " << control_queue.top().priority << " Proccess " << processState <<endl;

  //now using proccess logic allow the controller to communicate data between eachother
  controllerInterconnect();

  //give the ROSAdapter the final decision on how it should drive
  return result;
}

void LogicController::UpdateData() {

}

void LogicController::ProcessData() {

  //this controller priority is used when searching
  if (processState == PROCCESS_STATE_SEARCHING) {
    prioritizedControllers = {
      PrioritizedController{0, (Controller*)(&searchController)},
      PrioritizedController{10, (Controller*)(&obstacleController)},
      PrioritizedController{15, (Controller*)(&pickUpController)},
      PrioritizedController{5, (Controller*)(&range_controller)},
      PrioritizedController{-1, (Controller*)(&dropOffController)},
      PrioritizedController{-1, (Controller*)(&manualWaypointController)}
    };
  }

  //this priority is used when returning a target to the center collection zone
  else if (processState  == PROCCESS_STATE_TARGET_PICKEDUP) {
    prioritizedControllers = {
    PrioritizedController{-1, (Controller*)(&searchController)},
    PrioritizedController{15, (Controller*)(&obstacleController)},
    PrioritizedController{-1, (Controller*)(&pickUpController)},
    PrioritizedController{10, (Controller*)(&range_controller)},
    PrioritizedController{1, (Controller*)(&dropOffController)},
    PrioritizedController{-1, (Controller*)(&manualWaypointController)}
    };
  }
  //this priority is used when returning a target to the center collection zone
  else if (processState  == PROCCESS_STATE_DROP_OFF)
  {
    prioritizedControllers = {
      PrioritizedController{-1, (Controller*)(&searchController)},
      PrioritizedController{-1, (Controller*)(&obstacleController)},
      PrioritizedController{-1, (Controller*)(&pickUpController)},
      PrioritizedController{10, (Controller*)(&range_controller)},
      PrioritizedController{1, (Controller*)(&dropOffController)},
      PrioritizedController{-1, (Controller*)(&manualWaypointController)}
    };
  }
  else if (processState == PROCESS_STATE_MANUAL) {
    prioritizedControllers = {
      PrioritizedController{-1, (Controller*)(&searchController)},
      PrioritizedController{10, (Controller*)(&obstacleController)},
      PrioritizedController{-1, (Controller*)(&pickUpController)},
      PrioritizedController{-1, (Controller*)(&range_controller)},
      PrioritizedController{-1, (Controller*)(&dropOffController)},
      PrioritizedController{5,  (Controller*)(&manualWaypointController)}
    };
  }
}

bool LogicController::ShouldInterrupt() {
  ProcessData();

  return false;
}

bool LogicController::HasWork() {
  return false;
}

void LogicController::controllerInterconnect() {

  if (processState == PROCCESS_STATE_SEARCHING) {

    //obstacle needs to know if the center ultrasound should be ignored
    if(pickUpController.GetIgnoreCenter()) {
      obstacleController.SetIgnoreCenter();
    }

    //pickup controller annouces it has pickedup a target
    if(pickUpController.GetTargetHeld()) {
      dropOffController.SetTargetPickedUp();
      obstacleController.SetTargetHeld();
      searchController.SetSuccesfullPickup();
    }
  }

  //ask if drop off has released the target from the claws yet
  if (!dropOffController.HasTarget()) {
    obstacleController.SetTargetHeldClear();
  }

  //obstacle controller is running driveController needs to clear its waypoints
  if(obstacleController.GetShouldClearWaypoints()) {
    driveController.Reset();
  }

}

// Recieves position in the world inertial frame (should rename to SetOdomPositionData)
void LogicController::SetPositionData(Point currentLocation) {
  searchController.SetCurrentLocation(currentLocation);
  dropOffController.SetCurrentLocation(currentLocation);
  obstacleController.SetCurrentLocation(currentLocation);
  driveController.SetCurrentLocation(currentLocation);
  manualWaypointController.SetCurrentLocation(currentLocation);
}

// Recieves position in the world frame with global data (GPS)
void LogicController::SetMapPositionData(Point currentLocation) {
  range_controller.setCurrentLocation(currentLocation);

}

void LogicController::SetVelocityData(float linearVelocity, float angularVelocity) {
  driveController.SetVelocityData(linearVelocity,angularVelocity);
}

void LogicController::SetMapVelocityData(float linearVelocity, float angularVelocity) {

}

void LogicController::SetAprilTags(vector<TagPoint> tags) {
  pickUpController.SetTagData(tags);
  obstacleController.SetTagData(tags);
  dropOffController.SetTargetData(tags);
}

void LogicController::SetSonarData(float left, float center, float right) {
  pickUpController.SetSonarData(center);
  obstacleController.SetSonarData(left,center,right);
}

// Called once by RosAdapter in guarded init
void LogicController::SetCenterLocationOdom(Point centerLocationOdom) {
  searchController.SetCenterLocation(centerLocationOdom);
  dropOffController.SetCenterLocation(centerLocationOdom);
}

void LogicController::AddManualWaypoint(Point manualWaypoint)
{
  manualWaypointController.AddManualWaypoint(manualWaypoint);
}

void LogicController::setVirtualFenceOn( RangeShape* range )
{
  range_controller.setRangeShape(range);
  range_controller.setEnabled(true);
}

void LogicController::setVirtualFenceOff()
{
  range_controller.setEnabled(false);
}

void LogicController::SetCenterLocationMap(Point centerLocationMap) {

}

void LogicController::SetCurrentTimeInMilliSecs( long int time )
{
  current_time = time;
  dropOffController.SetCurrentTimeInMilliSecs( time );
  pickUpController.SetCurrentTimeInMilliSecs( time );
  obstacleController.SetCurrentTimeInMilliSecs( time );
}

void LogicController::SetModeAuto() {
  if(processState == PROCESS_STATE_MANUAL) {
    // only do something if we are in manual mode
    this->Reset();
  }
}
void LogicController::SetModeManual()
{
  if(processState != PROCESS_STATE_MANUAL) {
    logicState = LOGIC_STATE_INTERRUPT;
    processState = PROCESS_STATE_MANUAL;
    ProcessData();
    control_queue = priority_queue<PrioritizedController>();
    driveController.Reset();
  }
}
<commit_msg>Removed obstacle avoidance from Manual mode controllers<commit_after>#include "LogicController.h"

LogicController::LogicController() {

  logicState = LOGIC_STATE_INTERRUPT;
  processState = PROCCESS_STATE_SEARCHING;

  ProcessData();

  control_queue = priority_queue<PrioritizedController>();

}

LogicController::~LogicController() {}

void LogicController::Reset() {

  std::cout << "LogicController.Reset()" << std::endl;
  logicState = LOGIC_STATE_INTERRUPT;
  processState = PROCCESS_STATE_SEARCHING;

  ProcessData();

  control_queue = priority_queue<PrioritizedController>();
}

//***********************************************************************************************************************
//This function is called every 1/10th second by the ROSAdapter
//The logical flow if the behaviours is controlled here by using a interrupt, haswork, priority queue system.
Result LogicController::DoWork() {
  Result result;

  //first a loop runs through all the controllers who have a priority of 0 or above witht he largest number being
  //most important. A priority of less than 0 is an ignored controller use -1 for standards sake.
  //if any controller needs and interrupt the logic state is changed to interrupt
  for(PrioritizedController cntrlr : prioritizedControllers) {
    if(cntrlr.controller->ShouldInterrupt() && cntrlr.priority >= 0)
      {
	logicState = LOGIC_STATE_INTERRUPT;
	//do not break all shouldInterupts may need calling in order to properly pre-proccess data.
      }
  }

  //logic state switch
  switch(logicState) {

  //when an interrupt has been thorwn or there are no pending control_queue.top().actions logic controller is in this state.
  case LOGIC_STATE_INTERRUPT: {
    //Reset the control queue
    control_queue = priority_queue<PrioritizedController>();

    //check what controllers have work to do all that say yes will be added to the priority queue.
    for(PrioritizedController cntrlr : prioritizedControllers) {
      if(cntrlr.controller->HasWork()) {
        if (cntrlr.priority < 0) {
          continue;
        }
        else {
          control_queue.push(cntrlr);
        }
      }
    }

    //if no controlers have work report this to ROS Adapter and do nothing.
    if(control_queue.empty()) {
      result.type = behavior;
      result.b = wait;
      break;
    }
    else {
      //default result state if someone has work this safe gaurds against faulty result types
      result.b = noChange;
    }

    //take the top member of the priority queue and run their do work function.
    result = control_queue.top().controller->DoWork();

    //anaylyze the result that was returned and do state changes accordingly
    //behavior types are used to indicate behavior changes of some form
    if(result.type == behavior) {

      //ask for an external reset so the state of the controller is preserved untill after it has returned a result and
      //gotten a chance to communicate with other controllers
      if (result.reset) {
        controllerInterconnect(); //allow controller to communicate state data before it is reset
        control_queue.top().controller->Reset();
      }

      //ask for the procces state to change to the next state or loop around to the begining
      if(result.b == nextProcess) {
        if (processState == _LAST - 1) {
          processState = _FIRST;
        }
        else {
          processState = (ProcessState)((int)processState + 1);
        }
      }
      //ask for the procces state to change to the previouse state or loop around to the end
      else if(result.b == prevProcess) {
        if (processState == _FIRST) {
          processState = (ProcessState)((int)_LAST - 1);
        }
        else {
          processState = (ProcessState)((int)processState - 1);
        }
      }

      //update the priorites of the controllers based upon the new process state.
      if (result.b == nextProcess || result.b == prevProcess) {
        ProcessData();
        result.b = wait;
        driveController.Reset(); //it is assumed that the drive controller may be in a bad state if interrupted so reset it
      }
      break;
    }

    //precision driving result types are when a controller wants direct command of the robots actuators
    //logic controller facilitates the command pass through in the LOGIC_STATE_PRECISION_COMMAND switch case
    else if(result.type == precisionDriving) {

      logicState = LOGIC_STATE_PRECISION_COMMAND;
      break;

    }

    //waypoints are also a pass through facilitated command but with a slightly diffrent overhead
    //they are handled in the LOGIC_STATE_WAITING switch case
    else if(result.type == waypoint) {

      logicState = LOGIC_STATE_WAITING;
      driveController.SetResultData(result);
      //fall through on purpose
    }

  } //end of interupt case***************************************************************************************

    //this case is primarly when logic controller is waiting for drive controller to reach its last waypoint
  case LOGIC_STATE_WAITING: {
    //ask drive controller how to drive
    //commands to be passed the ROS Adapter as left and right wheel PWM values in the result struct are returned
    result = driveController.DoWork();

    //when out of waypoints drive controller will through an interrupt however unlike other controllers
    //drive controller is not on the priority queue so it must be checked here
    if (result.type == behavior) {
      if(driveController.ShouldInterrupt()) {
        logicState = LOGIC_STATE_INTERRUPT;
      }
    }
    break;
  }//end of waiting case*****************************************************************************************

    //used for precision driving pass through
  case LOGIC_STATE_PRECISION_COMMAND: {

    //unlike waypoints precision commands change every update tick so we ask the
    //controller for new commands on every update tick.
    result = control_queue.top().controller->DoWork();

    //pass the driving commands to the drive controller so it can interpret them
    driveController.SetResultData(result);

    //the interoreted commands are turned into properinitial_spiral_offset motor commands to be passed the ROS Adapter
    //as left and right wheel PWM values in the result struct.
    result = driveController.DoWork();
    break;

  }//end of precision case****************************************************************************************
  }//end switch statment******************************************************************************************

   // bad! causes node to crash
   // cout << "logic state " << logicState << " top controller " << control_queue.top().priority << " Proccess " << processState <<endl;

  //now using proccess logic allow the controller to communicate data between eachother
  controllerInterconnect();

  //give the ROSAdapter the final decision on how it should drive
  return result;
}

void LogicController::UpdateData() {

}

void LogicController::ProcessData() {

  //this controller priority is used when searching
  if (processState == PROCCESS_STATE_SEARCHING) {
    prioritizedControllers = {
      PrioritizedController{0, (Controller*)(&searchController)},
      PrioritizedController{10, (Controller*)(&obstacleController)},
      PrioritizedController{15, (Controller*)(&pickUpController)},
      PrioritizedController{5, (Controller*)(&range_controller)},
      PrioritizedController{-1, (Controller*)(&dropOffController)},
      PrioritizedController{-1, (Controller*)(&manualWaypointController)}
    };
  }

  //this priority is used when returning a target to the center collection zone
  else if (processState  == PROCCESS_STATE_TARGET_PICKEDUP) {
    prioritizedControllers = {
    PrioritizedController{-1, (Controller*)(&searchController)},
    PrioritizedController{15, (Controller*)(&obstacleController)},
    PrioritizedController{-1, (Controller*)(&pickUpController)},
    PrioritizedController{10, (Controller*)(&range_controller)},
    PrioritizedController{1, (Controller*)(&dropOffController)},
    PrioritizedController{-1, (Controller*)(&manualWaypointController)}
    };
  }
  //this priority is used when returning a target to the center collection zone
  else if (processState  == PROCCESS_STATE_DROP_OFF)
  {
    prioritizedControllers = {
      PrioritizedController{-1, (Controller*)(&searchController)},
      PrioritizedController{-1, (Controller*)(&obstacleController)},
      PrioritizedController{-1, (Controller*)(&pickUpController)},
      PrioritizedController{10, (Controller*)(&range_controller)},
      PrioritizedController{1, (Controller*)(&dropOffController)},
      PrioritizedController{-1, (Controller*)(&manualWaypointController)}
    };
  }
  else if (processState == PROCESS_STATE_MANUAL) {
    prioritizedControllers = {
      PrioritizedController{-1, (Controller*)(&searchController)},
      PrioritizedController{-1, (Controller*)(&obstacleController)},
      PrioritizedController{-1, (Controller*)(&pickUpController)},
      PrioritizedController{-1, (Controller*)(&range_controller)},
      PrioritizedController{-1, (Controller*)(&dropOffController)},
      PrioritizedController{5,  (Controller*)(&manualWaypointController)}
    };
  }
}

bool LogicController::ShouldInterrupt() {
  ProcessData();

  return false;
}

bool LogicController::HasWork() {
  return false;
}

void LogicController::controllerInterconnect() {

  if (processState == PROCCESS_STATE_SEARCHING) {

    //obstacle needs to know if the center ultrasound should be ignored
    if(pickUpController.GetIgnoreCenter()) {
      obstacleController.SetIgnoreCenter();
    }

    //pickup controller annouces it has pickedup a target
    if(pickUpController.GetTargetHeld()) {
      dropOffController.SetTargetPickedUp();
      obstacleController.SetTargetHeld();
      searchController.SetSuccesfullPickup();
    }
  }

  //ask if drop off has released the target from the claws yet
  if (!dropOffController.HasTarget()) {
    obstacleController.SetTargetHeldClear();
  }

  //obstacle controller is running driveController needs to clear its waypoints
  if(obstacleController.GetShouldClearWaypoints()) {
    driveController.Reset();
  }

}

// Recieves position in the world inertial frame (should rename to SetOdomPositionData)
void LogicController::SetPositionData(Point currentLocation) {
  searchController.SetCurrentLocation(currentLocation);
  dropOffController.SetCurrentLocation(currentLocation);
  obstacleController.SetCurrentLocation(currentLocation);
  driveController.SetCurrentLocation(currentLocation);
  manualWaypointController.SetCurrentLocation(currentLocation);
}

// Recieves position in the world frame with global data (GPS)
void LogicController::SetMapPositionData(Point currentLocation) {
  range_controller.setCurrentLocation(currentLocation);

}

void LogicController::SetVelocityData(float linearVelocity, float angularVelocity) {
  driveController.SetVelocityData(linearVelocity,angularVelocity);
}

void LogicController::SetMapVelocityData(float linearVelocity, float angularVelocity) {

}

void LogicController::SetAprilTags(vector<TagPoint> tags) {
  pickUpController.SetTagData(tags);
  obstacleController.SetTagData(tags);
  dropOffController.SetTargetData(tags);
}

void LogicController::SetSonarData(float left, float center, float right) {
  pickUpController.SetSonarData(center);
  obstacleController.SetSonarData(left,center,right);
}

// Called once by RosAdapter in guarded init
void LogicController::SetCenterLocationOdom(Point centerLocationOdom) {
  searchController.SetCenterLocation(centerLocationOdom);
  dropOffController.SetCenterLocation(centerLocationOdom);
}

void LogicController::AddManualWaypoint(Point manualWaypoint)
{
  manualWaypointController.AddManualWaypoint(manualWaypoint);
}

void LogicController::setVirtualFenceOn( RangeShape* range )
{
  range_controller.setRangeShape(range);
  range_controller.setEnabled(true);
}

void LogicController::setVirtualFenceOff()
{
  range_controller.setEnabled(false);
}

void LogicController::SetCenterLocationMap(Point centerLocationMap) {

}

void LogicController::SetCurrentTimeInMilliSecs( long int time )
{
  current_time = time;
  dropOffController.SetCurrentTimeInMilliSecs( time );
  pickUpController.SetCurrentTimeInMilliSecs( time );
  obstacleController.SetCurrentTimeInMilliSecs( time );
}

void LogicController::SetModeAuto() {
  if(processState == PROCESS_STATE_MANUAL) {
    // only do something if we are in manual mode
    this->Reset();
  }
}
void LogicController::SetModeManual()
{
  if(processState != PROCESS_STATE_MANUAL) {
    logicState = LOGIC_STATE_INTERRUPT;
    processState = PROCESS_STATE_MANUAL;
    ProcessData();
    control_queue = priority_queue<PrioritizedController>();
    driveController.Reset();
  }
}
<|endoftext|>


<commit_before>/*
 * jcom.hub - internals
 * manage internal objects that are hosted within the hub for a module
 * By Tim Place, Copyright  2007
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "jcom.hub.h"

class hubInternalObject {
	private:
	t_object	*theObject;

	public:
	method		action;

	hubInternalObject(char *classname, char *subscribername, char *subscribertype, char *ramptype, char *description)
	{
		t_atom		a[7];

		theObject = NULL;
		atom_setsym(a+0, gensym(subscribername));
		atom_setsym(a+1, gensym("@type"));
		atom_setsym(a+2, gensym(subscribertype));
		atom_setsym(a+3, gensym("@ramp/drive"));
		atom_setsym(a+4, gensym(ramptype));
		atom_setsym(a+5, gensym("@description"));
		atom_setsym(a+6, gensym(description));
		jcom_core_loadextern(gensym(classname), 7, a, &theObject);
	}

	~hubInternalObject()
	{
		object_free(theObject);
	}
};

void hub_internals_create(t_hub *x)
{
	hubInternalObject	*anObject;

	x->hash_internals = hashtab_new(0);

	anObject = new hubInternalObject("jcom.message", 	"init",						"msg_none",		"none",	"Initialize a module completely to the original state.");
	anObject->action = (method)hub_init;
	hashtab_store(x->hash_internals, gensym("init"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"documentation/generate",	"msg_none",		"none",	"Generate a documentation page for this module and save it to disk.");
	anObject->action = (method)hub_autodoc;
	hashtab_store(x->hash_internals, gensym("documentation/generate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"module/view_internals",	"msg_none",		"none",	"Attempts to open the internal algorithm for viewing.  This works for most modules.  Some modules may choose to cloak the algorithms - preventing this message from functioning.");
	anObject->action = (method)hub_module_view_alg;
	hashtab_store(x->hash_internals, gensym("module/view_internals"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/read",				"msg_symbol",	"none",	"Open an xml-preset file and recall the first preset in that file.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_read;
	hashtab_store(x->hash_internals, gensym("preset/read"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/write",				"msg_symbol",	"none",	"Write an xml-preset file to disk.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_write;
	hashtab_store(x->hash_internals, gensym("preset/write"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/recall",			"msg_generic",	"none",	"Recall a preset by number - you can also choose presets from the module menu.");
	anObject->action = (method)hub_preset_recall;
	hashtab_store(x->hash_internals, gensym("preset/recall"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/copy",				"msg_list",		"none",	"Create a new preset (2nd argument) by copying the contents of another preset (1st argument)");
	anObject->action = (method)hub_preset_copy;
	hashtab_store(x->hash_internals, gensym("preset/copy"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/store",				"msg_list",		"none",	"Store a preset by number in memory.  All presets present in memory will be written to disk when you send a save_settings message to the module.");
	anObject->action = (method)hub_preset_store;
	hashtab_store(x->hash_internals, gensym("preset/store"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/storenext",			"msg_list",		"none",	"Store a preset in the next preset slot.  Handy so that you do not need to specify a preset number manually.");
	anObject->action = (method)hub_preset_store_next;
	hashtab_store(x->hash_internals, gensym("preset/storenext"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/interpolate",		"msg_list",		"none",	"Interpolate between two named presets (argument 1 and 2) using a ratio (float in the range [0.0, 1.0]) specified as the third argument.");
	anObject->action = (method)hub_preset_interpolate;
	hashtab_store(x->hash_internals, gensym("preset/interpolate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/default",			"msg_none",		"none",	"Open the default preset file and recall the first preset in that file.");
	anObject->action = (method)hub_preset_default;
	hashtab_store(x->hash_internals, gensym("preset/default"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/clear",				"msg_none",		"none",	"This is the same preset/default.");
	anObject->action = (method)hub_preset_default;
	hashtab_store(x->hash_internals, gensym("preset/clear"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/post",				"msg_none",		"none",	"Post all presets to the Max window.");
	anObject->action = (method)hub_presets_dump;
	hashtab_store(x->hash_internals, gensym("preset/post"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.parameter",	"ui/freeze",				"msg_toggle",	"none",	"Turn off the updating of user interface elements when parameters change.  This may be done to conserve CPU resources.");
	anObject->action = (method)hub_ui_freeze;
	hashtab_store(x->hash_internals, gensym("ui/freeze"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"ui/refresh",				"msg_none",		"none",	"Update displayed values for module to reflect current state.");
	anObject->action = (method)hub_ui_refresh;
	hashtab_store(x->hash_internals, gensym("ui/refresh"), (t_object*)anObject);
}

void hub_internals_destroy(t_hub *x)
{
	long				i;
	long				numKeys;
	t_symbol			**keys;
	hubInternalObject	*anObject;
	t_max_err			err;

	hashtab_getkeys(x->hash_internals, &numKeys, &keys);
	for(i=0; i<numKeys; i++){
		err = hashtab_lookup(x->hash_internals, keys[i], (t_object**)&anObject);
		if(!err)
			delete anObject;
	}
	hashtab_chuck(x->hash_internals);
}

void hub_internals_dispatch(t_hub *x, t_symbol *osc_name, long argc, t_atom *argv)
{
	hubInternalObject	*theObject;
	t_max_err			err;

	err = hashtab_lookup(x->hash_internals, osc_name, (t_object**)&theObject);
	if(!err)
		theObject->action(x, osc_name, argc, argv);
}

<commit_msg>/preset/clear now calls the clear method rather than the default method<commit_after>/*
 * jcom.hub - internals
 * manage internal objects that are hosted within the hub for a module
 * By Tim Place, Copyright  2007
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "jcom.hub.h"

class hubInternalObject {
	private:
	t_object	*theObject;

	public:
	method		action;

	hubInternalObject(char *classname, char *subscribername, char *subscribertype, char *ramptype, char *description)
	{
		t_atom		a[7];

		theObject = NULL;
		atom_setsym(a+0, gensym(subscribername));
		atom_setsym(a+1, gensym("@type"));
		atom_setsym(a+2, gensym(subscribertype));
		atom_setsym(a+3, gensym("@ramp/drive"));
		atom_setsym(a+4, gensym(ramptype));
		atom_setsym(a+5, gensym("@description"));
		atom_setsym(a+6, gensym(description));
		jcom_core_loadextern(gensym(classname), 7, a, &theObject);
	}

	~hubInternalObject()
	{
		object_free(theObject);
	}
};

void hub_internals_create(t_hub *x)
{
	hubInternalObject	*anObject;

	x->hash_internals = hashtab_new(0);

	anObject = new hubInternalObject("jcom.message", 	"init",						"msg_none",		"none",	"Initialize a module completely to the original state.");
	anObject->action = (method)hub_init;
	hashtab_store(x->hash_internals, gensym("init"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"documentation/generate",	"msg_none",		"none",	"Generate a documentation page for this module and save it to disk.");
	anObject->action = (method)hub_autodoc;
	hashtab_store(x->hash_internals, gensym("documentation/generate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"module/view_internals",	"msg_none",		"none",	"Attempts to open the internal algorithm for viewing.  This works for most modules.  Some modules may choose to cloak the algorithms - preventing this message from functioning.");
	anObject->action = (method)hub_module_view_alg;
	hashtab_store(x->hash_internals, gensym("module/view_internals"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/read",				"msg_symbol",	"none",	"Open an xml-preset file and recall the first preset in that file.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_read;
	hashtab_store(x->hash_internals, gensym("preset/read"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/write",				"msg_symbol",	"none",	"Write an xml-preset file to disk.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_write;
	hashtab_store(x->hash_internals, gensym("preset/write"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/recall",			"msg_generic",	"none",	"Recall a preset by number - you can also choose presets from the module menu.");
	anObject->action = (method)hub_preset_recall;
	hashtab_store(x->hash_internals, gensym("preset/recall"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/copy",				"msg_list",		"none",	"Create a new preset (2nd argument) by copying the contents of another preset (1st argument)");
	anObject->action = (method)hub_preset_copy;
	hashtab_store(x->hash_internals, gensym("preset/copy"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/store",				"msg_list",		"none",	"Store a preset by number in memory.  All presets present in memory will be written to disk when you send a save_settings message to the module.");
	anObject->action = (method)hub_preset_store;
	hashtab_store(x->hash_internals, gensym("preset/store"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/storenext",			"msg_list",		"none",	"Store a preset in the next preset slot.  Handy so that you do not need to specify a preset number manually.");
	anObject->action = (method)hub_preset_store_next;
	hashtab_store(x->hash_internals, gensym("preset/storenext"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/interpolate",		"msg_list",		"none",	"Interpolate between two named presets (argument 1 and 2) using a ratio (float in the range [0.0, 1.0]) specified as the third argument.");
	anObject->action = (method)hub_preset_interpolate;
	hashtab_store(x->hash_internals, gensym("preset/interpolate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/default",			"msg_none",		"none",	"Open the default preset file and recall the first preset in that file.");
	anObject->action = (method)hub_preset_default;
	hashtab_store(x->hash_internals, gensym("preset/default"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/clear",				"msg_none",		"none",	"This is the same preset/default.");
	anObject->action = (method)hub_presets_clear;
	hashtab_store(x->hash_internals, gensym("preset/clear"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/post",				"msg_none",		"none",	"Post all presets to the Max window.");
	anObject->action = (method)hub_presets_dump;
	hashtab_store(x->hash_internals, gensym("preset/post"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.parameter",	"ui/freeze",				"msg_toggle",	"none",	"Turn off the updating of user interface elements when parameters change.  This may be done to conserve CPU resources.");
	anObject->action = (method)hub_ui_freeze;
	hashtab_store(x->hash_internals, gensym("ui/freeze"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"ui/refresh",				"msg_none",		"none",	"Update displayed values for module to reflect current state.");
	anObject->action = (method)hub_ui_refresh;
	hashtab_store(x->hash_internals, gensym("ui/refresh"), (t_object*)anObject);
}

void hub_internals_destroy(t_hub *x)
{
	long				i;
	long				numKeys;
	t_symbol			**keys;
	hubInternalObject	*anObject;
	t_max_err			err;

	hashtab_getkeys(x->hash_internals, &numKeys, &keys);
	for(i=0; i<numKeys; i++){
		err = hashtab_lookup(x->hash_internals, keys[i], (t_object**)&anObject);
		if(!err)
			delete anObject;
	}
	hashtab_chuck(x->hash_internals);
}

void hub_internals_dispatch(t_hub *x, t_symbol *osc_name, long argc, t_atom *argv)
{
	hubInternalObject	*theObject;
	t_max_err			err;

	err = hashtab_lookup(x->hash_internals, osc_name, (t_object**)&theObject);
	if(!err)
		theObject->action(x, osc_name, argc, argv);
}

<|endoftext|>


<commit_before>//  File: cloud_auth_unittests.cc
//  Author: Tom Roeder <tmroeder@google.com>
//
//  Description: Basic tests for the CloudAuth class.
//
//  Copyright (c) 2014, Google Inc.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <stdlib.h>

#include <fstream>

#include <gtest/gtest.h>
#include <glog/logging.h>
#include <keyczar/keyczar.h>

#include "cloudproxy/cloud_auth.h"
#include "cloudproxy/util.h"
#include "tao/fake_tao.h"
#include "tao/util.h"

using cloudproxy::CloudAuth;
using cloudproxy::ACL;
using cloudproxy::Action;
using cloudproxy::SignedACL;

using keyczar::Keyczar;

using std::ofstream;

using tao::CreateTempPubKey;
using tao::ScopedTempDir;
using tao::SignData;

class CloudAuthTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    EXPECT_TRUE(CreateTempPubKey(&temp_dir_, &policy_public_key_))
      << "Could not create a public key";

    // Set up a simple ACL to query.
    ACL acl;
    Action *a1 = acl.add_permissions();
    a1->set_subject("tmroeder");
    a1->set_verb(cloudproxy::ADMIN);

    Action *a2 = acl.add_permissions();
    a2->set_subject("jlm");
    a2->set_verb(cloudproxy::CREATE);
    a2->set_object("/files");

    SignedACL sacl;
    string *ser = sacl.mutable_serialized_acls();
    EXPECT_TRUE(acl.SerializeToString(ser)) << "Could not serialize ACL";

    string *sig = sacl.mutable_signature();
    EXPECT_TRUE(SignData(*ser, sig, policy_public_key_.get()))
      << "Could not sign the serialized ACL with the policy key";

    string signed_whitelist_path = *temp_dir_ + string("/signed_whitelist");
    ofstream whitelist_file(signed_whitelist_path.c_str(), ofstream::out);
    ASSERT_TRUE(whitelist_file) << "Could not open " << signed_whitelist_path;

    EXPECT_TRUE(sacl.SerializeToOstream(&whitelist_file))
      << "Could not write the signed whitelist to a file";

    whitelist_file.close();

    cloud_auth_.reset(new CloudAuth(signed_whitelist_path,
                                    policy_public_key_.get()));
  }

  scoped_ptr<CloudAuth> cloud_auth_;
  scoped_ptr<Keyczar> policy_public_key_;
  ScopedTempDir temp_dir_;
};

TEST_F(CloudAuthTest, AdminTest) {
  // Admin privileges should allow tmroeder to perform any operation.
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::CREATE, "/files"));
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::DESTROY,
                                     "/files"));
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::READ, "/files_2"));
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::WRITE, "/asdf"));
}

TEST_F(CloudAuthTest, UnknownUserTest) {
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::CREATE, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::DESTROY,
                                     "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::READ, "/files_2"));
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::WRITE, "/asdf"));
}

TEST_F(CloudAuthTest, LimitedUserTest) {
  // A user with limited permissions should only be allowed those permissions.
  EXPECT_TRUE(cloud_auth_->Permitted("jlm", cloudproxy::CREATE, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::DESTROY,
                                     "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::READ, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::WRITE, "/files"));
}

TEST_F(CloudAuthTest, AddPermissionsTest) {
  // Permissions can be added to the ACL
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::CREATE, "/files"));
  EXPECT_TRUE(cloud_auth_->Insert("jlm", cloudproxy::DESTROY, "/files"));
  EXPECT_TRUE(cloud_auth_->Permitted("jlm", cloudproxy::DESTROY, "/files"));

}
<commit_msg>Added more tests for CloudAuth<commit_after>//  File: cloud_auth_unittests.cc
//  Author: Tom Roeder <tmroeder@google.com>
//
//  Description: Basic tests for the CloudAuth class.
//
//  Copyright (c) 2014, Google Inc.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <stdlib.h>

#include <fstream>

#include <gtest/gtest.h>
#include <glog/logging.h>
#include <keyczar/keyczar.h>

#include "cloudproxy/cloud_auth.h"
#include "cloudproxy/util.h"
#include "tao/fake_tao.h"
#include "tao/util.h"

using cloudproxy::CloudAuth;
using cloudproxy::ACL;
using cloudproxy::Action;
using cloudproxy::SignedACL;

using keyczar::Keyczar;

using std::ofstream;

using tao::CreateTempPubKey;
using tao::ScopedTempDir;
using tao::SignData;

class CloudAuthTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    EXPECT_TRUE(CreateTempPubKey(&temp_dir_, &policy_public_key_))
      << "Could not create a public key";

    // Set up a simple ACL to query.
    ACL acl;
    Action *a1 = acl.add_permissions();
    a1->set_subject("tmroeder");
    a1->set_verb(cloudproxy::ADMIN);

    Action *a2 = acl.add_permissions();
    a2->set_subject("jlm");
    a2->set_verb(cloudproxy::CREATE);
    a2->set_object("/files");

    SignedACL sacl;
    string *ser = sacl.mutable_serialized_acls();
    EXPECT_TRUE(acl.SerializeToString(ser)) << "Could not serialize ACL";

    string *sig = sacl.mutable_signature();
    EXPECT_TRUE(SignData(*ser, sig, policy_public_key_.get()))
      << "Could not sign the serialized ACL with the policy key";

    string signed_whitelist_path = *temp_dir_ + string("/signed_whitelist");
    ofstream whitelist_file(signed_whitelist_path.c_str(), ofstream::out);
    ASSERT_TRUE(whitelist_file) << "Could not open " << signed_whitelist_path;

    EXPECT_TRUE(sacl.SerializeToOstream(&whitelist_file))
      << "Could not write the signed whitelist to a file";

    whitelist_file.close();

    cloud_auth_.reset(new CloudAuth(signed_whitelist_path,
                                    policy_public_key_.get()));
  }

  scoped_ptr<CloudAuth> cloud_auth_;
  scoped_ptr<Keyczar> policy_public_key_;
  ScopedTempDir temp_dir_;
};

TEST_F(CloudAuthTest, AdminTest) {
  // Admin privileges should allow tmroeder to perform any operation.
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::CREATE, "/files"));
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::DESTROY,
                                     "/files"));
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::READ, "/files_2"));
  EXPECT_TRUE(cloud_auth_->Permitted("tmroeder", cloudproxy::WRITE, "/asdf"));
}

TEST_F(CloudAuthTest, UnknownUserTest) {
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::CREATE, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::DESTROY,
                                     "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::READ, "/files_2"));
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::WRITE, "/asdf"));
}

TEST_F(CloudAuthTest, LimitedUserTest) {
  // A user with limited permissions should only be allowed those permissions.
  EXPECT_TRUE(cloud_auth_->Permitted("jlm", cloudproxy::CREATE, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::DESTROY,
                                     "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::READ, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::WRITE, "/files"));
}

TEST_F(CloudAuthTest, AddPermissionsTest) {
  // Permissions can be added to the ACL
  EXPECT_FALSE(cloud_auth_->Permitted("unknown_user", cloudproxy::CREATE, "/files"));
  EXPECT_TRUE(cloud_auth_->Insert("jlm", cloudproxy::DESTROY, "/files"));
  EXPECT_TRUE(cloud_auth_->Permitted("jlm", cloudproxy::DESTROY, "/files"));
}

TEST_F(CloudAuthTest, DeletePermissionsTest) {
  EXPECT_TRUE(cloud_auth_->Permitted("jlm", cloudproxy::CREATE, "/files"));
  EXPECT_TRUE(cloud_auth_->Delete("jlm", cloudproxy::CREATE, "/files"));
  EXPECT_FALSE(cloud_auth_->Permitted("jlm", cloudproxy::CREATE, "/files"));
}

TEST_F(CloudAuthTest, DeletePermissionsFailTest) {
  // You can't delete permissions that aren't there.
  EXPECT_FALSE(cloud_auth_->Delete("jlm", cloudproxy::READ, "/files"));
  EXPECT_FALSE(cloud_auth_->Delete("jlm", cloudproxy::CREATE, "/files_2"));
  EXPECT_FALSE(cloud_auth_->Delete("tmroeder", cloudproxy::CREATE, "/files"));
}

TEST_F(CloudAuthTest, SerializeTest) {
  string serialized_auth;
  EXPECT_TRUE(cloud_auth_->Serialize(&serialized_auth));
}
<|endoftext|>


<commit_before>#include <string.h>
#include <stdlib.h>
#include <string>
#include "core/error.h"
#include "core/package/load.h"

using namespace std;

inline void
InkWarn_Unknown_Argument(const char *name)
{
	InkWarn_doPrintWarning("Ink Packer: Unknown argument \"$(name)\"", name);
	return;
}

inline void
InkWarn_Excess_Argument(const char *name)
{
	InkWarn_doPrintWarning("Ink Packer: Excess argument \"$(name)\"", name);
	return;
}

inline void
InkErr_No_Lib_Given()
{
	InkErr_doPrintError("Ink Packer: No library file given");
	return;
}

inline void
InkErr_No_Dest_Given()
{
	InkErr_doPrintError("Ink Packer: No output file given");
	return;
}

inline void
InkErr_Could_Not_Create_File(const char *path)
{
	InkErr_doPrintError("Ink Packer: Couldn't create file $(path)", path);
	return;
}

enum Instr {
	UNKNOWN = 0,
	PACKAGE_NAME,
	AUTHOR
};

class Argument {
public:
	Instr instr;
	char *arg;

	Argument(char *origin)
	{
		int i, len = strlen(origin), start;
		string instr_str;

		for (i = 0; i < len && origin[i] == '-'; i++) ;
		start = i;

		for (; i < len; i++) {
			if (origin[i] == '=') {
				break;
			}
		}

		arg = NULL;
		if (i < len) {
			instr_str = string(origin).substr(start, i - 2);
		} else {
			instr_str = string(origin).substr(start);
			return;
		}

		if (!strcmp(instr_str.c_str(), "package-name")) {
			instr = PACKAGE_NAME;
		} else if (!strcmp(instr_str.c_str(), "author")) {
			instr = AUTHOR;
		} else {
			instr = UNKNOWN;
			InkWarn_Unknown_Argument(instr_str.c_str());
			return;
		}

		arg = (char *)malloc(sizeof(char) * (len - i));
		strcpy(arg, string(origin).substr(i + 1, len - i - 1).c_str());
	}

	~Argument()
	{
		if (arg)
			free(arg);
	}
};

#define MAX_ARG_COUNT 1000

int main(int argc, char **argv)
{
	int i, argi = 0;
	const char *so_file = NULL, *pack_name = "Unknown", *author = "Anonymous";
	char *target = NULL;
	Argument *arg[MAX_ARG_COUNT];

	for (i = 1; i < argc; i++) {
		if (argv[i][0] != '-') {
			if (!so_file)
				so_file = argv[i];
			else if (!target)
				target = argv[i];
			else InkWarn_Excess_Argument(argv[i]);
		} else {
			arg[argi++] = new Argument(argv[i]);
		}
	}

	for (i = 0; i < argi; i++) {
		if (arg[i]->instr == PACKAGE_NAME) {
			pack_name = arg[i]->arg;
		} else if (arg[i]->instr == PACKAGE_NAME) {
			author = arg[i]->arg;
		}
	}

	if (!so_file) {
		InkErr_No_Lib_Given();
		// unreachable
	}

	if (!target) {
		InkErr_No_Dest_Given();
		// unreachable
	}

	FILE *fp;
	fp = fopen(target, "wb");

	if (!fp) {
		InkErr_Could_Not_Create_File(target);
		// unreachable
	}

	Ink_Package *pack = new Ink_Package(pack_name, author, so_file);
	pack->writeTo(fp);
	fflush(fp);
	fclose(fp);

	return 0;
}<commit_msg>090116#09: a little problem in ink packer<commit_after>#include <string.h>
#include <stdlib.h>
#include <string>
#include "core/error.h"
#include "core/package/load.h"

using namespace std;

inline void
InkWarn_Unknown_Argument(const char *name)
{
	InkWarn_doPrintWarning("Ink Packer: Unknown argument \"$(name)\"", name);
	return;
}

inline void
InkWarn_Excess_Argument(const char *name)
{
	InkWarn_doPrintWarning("Ink Packer: Excess argument \"$(name)\"", name);
	return;
}

inline void
InkErr_No_Lib_Given()
{
	InkErr_doPrintError("Ink Packer: No library file given");
	return;
}

inline void
InkErr_No_Dest_Given()
{
	InkErr_doPrintError("Ink Packer: No output file given");
	return;
}

inline void
InkErr_Could_Not_Create_File(const char *path)
{
	InkErr_doPrintError("Ink Packer: Couldn't create file $(path)", path);
	return;
}

enum Instr {
	UNKNOWN = 0,
	PACKAGE_NAME,
	AUTHOR
};

class Argument {
public:
	Instr instr;
	char *arg;

	Argument(char *origin)
	{
		int i, len = strlen(origin), start;
		string instr_str;

		for (i = 0; i < len && origin[i] == '-'; i++) ;
		start = i;

		for (; i < len; i++) {
			if (origin[i] == '=') {
				break;
			}
		}

		arg = NULL;
		if (i < len) {
			instr_str = string(origin).substr(start, i - 2);
		} else {
			instr_str = string(origin).substr(start);
			return;
		}

		if (!strcmp(instr_str.c_str(), "package-name")) {
			instr = PACKAGE_NAME;
		} else if (!strcmp(instr_str.c_str(), "author")) {
			instr = AUTHOR;
		} else {
			instr = UNKNOWN;
			InkWarn_Unknown_Argument(instr_str.c_str());
			return;
		}

		arg = (char *)malloc(sizeof(char) * (len - i));
		strcpy(arg, string(origin).substr(i + 1, len - i - 1).c_str());
	}

	~Argument()
	{
		if (arg)
			free(arg);
	}
};

#define MAX_ARG_COUNT 1000

int main(int argc, char **argv)
{
	int i, argi = 0;
	const char *so_file = NULL, *pack_name = "Unknown", *author = "Anonymous";
	char *target = NULL;
	Argument *arg[MAX_ARG_COUNT];

	for (i = 1; i < argc; i++) {
		if (argv[i][0] != '-') {
			if (!so_file)
				so_file = argv[i];
			else if (!target)
				target = argv[i];
			else InkWarn_Excess_Argument(argv[i]);
		} else {
			arg[argi++] = new Argument(argv[i]);
		}
	}

	for (i = 0; i < argi; i++) {
		if (arg[i]->instr == PACKAGE_NAME) {
			pack_name = arg[i]->arg;
		} else if (arg[i]->instr == AUTHOR) {
			author = arg[i]->arg;
		}
	}

	if (!so_file) {
		InkErr_No_Lib_Given();
		// unreachable
	}

	if (!target) {
		InkErr_No_Dest_Given();
		// unreachable
	}

	FILE *fp;
	fp = fopen(target, "wb");

	if (!fp) {
		InkErr_Could_Not_Create_File(target);
		// unreachable
	}

	Ink_Package *pack = new Ink_Package(pack_name, author, so_file);
	pack->writeTo(fp);
	fflush(fp);
	fclose(fp);

	return 0;
}<|endoftext|>


<commit_before>/*
 * Dragable.cpp
 *
 *  Created on: Jan 24, 2015
 *      Author: dawid
 */

#include "Draggable.h"

#include <cocos2d.h>

#include <component/touch/drag/OnDragEvent.h>
#include <component/ComponentManager.h>
#include <component/builder/Flags.h>
#include <component/touch/TouchableEvents.h>

namespace Dexode
{
namespace Component
{

void Draggable::onTouchBegan(cocos2d::Touch* touch)
{
	_startPosition = getWorkingNode()->getPosition();
	if (_onTouchBegan)
	{
		OnDragEvent event;
		event.node = getWorkingNode();
		event.touch = touch;
		event.startPosition = _startPosition;
		_onTouchBegan(event);
	}
}

void Draggable::onTouchMoved(cocos2d::Touch* touch)
{
	if ((_flags & Config::Draggable::MOVING_ONLY_X) != 0)
	{
		getWorkingNode()->setPositionX(_startPosition.x - (touch->getStartLocation().x - touch->getLocation().x));
	}
	else
	{
		getWorkingNode()->setPosition(_startPosition - (touch->getStartLocation() - touch->getLocation()));
	}

	if (_onTouchMoved)
	{
		OnDragEvent event;
		event.node = getWorkingNode();
		event.touch = touch;
		event.startPosition = _startPosition;
		_onTouchMoved(event);
	}
}

void Draggable::onTouchEnded(cocos2d::Touch* touch)
{
	if ((_flags & Config::Draggable::DO_NOT_RESTORE_POSITION_ON_END)
		!= Config::Draggable::DO_NOT_RESTORE_POSITION_ON_END)
	{
		getWorkingNode()->setPosition(_startPosition);
	}

	if (_onTouchEnded)
	{
		OnDragEvent event;
		event.node = getWorkingNode();
		event.touch = touch;
		event.startPosition = _startPosition;
		_onTouchEnded(event);
	}
}

void Draggable::setListeners(const OnTouch& onTouchBegan, const OnTouch& onTouchMoved, const OnTouch& onTouchEnded)
{
	_onTouchBegan = onTouchBegan;
	_onTouchMoved = onTouchMoved;
	_onTouchEnded = onTouchEnded;
}

void Draggable::setFlags(int flags)
{
	_flags = flags;
}

void Draggable::onAttach()
{
	inherited::onAttach();
	_collector = listenForTouches(this);
}

void Draggable::onDetach()
{
	_collector.unlistenAll();
	inherited::onDetach();
}

} /* namespace Component */
} /* namespace Dexode */
<commit_msg>Fix Draggable<commit_after>/*
 * Dragable.cpp
 *
 *  Created on: Jan 24, 2015
 *      Author: dawid
 */

#include "Draggable.h"

#include <cocos2d.h>

#include <component/touch/drag/OnDragEvent.h>
#include <component/ComponentManager.h>
#include <component/builder/Flags.h>
#include <component/touch/TouchableEvents.h>

namespace Dexode
{
namespace Component
{

void Draggable::onTouchBegan(cocos2d::Touch* touch)
{
	_startPosition = getWorkingNode()->getPosition();
	if (_onTouchBegan)
	{
		OnDragEvent event;
		event.node = getWorkingNode();
		event.touch = touch;
		event.startPosition = _startPosition;
		_onTouchBegan(event);
	}
}

void Draggable::onTouchMoved(cocos2d::Touch* touch)
{
	if ((_flags & Config::Draggable::MOVING_ONLY_X) != 0)
	{
		getWorkingNode()->setPositionX(_startPosition.x - (touch->getStartLocation().x - touch->getLocation().x));
	}
	else
	{
		getWorkingNode()->setPosition(_startPosition - (touch->getStartLocation() - touch->getLocation()));
	}

	if (_onTouchMoved)
	{
		OnDragEvent event;
		event.node = getWorkingNode();
		event.touch = touch;
		event.startPosition = _startPosition;
		_onTouchMoved(event);
	}
}

void Draggable::onTouchEnded(cocos2d::Touch* touch)
{
	if (_onTouchEnded)
	{
		OnDragEvent event;
		event.node = getWorkingNode();
		event.touch = touch;
		event.startPosition = _startPosition;
		_onTouchEnded(event);
	}

	if ((_flags & Config::Draggable::DO_NOT_RESTORE_POSITION_ON_END)
		!= Config::Draggable::DO_NOT_RESTORE_POSITION_ON_END)
	{
		getWorkingNode()->setPosition(_startPosition);
	}
}

void Draggable::setListeners(const OnTouch& onTouchBegan, const OnTouch& onTouchMoved, const OnTouch& onTouchEnded)
{
	_onTouchBegan = onTouchBegan;
	_onTouchMoved = onTouchMoved;
	_onTouchEnded = onTouchEnded;
}

void Draggable::setFlags(int flags)
{
	_flags = flags;
}

void Draggable::onAttach()
{
	inherited::onAttach();
	_collector = listenForTouches(this);
}

void Draggable::onDetach()
{
	_collector.unlistenAll();
	inherited::onDetach();
}

} /* namespace Component */
} /* namespace Dexode */
<|endoftext|>


<commit_before>// Copyright 2014 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "elang/compiler/testing/compiler_test.h"

namespace elang {
namespace compiler {
namespace {

//////////////////////////////////////////////////////////////////////
//
// NamespaceAnalyzerTest
//
class NamespaceAnalyzerTest : public testing::CompilerTest {
 protected:
  NamespaceAnalyzerTest() = default;
  ~NamespaceAnalyzerTest() override = default;

 private:
  DISALLOW_COPY_AND_ASSIGN(NamespaceAnalyzerTest);
};

//////////////////////////////////////////////////////////////////////
//
// Alias resolution
//
TEST_F(NamespaceAnalyzerTest, AliasBasic) {
  Prepare(
      "namespace N1.N2 { class A {} }"
      "namespace N3 { using C = N1.N2.A; class B : C {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.B"));
}

// Same as |AliasBasic|, but order of declaration is different.
TEST_F(NamespaceAnalyzerTest, AliasLayout) {
  Prepare(
      "namespace N3 { using C = N1.N2.A; class B : C {} }"
      "namespace N1.N2 { class A {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.B"));
}

TEST_F(NamespaceAnalyzerTest, AliasExtent) {
  Prepare(
      "using R = N1.N2;"
      "namespace N1.N2 { class A {} }"
      "namespace N3 { class B : R.A {} }"
      "namespace N3 { class C : R.A {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.B"));
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.C"));
}

TEST_F(NamespaceAnalyzerTest, AliasToAlias) {
  Prepare(
      "using R1 = A.B;"
      "class A { class B { class C {} } }"
      "namespace N1 {"
      "  using R2 = R1;"
      "  class D : R2.C {}"
      "}");
  ASSERT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("A.B.C", GetBaseClasses("N1.D"));
}

TEST_F(NamespaceAnalyzerTest, AliasToAliasDeep) {
  Prepare(
      "using R1 = N1.N2.A.B;"
      "namespace N1 {"
      "  using R2 = R1;"
      "  class D : R2.C {}"
      "  namespace N2 {"
      "     class A { class B { class C {} } }"
      "  }"
      "}");
  ASSERT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A.B.C", GetBaseClasses("N1.D"));
}

// Note: MS C# compiler doesn't report error if alias A isn't used.
TEST_F(NamespaceAnalyzerTest, AliasErrorAmbiguous) {
  Prepare(
      "namespace N1.N2 { class A {} }"
      "namespace N3 { class A {} }"
      "namespace N3 {"
      "  using A = N1.N2.A;"
      "  class B : A {}"  // A can be N1.N2.A or N3.A.
      "}");
  EXPECT_EQ("NameResolution.Name.Ambiguous(103) A\n",
            AnalyzeNamespace());
}

// Scope of using alias directive is limited into namespace body.
TEST_F(NamespaceAnalyzerTest, AliasErrorScope) {
  Prepare(
      "namespace N1.N2 { class A {} }"
      "namespace N3 { using R = N1.N2; }"
      "namespace N3 { class B : R.A {} }");  // Error: R unknown
  EXPECT_EQ("NameResolution.Name.NotResolved(88) R\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, AliasErrorScopeHide) {
  Prepare(
      "using R = N1.N2;"
      "namespace N1.N2 { class A {} }"
      "namespace N3 {"
      "  class R {}"        // Class R hides alias R in toplevel.
      "  class B : R.A {}"  // Error: R has no member A.
      "}");
  EXPECT_EQ("NameResolution.Name.NotResolved(86) A\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, AliasErrorScopeResolution) {
  Prepare(
      "namespace N1.N2 {}"
      "namespace N3 {"
      "  using R1 = N1;"
      "  using R2 = N1.N2;"
      "  using R3 = R1.N2;"  // Error: R1 is unknown.
      "}");
  EXPECT_EQ("NameResolution.Name.NotResolved(80) R1\n",
            AnalyzeNamespace());
}

//////////////////////////////////////////////////////////////////////
//
// Class resolution
//
TEST_F(NamespaceAnalyzerTest, ClassBasic) {
  Prepare("class A : C {} class B : A {} class C {}");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("C", GetBaseClasses("A"));
  EXPECT_EQ("A", GetBaseClasses("B"));
}

TEST_F(NamespaceAnalyzerTest, ClassNested) {
  Prepare("class A { class B {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("System.Object", GetBaseClasses("A"));
  EXPECT_EQ("System.Object", GetBaseClasses("A.B"));
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseNotInterface) {
  Prepare(
      "class A : B, C {}"  // C must be an interface.
      "class B {}"
      "class C {}");
  EXPECT_EQ("NameResolution.Name.NotInterface(13) C\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseClassIsInterface) {
  Prepare(
      "class A : B, C {}"
      "interface B {}"
      "class C {}");
  EXPECT_EQ("NameResolution.Name.NotInterface(13) C\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseClassIsStruct) {
  Prepare(
      "class A : B {}"
      "struct B {}");
  EXPECT_EQ("NameResolution.Name.NeitherClassNorInterface(10) B\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseClassIsNamespace) {
  Prepare("namespace N1 { class A : N1 {} }");
  EXPECT_EQ("NameResolution.Name.NeitherClassNorInterface(25) N1\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorCircularlyDependency) {
  Prepare(
      "class A : B {}"
      "class B : C {}"
      "class C : A {}");
  EXPECT_EQ(
      "NameResolution.Name.Cycle(6) A C\n"
      "NameResolution.Name.Cycle(20) B A\n"
      "NameResolution.Name.Cycle(34) C B\n",
      AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorCircularlyDependencyNested) {
  Prepare(
      "class A : B.C {}"     // A depends on B and C.
      "class B : A {"        // B depends on A.
      "  public class C {}"  // C depends on B.
      "}");
  EXPECT_EQ(
      "NameResolution.Name.Cycle(6) A B\n"
      "NameResolution.Name.Cycle(22) B C\n"
      "NameResolution.Name.Cycle(44) C A\n",
      AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorNestedDependency) {
  Prepare("class A { class B : A {} }");
  EXPECT_EQ("NameResolution.Class.Containing(20) A B\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorSelfReference) {
  Prepare("class A : A {}");
  EXPECT_EQ("NameResolution.Name.Cycle(6) A A\n",
            AnalyzeNamespace());
}

//////////////////////////////////////////////////////////////////////
//
// Predefined types
//
TEST_F(NamespaceAnalyzerTest, PredefinedTypes) {
  Prepare("class A {}");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("", GetBaseClasses("System.Object"));
  EXPECT_EQ("System.Object", GetBaseClasses("System.Value"));
  EXPECT_EQ("System.Value", GetBaseClasses("System.Bool"));
  EXPECT_EQ("System.Value", GetBaseClasses("System.Void"));
}

}  // namespace
}  // namespace compiler
}  // namespace elang
<commit_msg>elang/compiler/analyze: Introduce |struct| and |interface| test case to |NamespaceAnalyzer|.<commit_after>// Copyright 2014 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "elang/compiler/testing/compiler_test.h"

namespace elang {
namespace compiler {
namespace {

//////////////////////////////////////////////////////////////////////
//
// NamespaceAnalyzerTest
//
class NamespaceAnalyzerTest : public testing::CompilerTest {
 protected:
  NamespaceAnalyzerTest() = default;
  ~NamespaceAnalyzerTest() override = default;

 private:
  DISALLOW_COPY_AND_ASSIGN(NamespaceAnalyzerTest);
};

//////////////////////////////////////////////////////////////////////
//
// Alias resolution
//
TEST_F(NamespaceAnalyzerTest, AliasBasic) {
  Prepare(
      "namespace N1.N2 { class A {} }"
      "namespace N3 { using C = N1.N2.A; class B : C {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.B"));
}

// Same as |AliasBasic|, but order of declaration is different.
TEST_F(NamespaceAnalyzerTest, AliasLayout) {
  Prepare(
      "namespace N3 { using C = N1.N2.A; class B : C {} }"
      "namespace N1.N2 { class A {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.B"));
}

TEST_F(NamespaceAnalyzerTest, AliasExtent) {
  Prepare(
      "using R = N1.N2;"
      "namespace N1.N2 { class A {} }"
      "namespace N3 { class B : R.A {} }"
      "namespace N3 { class C : R.A {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.B"));
  EXPECT_EQ("N1.N2.A", GetBaseClasses("N3.C"));
}

TEST_F(NamespaceAnalyzerTest, AliasToAlias) {
  Prepare(
      "using R1 = A.B;"
      "class A { class B { class C {} } }"
      "namespace N1 {"
      "  using R2 = R1;"
      "  class D : R2.C {}"
      "}");
  ASSERT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("A.B.C", GetBaseClasses("N1.D"));
}

TEST_F(NamespaceAnalyzerTest, AliasToAliasDeep) {
  Prepare(
      "using R1 = N1.N2.A.B;"
      "namespace N1 {"
      "  using R2 = R1;"
      "  class D : R2.C {}"
      "  namespace N2 {"
      "     class A { class B { class C {} } }"
      "  }"
      "}");
  ASSERT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("N1.N2.A.B.C", GetBaseClasses("N1.D"));
}

// Note: MS C# compiler doesn't report error if alias A isn't used.
TEST_F(NamespaceAnalyzerTest, AliasErrorAmbiguous) {
  Prepare(
      "namespace N1.N2 { class A {} }"
      "namespace N3 { class A {} }"
      "namespace N3 {"
      "  using A = N1.N2.A;"
      "  class B : A {}"  // A can be N1.N2.A or N3.A.
      "}");
  EXPECT_EQ("NameResolution.Name.Ambiguous(103) A\n", AnalyzeNamespace());
}

// Scope of using alias directive is limited into namespace body.
TEST_F(NamespaceAnalyzerTest, AliasErrorScope) {
  Prepare(
      "namespace N1.N2 { class A {} }"
      "namespace N3 { using R = N1.N2; }"
      "namespace N3 { class B : R.A {} }");  // Error: R unknown
  EXPECT_EQ("NameResolution.Name.NotResolved(88) R\n", AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, AliasErrorScopeHide) {
  Prepare(
      "using R = N1.N2;"
      "namespace N1.N2 { class A {} }"
      "namespace N3 {"
      "  class R {}"        // Class R hides alias R in toplevel.
      "  class B : R.A {}"  // Error: R has no member A.
      "}");
  EXPECT_EQ("NameResolution.Name.NotResolved(86) A\n", AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, AliasErrorScopeResolution) {
  Prepare(
      "namespace N1.N2 {}"
      "namespace N3 {"
      "  using R1 = N1;"
      "  using R2 = N1.N2;"
      "  using R3 = R1.N2;"  // Error: R1 is unknown.
      "}");
  EXPECT_EQ("NameResolution.Name.NotResolved(80) R1\n", AnalyzeNamespace());
}

//////////////////////////////////////////////////////////////////////
//
// Class resolution
//
TEST_F(NamespaceAnalyzerTest, ClassBasic) {
  Prepare("class A : C {} class B : A {} class C {}");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("C", GetBaseClasses("A"));
  EXPECT_EQ("A", GetBaseClasses("B"));
}

TEST_F(NamespaceAnalyzerTest, ClassNested) {
  Prepare("class A { class B {} }");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("System.Object", GetBaseClasses("A"));
  EXPECT_EQ("System.Object", GetBaseClasses("A.B"));
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseNotInterface) {
  Prepare(
      "class A : B, C {}"  // C must be an interface.
      "class B {}"
      "class C {}");
  EXPECT_EQ("NameResolution.Name.NotInterface(13) C\n", AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseStruct) {
  Prepare(
      "class A : S {}"
      "struct S {}");
  EXPECT_EQ("NameResolution.Name.NeitherClassNorInterface(10) S\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseClassIsInterface) {
  Prepare(
      "class A : B, C {}"
      "interface B {}"
      "class C {}");
  EXPECT_EQ("NameResolution.Name.NotInterface(13) C\n", AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseClassIsStruct) {
  Prepare(
      "class A : B {}"
      "struct B {}");
  EXPECT_EQ("NameResolution.Name.NeitherClassNorInterface(10) B\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorBaseClassIsNamespace) {
  Prepare("namespace N1 { class A : N1 {} }");
  EXPECT_EQ("NameResolution.Name.NeitherClassNorInterface(25) N1\n",
            AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorCircularlyDependency) {
  Prepare(
      "class A : B {}"
      "class B : C {}"
      "class C : A {}");
  EXPECT_EQ(
      "NameResolution.Name.Cycle(6) A C\n"
      "NameResolution.Name.Cycle(20) B A\n"
      "NameResolution.Name.Cycle(34) C B\n",
      AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorCircularlyDependencyNested) {
  Prepare(
      "class A : B.C {}"     // A depends on B and C.
      "class B : A {"        // B depends on A.
      "  public class C {}"  // C depends on B.
      "}");
  EXPECT_EQ(
      "NameResolution.Name.Cycle(6) A B\n"
      "NameResolution.Name.Cycle(22) B C\n"
      "NameResolution.Name.Cycle(44) C A\n",
      AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorNestedDependency) {
  Prepare("class A { class B : A {} }");
  EXPECT_EQ("NameResolution.Class.Containing(20) A B\n", AnalyzeNamespace());
}

TEST_F(NamespaceAnalyzerTest, ClassErrorSelfReference) {
  Prepare("class A : A {}");
  EXPECT_EQ("NameResolution.Name.Cycle(6) A A\n", AnalyzeNamespace());
}

//////////////////////////////////////////////////////////////////////
//
// Interface
//
TEST_F(NamespaceAnalyzerTest, InterfaceBasic) {
  Prepare(
      "interface I {}"
      "interface J {}"
      "interface K : I, J {}");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("I, J", GetBaseClasses("K"));
}

TEST_F(NamespaceAnalyzerTest, InterfaceErrorBaseClass) {
  Prepare(
      "class A {}"
      "interface I : A {}");
  EXPECT_EQ("NameResolution.Name.NotInterface(24) A\n", AnalyzeNamespace());
}

//////////////////////////////////////////////////////////////////////
//
// Predefined types
//
TEST_F(NamespaceAnalyzerTest, PredefinedTypes) {
  Prepare("class A {}");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("", GetBaseClasses("System.Object"));
  EXPECT_EQ("System.Object", GetBaseClasses("System.Value"));
  EXPECT_EQ("System.Value", GetBaseClasses("System.Bool"));
  EXPECT_EQ("System.Value", GetBaseClasses("System.Void"));
}

//////////////////////////////////////////////////////////////////////
//
// Struct
//
TEST_F(NamespaceAnalyzerTest, StructBasic) {
  Prepare(
      "interface I {}"
      "interface J {}"
      "struct S : I, J {}");
  EXPECT_EQ("", AnalyzeNamespace());
  EXPECT_EQ("System.Value, I, J", GetBaseClasses("S"));
}

TEST_F(NamespaceAnalyzerTest, StructErrorBaseClass) {
  Prepare(
      "class A {}"
      "struct S : A {}");
  EXPECT_EQ("NameResolution.Name.NotInterface(21) A\n", AnalyzeNamespace());
}

}  // namespace
}  // namespace compiler
}  // namespace elang
<|endoftext|>