<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2011 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#include "headers.h"
#include "irc.h"
#include "net.h"
#include "strlcpy.h"

using namespace std;
using namespace boost;

int nGotIRCAddresses = 0;
bool fGotExternalIP = false;

void ThreadIRCSeed2(void* parg);

#pragma pack(push, 1)
struct ircaddr
{
    int ip;
    short port;
};
#pragma pack(pop)

string EncodeAddress(const CAddress& addr)
{
    struct ircaddr tmp;
    tmp.ip    = addr.ip;
    tmp.port  = addr.port;

    vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
    return string("u") + EncodeBase58Check(vch);
}

bool DecodeAddress(string str, CAddress& addr)
{
    vector<unsigned char> vch;
    if (!DecodeBase58Check(str.substr(1), vch))
        return false;

    struct ircaddr tmp;
    if (vch.size() != sizeof(tmp))
        return false;
    memcpy(&tmp, &vch[0], sizeof(tmp));

    addr = CAddress(tmp.ip, ntohs(tmp.port), NODE_NETWORK);
    return true;
}

static bool Send(SOCKET hSocket, const char* pszSend)
{
    if (strstr(pszSend, "PONG") != pszSend)
        printf("IRC SENDING: %s\n", pszSend);
    const char* psz = pszSend;
    const char* pszEnd = psz + strlen(psz);
    while (psz < pszEnd)
    {
        int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
        if (ret < 0)
            return false;
        psz += ret;
    }
    return true;
}

bool RecvLine(SOCKET hSocket, string& strLine)
{
    strLine = "";
    loop
    {
        char c;
        int nBytes = recv(hSocket, &c, 1, 0);
        if (nBytes > 0)
        {
            if (c == '\n')
                continue;
            if (c == '\r')
                return true;
            strLine += c;
            if (strLine.size() >= 9000)
                return true;
        }
        else if (nBytes <= 0)
        {
            if (fShutdown)
                return false;
            if (nBytes < 0)
            {
                int nErr = WSAGetLastError();
                if (nErr == WSAEMSGSIZE)
                    continue;
                if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
                {
                    Sleep(10);
                    continue;
                }
            }
            if (!strLine.empty())
                return true;
            if (nBytes == 0)
            {
                // socket closed
                printf("IRC socket closed\n");
                return false;
            }
            else
            {
                // socket error
                int nErr = WSAGetLastError();
                printf("IRC recv failed: %d\n", nErr);
                return false;
            }
        }
    }
}

bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
    loop
    {
        bool fRet = RecvLine(hSocket, strLine);
        if (fRet)
        {
            if (fShutdown)
                return false;
            vector<string> vWords;
            ParseString(strLine, ' ', vWords);
            if (vWords.size() >= 1 && vWords[0] == "PING")
            {
                strLine[1] = 'O';
                strLine += '\r';
                Send(hSocket, strLine.c_str());
                continue;
            }
        }
        return fRet;
    }
}

int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
    loop
    {
        string strLine;
        strLine.reserve(10000);
        if (!RecvLineIRC(hSocket, strLine))
            return 0;
        printf("IRC %s\n", strLine.c_str());
        if (psz1 && strLine.find(psz1) != -1)
            return 1;
        if (psz2 && strLine.find(psz2) != -1)
            return 2;
        if (psz3 && strLine.find(psz3) != -1)
            return 3;
        if (psz4 && strLine.find(psz4) != -1)
            return 4;
    }
}

bool Wait(int nSeconds)
{
    if (fShutdown)
        return false;
    printf("IRC waiting %d seconds to reconnect\n", nSeconds);
    for (int i = 0; i < nSeconds; i++)
    {
        if (fShutdown)
            return false;
        Sleep(1000);
    }
    return true;
}

bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
    strRet.clear();
    loop
    {
        string strLine;
        if (!RecvLineIRC(hSocket, strLine))
            return false;

        vector<string> vWords;
        ParseString(strLine, ' ', vWords);
        if (vWords.size() < 2)
            continue;

        if (vWords[1] == psz1)
        {
            printf("IRC %s\n", strLine.c_str());
            strRet = strLine;
            return true;
        }
    }
}

bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet)
{
    Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());

    string strLine;
    if (!RecvCodeLine(hSocket, "302", strLine))
        return false;

    vector<string> vWords;
    ParseString(strLine, ' ', vWords);
    if (vWords.size() < 4)
        return false;

    string str = vWords[3];
    if (str.rfind("@") == string::npos)
        return false;
    string strHost = str.substr(str.rfind("@")+1);

    // Hybrid IRC used by lfnet always returns IP when you userhost yourself,
    // but in case another IRC is ever used this should work.
    printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
    if (fUseProxy)
        return false;
    CAddress addr(strHost, 0, true);
    if (!addr.IsValid())
        return false;
    ipRet = addr.ip;

    return true;
}

void ThreadIRCSeed(void* parg)
{
    IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
    try
    {
        ThreadIRCSeed2(parg);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "ThreadIRCSeed()");
    } catch (...) {
        PrintExceptionContinue(NULL, "ThreadIRCSeed()");
    }
    printf("ThreadIRCSeed exiting\n");
}

void ThreadIRCSeed2(void* parg)
{
    /* Dont advertise on IRC if we don't allow incoming connections */
    if (mapArgs.count("-connect") || fNoListen)
        return;

    if (GetBoolArg("-noirc"))
        return;
    printf("ThreadIRCSeed started\n");
    int nErrorWait = 10;
    int nRetryWait = 10;
    bool fNameInUse = false;
    bool fTOR = (fUseProxy && addrProxy.port == htons(9050));

    while (!fShutdown)
    {
        CAddress addrConnect("213.92.8.4", 6667); // chat.freenode.net
        //CAddress addrConnect("92.243.23.21", 6667); // irc.lfnet.org
        if (!fTOR)
        {
            //struct hostent* phostent = gethostbyname("chat.freenode.net");
            //CAddress addrIRC("irc.lfnet.org", 6667, true);
			CAddress addrIRC("chat.freenode.net", 6667, true);
            if (addrIRC.IsValid())
                addrConnect = addrIRC;
        }

        SOCKET hSocket;
        if (!ConnectSocket(addrConnect, hSocket))
        {
            printf("IRC connect failed\n");
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }

        if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
        {
            closesocket(hSocket);
            hSocket = INVALID_SOCKET;
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }

        string strMyName;
        if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse)
            strMyName = EncodeAddress(addrLocalHost);
        else
            strMyName = strprintf("x%u", GetRand(1000000000));

        Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
        Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());

        int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
        if (nRet != 1)
        {
            closesocket(hSocket);
            hSocket = INVALID_SOCKET;
            if (nRet == 2)
            {
                printf("IRC name already in use\n");
                fNameInUse = true;
                Wait(10);
                continue;
            }
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }
        Sleep(500);

        // Get our external IP from the IRC server and re-nick before joining the channel
        CAddress addrFromIRC;
        if (GetIPFromIRC(hSocket, strMyName, addrFromIRC.ip))
        {
            printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToStringIP().c_str());
            if (!fUseProxy && addrFromIRC.IsRoutable())
            {
                // IRC lets you to re-nick
                fGotExternalIP = true;
                addrLocalHost.ip = addrFromIRC.ip;
                strMyName = EncodeAddress(addrLocalHost);
                Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
            }
        }

        if (fTestNet) {
            Send(hSocket, "JOIN #i0coinTEST\r");
            Send(hSocket, "WHO #i0coinTEST\r");
        } else {
            // randomly join #i0coin00-#i0coin99 --> will be implemented when i0coin grow
            int channel_number = 0;//GetRandInt(100);
            Send(hSocket, strprintf("JOIN #i0coin%02d\r", channel_number).c_str());
            Send(hSocket, strprintf("WHO #i0coin%02d\r", channel_number).c_str());
        }

        int64 nStart = GetTime();
        string strLine;
        strLine.reserve(10000);
        while (!fShutdown && RecvLineIRC(hSocket, strLine))
        {
            if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
                continue;

            vector<string> vWords;
            ParseString(strLine, ' ', vWords);
            if (vWords.size() < 2)
                continue;

            char pszName[10000];
            pszName[0] = '\0';

            if (vWords[1] == "352" && vWords.size() >= 8)
            {
                // index 7 is limited to 16 characters
                // could get full length name at index 10, but would be different from join messages
                strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
                printf("IRC got who\n");
            }

            if (vWords[1] == "JOIN" && vWords[0].size() > 1)
            {
                // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
                strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
                if (strchr(pszName, '!'))
                    *strchr(pszName, '!') = '\0';
                printf("IRC got join\n");
            }

            if (pszName[0] == 'u')
            {
                CAddress addr;
                if (DecodeAddress(pszName, addr))
                {
                    addr.nTime = GetAdjustedTime();
                    if (AddAddress(addr, 51 * 60))
                        printf("IRC got new address: %s\n", addr.ToString().c_str());
                    nGotIRCAddresses++;
                }
                else
                {
                    printf("IRC decode failed\n");
                }
            }
        }
        closesocket(hSocket);
        hSocket = INVALID_SOCKET;

        // IRC usually blocks TOR, so only try once
        if (fTOR)
            return;

        if (GetTime() - nStart > 20 * 60)
        {
            nErrorWait /= 3;
            nRetryWait /= 3;
        }

        nRetryWait = nRetryWait * 11 / 10;
        if (!Wait(nRetryWait += 60))
            return;
    }
}

#ifdef TEST
int main(int argc, char *argv[])
{
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
    {
        printf("Error at WSAStartup()\n");
        return false;
    }

    ThreadIRCSeed(NULL);

    WSACleanup();
    return 0;
}
#endif
<commit_msg>Change IRC to use lfnet instead of freenode<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2011 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#include "headers.h"
#include "irc.h"
#include "net.h"
#include "strlcpy.h"

using namespace std;
using namespace boost;

int nGotIRCAddresses = 0;
bool fGotExternalIP = false;

void ThreadIRCSeed2(void* parg);

#pragma pack(push, 1)
struct ircaddr
{
    int ip;
    short port;
};
#pragma pack(pop)

string EncodeAddress(const CAddress& addr)
{
    struct ircaddr tmp;
    tmp.ip    = addr.ip;
    tmp.port  = addr.port;

    vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
    return string("u") + EncodeBase58Check(vch);
}

bool DecodeAddress(string str, CAddress& addr)
{
    vector<unsigned char> vch;
    if (!DecodeBase58Check(str.substr(1), vch))
        return false;

    struct ircaddr tmp;
    if (vch.size() != sizeof(tmp))
        return false;
    memcpy(&tmp, &vch[0], sizeof(tmp));

    addr = CAddress(tmp.ip, ntohs(tmp.port), NODE_NETWORK);
    return true;
}

static bool Send(SOCKET hSocket, const char* pszSend)
{
    if (strstr(pszSend, "PONG") != pszSend)
        printf("IRC SENDING: %s\n", pszSend);
    const char* psz = pszSend;
    const char* pszEnd = psz + strlen(psz);
    while (psz < pszEnd)
    {
        int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
        if (ret < 0)
            return false;
        psz += ret;
    }
    return true;
}

bool RecvLine(SOCKET hSocket, string& strLine)
{
    strLine = "";
    loop
    {
        char c;
        int nBytes = recv(hSocket, &c, 1, 0);
        if (nBytes > 0)
        {
            if (c == '\n')
                continue;
            if (c == '\r')
                return true;
            strLine += c;
            if (strLine.size() >= 9000)
                return true;
        }
        else if (nBytes <= 0)
        {
            if (fShutdown)
                return false;
            if (nBytes < 0)
            {
                int nErr = WSAGetLastError();
                if (nErr == WSAEMSGSIZE)
                    continue;
                if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
                {
                    Sleep(10);
                    continue;
                }
            }
            if (!strLine.empty())
                return true;
            if (nBytes == 0)
            {
                // socket closed
                printf("IRC socket closed\n");
                return false;
            }
            else
            {
                // socket error
                int nErr = WSAGetLastError();
                printf("IRC recv failed: %d\n", nErr);
                return false;
            }
        }
    }
}

bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
    loop
    {
        bool fRet = RecvLine(hSocket, strLine);
        if (fRet)
        {
            if (fShutdown)
                return false;
            vector<string> vWords;
            ParseString(strLine, ' ', vWords);
            if (vWords.size() >= 1 && vWords[0] == "PING")
            {
                strLine[1] = 'O';
                strLine += '\r';
                Send(hSocket, strLine.c_str());
                continue;
            }
        }
        return fRet;
    }
}

int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
    loop
    {
        string strLine;
        strLine.reserve(10000);
        if (!RecvLineIRC(hSocket, strLine))
            return 0;
        printf("IRC %s\n", strLine.c_str());
        if (psz1 && strLine.find(psz1) != -1)
            return 1;
        if (psz2 && strLine.find(psz2) != -1)
            return 2;
        if (psz3 && strLine.find(psz3) != -1)
            return 3;
        if (psz4 && strLine.find(psz4) != -1)
            return 4;
    }
}

bool Wait(int nSeconds)
{
    if (fShutdown)
        return false;
    printf("IRC waiting %d seconds to reconnect\n", nSeconds);
    for (int i = 0; i < nSeconds; i++)
    {
        if (fShutdown)
            return false;
        Sleep(1000);
    }
    return true;
}

bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
    strRet.clear();
    loop
    {
        string strLine;
        if (!RecvLineIRC(hSocket, strLine))
            return false;

        vector<string> vWords;
        ParseString(strLine, ' ', vWords);
        if (vWords.size() < 2)
            continue;

        if (vWords[1] == psz1)
        {
            printf("IRC %s\n", strLine.c_str());
            strRet = strLine;
            return true;
        }
    }
}

bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet)
{
    Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());

    string strLine;
    if (!RecvCodeLine(hSocket, "302", strLine))
        return false;

    vector<string> vWords;
    ParseString(strLine, ' ', vWords);
    if (vWords.size() < 4)
        return false;

    string str = vWords[3];
    if (str.rfind("@") == string::npos)
        return false;
    string strHost = str.substr(str.rfind("@")+1);

    // Hybrid IRC used by lfnet always returns IP when you userhost yourself,
    // but in case another IRC is ever used this should work.
    printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
    if (fUseProxy)
        return false;
    CAddress addr(strHost, 0, true);
    if (!addr.IsValid())
        return false;
    ipRet = addr.ip;

    return true;
}

void ThreadIRCSeed(void* parg)
{
    IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
    try
    {
        ThreadIRCSeed2(parg);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "ThreadIRCSeed()");
    } catch (...) {
        PrintExceptionContinue(NULL, "ThreadIRCSeed()");
    }
    printf("ThreadIRCSeed exiting\n");
}

void ThreadIRCSeed2(void* parg)
{
    /* Dont advertise on IRC if we don't allow incoming connections */
    if (mapArgs.count("-connect") || fNoListen)
        return;

    if (GetBoolArg("-noirc"))
        return;
    printf("ThreadIRCSeed started\n");
    int nErrorWait = 10;
    int nRetryWait = 10;
    bool fNameInUse = false;
    bool fTOR = (fUseProxy && addrProxy.port == htons(9050));

    while (!fShutdown)
    {
        //CAddress addrConnect("213.92.8.4", 6667); // chat.freenode.net
        CAddress addrConnect("92.243.23.21", 6667); // irc.lfnet.org
        if (!fTOR)
        {
            //struct hostent* phostent = gethostbyname("chat.freenode.net");
            CAddress addrIRC("irc.lfnet.org", 6667, true);
            //CAddress addrIRC("chat.freenode.net", 6667, true);
            if (addrIRC.IsValid())
                addrConnect = addrIRC;
        }

        SOCKET hSocket;
        if (!ConnectSocket(addrConnect, hSocket))
        {
            printf("IRC connect failed\n");
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }

        if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
        {
            closesocket(hSocket);
            hSocket = INVALID_SOCKET;
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }

        string strMyName;
        if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse)
            strMyName = EncodeAddress(addrLocalHost);
        else
            strMyName = strprintf("x%u", GetRand(1000000000));

        Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
        Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());

        int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
        if (nRet != 1)
        {
            closesocket(hSocket);
            hSocket = INVALID_SOCKET;
            if (nRet == 2)
            {
                printf("IRC name already in use\n");
                fNameInUse = true;
                Wait(10);
                continue;
            }
            nErrorWait = nErrorWait * 11 / 10;
            if (Wait(nErrorWait += 60))
                continue;
            else
                return;
        }
        Sleep(500);

        // Get our external IP from the IRC server and re-nick before joining the channel
        CAddress addrFromIRC;
        if (GetIPFromIRC(hSocket, strMyName, addrFromIRC.ip))
        {
            printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToStringIP().c_str());
            if (!fUseProxy && addrFromIRC.IsRoutable())
            {
                // IRC lets you to re-nick
                fGotExternalIP = true;
                addrLocalHost.ip = addrFromIRC.ip;
                strMyName = EncodeAddress(addrLocalHost);
                Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
            }
        }

        if (fTestNet) {
            Send(hSocket, "JOIN #i0coinTEST\r");
            Send(hSocket, "WHO #i0coinTEST\r");
        } else {
            // randomly join #i0coin00-#i0coin99 --> will be implemented when i0coin grow
            int channel_number = 0;//GetRandInt(100);
            Send(hSocket, strprintf("JOIN #i0coin%02d\r", channel_number).c_str());
            Send(hSocket, strprintf("WHO #i0coin%02d\r", channel_number).c_str());
        }

        int64 nStart = GetTime();
        string strLine;
        strLine.reserve(10000);
        while (!fShutdown && RecvLineIRC(hSocket, strLine))
        {
            if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
                continue;

            vector<string> vWords;
            ParseString(strLine, ' ', vWords);
            if (vWords.size() < 2)
                continue;

            char pszName[10000];
            pszName[0] = '\0';

            if (vWords[1] == "352" && vWords.size() >= 8)
            {
                // index 7 is limited to 16 characters
                // could get full length name at index 10, but would be different from join messages
                strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
                printf("IRC got who\n");
            }

            if (vWords[1] == "JOIN" && vWords[0].size() > 1)
            {
                // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
                strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
                if (strchr(pszName, '!'))
                    *strchr(pszName, '!') = '\0';
                printf("IRC got join\n");
            }

            if (pszName[0] == 'u')
            {
                CAddress addr;
                if (DecodeAddress(pszName, addr))
                {
                    addr.nTime = GetAdjustedTime();
                    if (AddAddress(addr, 51 * 60))
                        printf("IRC got new address: %s\n", addr.ToString().c_str());
                    nGotIRCAddresses++;
                }
                else
                {
                    printf("IRC decode failed\n");
                }
            }
        }
        closesocket(hSocket);
        hSocket = INVALID_SOCKET;

        // IRC usually blocks TOR, so only try once
        if (fTOR)
            return;

        if (GetTime() - nStart > 20 * 60)
        {
            nErrorWait /= 3;
            nRetryWait /= 3;
        }

        nRetryWait = nRetryWait * 11 / 10;
        if (!Wait(nRetryWait += 60))
            return;
    }
}

#ifdef TEST
int main(int argc, char *argv[])
{
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
    {
        printf("Error at WSAStartup()\n");
        return false;
    }

    ThreadIRCSeed(NULL);

    WSACleanup();
    return 0;
}
#endif
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX デバイス選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#include "common/device.hpp"

#include "RX600/lvda.hpp"
#include "RX600/bus.hpp"

#if defined(SIG_RX24T)
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_in.hpp"
#include "RX24T/da.hpp"
#include "RX600/cmpc.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX621) || defined(SIG_RX62N)
#include "RX62x/system.hpp"

#elif defined(SIG_RX64M) || defined(SIG_RX71M)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/elc.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/ppg.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_in.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/eptpc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/usba.hpp"
#include "RX600/scif.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/mmcif.hpp"
#include "RX600/pdc.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX65N)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/elc.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/ppg.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_in.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/mmcif.hpp"
#include "RX600/pdc.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX66T)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/elc.hpp"
#include "RX600/mpc.hpp"
#include "RX66T/hrpwm.hpp"
#include "RX600/can.hpp"
#include "RX600/r12da.hpp"
#include "RX600/usb.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/cmpc.hpp"

#else
#  error "renesas.hpp: Requires SIG_XXX to be defined"
#endif

// RX マイコン共通ペリフェラル
#include "RX600/cac.hpp"
#include "RX600/dtc.hpp"
#include "RX600/port.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/poe3.hpp"
#include "RX600/gpt.hpp"
#include "RX600/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX600/iwdt.hpp"
#include "RX600/sci.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/crc.hpp"
#include "RX600/mpu.hpp"
#include "RX600/doc.hpp"
<commit_msg>update: poeg for RX66T<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX デバイス選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#include "common/device.hpp"

#include "RX600/lvda.hpp"
#include "RX600/bus.hpp"

#if defined(SIG_RX24T)
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_in.hpp"
#include "RX24T/da.hpp"
#include "RX600/cmpc.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX621) || defined(SIG_RX62N)
#include "RX62x/system.hpp"

#elif defined(SIG_RX64M) || defined(SIG_RX71M)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/elc.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/ppg.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_in.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/eptpc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/usba.hpp"
#include "RX600/scif.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/mmcif.hpp"
#include "RX600/pdc.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX65N)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/elc.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/ppg.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_in.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/mmcif.hpp"
#include "RX600/pdc.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX66T)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/elc.hpp"
#include "RX600/mpc.hpp"
#include "RX66T/hrpwm.hpp"
#include "RX66T/poeg.hpp"
#include "RX600/can.hpp"
#include "RX600/r12da.hpp"
#include "RX600/usb.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/cmpc.hpp"

#else
#  error "renesas.hpp: Requires SIG_XXX to be defined"
#endif

// RX マイコン共通ペリフェラル
#include "RX600/cac.hpp"
#include "RX600/dtc.hpp"
#include "RX600/port.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/poe3.hpp"
#include "RX600/gpt.hpp"
#include "RX600/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX600/iwdt.hpp"
#include "RX600/sci.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/crc.hpp"
#include "RX600/mpu.hpp"
#include "RX600/doc.hpp"
<|endoftext|>


<commit_before>#include "juci.h"
#include "window.h"
#include "notebook.h"
#include "directories.h"
#include "menu.h"
#include "config.h"
#include "logging.h"

int Application::on_command_line(const Glib::RefPtr<Gio::ApplicationCommandLine> &cmd) {
  Glib::set_prgname("juci");
  Glib::OptionContext ctx("[PATH ...]");
  Glib::OptionGroup gtk_group(gtk_get_option_group(true));
  ctx.add_group(gtk_group);
  int argc;
  char **argv = cmd->get_arguments(argc);
  ctx.parse(argc, argv);
  if(argc>=2) {
    for(int c=1;c<argc;c++) {
      boost::filesystem::path p(argv[c]);
      if(boost::filesystem::exists(p)) {
        p=boost::filesystem::canonical(p);
        if(boost::filesystem::is_regular_file(p))
          files.emplace_back(p);
        else if(boost::filesystem::is_directory(p))
          directories.emplace_back(p);
      }
      else { //Open new file if parent path exists
        auto parent_p=p.parent_path();
        boost::system::error_code ec;
        auto new_p=boost::filesystem::canonical(parent_p, ec);
        if(!ec && boost::filesystem::is_directory(new_p)) {
          new_p/=p.filename();
          files.emplace_back(new_p);
        }
        else
          errors.emplace_back("Error: folder path "+parent_p.string()+" does not exist.\n");
      }
    }
  }
  activate();
  return 0;
}

void Application::on_activate() {
  add_window(Window::get());
  Window::get().show();

  std::string last_current_file;

  if(directories.empty() && files.empty()) {
    try {
      boost::property_tree::ptree pt;
      boost::property_tree::read_json((Config::get().juci_home_path()/"last_session.json").string(), pt);
      auto folder=pt.get<std::string>("folder");
      if(!folder.empty() && boost::filesystem::exists(folder))
        directories.emplace_back(folder);
      for(auto &v: pt.get_child("files")) {
        std::string file=v.second.data();
        if(!file.empty() && boost::filesystem::exists(file))
          files.emplace_back(file);
      }
      last_current_file=pt.get<std::string>("current_file");
      if(!boost::filesystem::exists(last_current_file))
        last_current_file.clear();
    }
    catch(const std::exception &) {}
  }

  bool first_directory=true;
  for(auto &directory: directories) {
    if(first_directory) {
      Directories::get().open(directory);
      first_directory=false;
    }
    else {
      std::string files_in_directory;
      for(auto it=files.begin();it!=files.end();) {
        if(it->generic_string().substr(0, directory.generic_string().size()+1)==directory.generic_string()+'/') {
          files_in_directory+=" "+it->string();
          it=files.erase(it);
        }
        else
          it++;
      }
      std::thread another_juci_app([this, directory, files_in_directory](){
        Terminal::get().async_print("Executing: juci "+directory.string()+files_in_directory+"\n");
        Terminal::get().process("juci "+directory.string()+files_in_directory, "", false);
      });
      another_juci_app.detach();
    }
  }

  for(auto &file: files)
    Notebook::get().open(file);

  for(auto &error: errors)
    Terminal::get().print(error, true);

  if(!last_current_file.empty())
    Notebook::get().open(last_current_file);
}

void Application::on_startup() {
  Gtk::Application::on_startup();

  Menu::get().build();

  if (!Menu::get().juci_menu || !Menu::get().window_menu) {
    std::cerr << "Menu not found." << std::endl;
  }
  else {
    set_app_menu(Menu::get().juci_menu);
    set_menubar(Menu::get().window_menu);
  }
}

Application::Application() : Gtk::Application("no.sout.juci", Gio::APPLICATION_NON_UNIQUE | Gio::APPLICATION_HANDLES_COMMAND_LINE) {
  boost::log::add_common_attributes();
  auto log_dir = Config::get().juci_home_path()/"log"/"juci.log";
  boost::log::add_file_log(boost::log::keywords::file_name = log_dir, boost::log::keywords::auto_flush = true);
  JINFO("Logging initalized");

  Glib::set_application_name("juCi++");

  //Gtk::MessageDialog without buttons caused text to be selected, this prevents that
  Gtk::Settings::get_default()->property_gtk_label_select_on_focus()=false;
}

int main(int argc, char *argv[]) {
  return Application().run(argc, argv);
}
<commit_msg>Additional checks to reopened folder and files at startup<commit_after>#include "juci.h"
#include "window.h"
#include "notebook.h"
#include "directories.h"
#include "menu.h"
#include "config.h"
#include "logging.h"

int Application::on_command_line(const Glib::RefPtr<Gio::ApplicationCommandLine> &cmd) {
  Glib::set_prgname("juci");
  Glib::OptionContext ctx("[PATH ...]");
  Glib::OptionGroup gtk_group(gtk_get_option_group(true));
  ctx.add_group(gtk_group);
  int argc;
  char **argv = cmd->get_arguments(argc);
  ctx.parse(argc, argv);
  if(argc>=2) {
    for(int c=1;c<argc;c++) {
      boost::filesystem::path p(argv[c]);
      if(boost::filesystem::exists(p)) {
        p=boost::filesystem::canonical(p);
        if(boost::filesystem::is_regular_file(p))
          files.emplace_back(p);
        else if(boost::filesystem::is_directory(p))
          directories.emplace_back(p);
      }
      else { //Open new file if parent path exists
        auto parent_p=p.parent_path();
        boost::system::error_code ec;
        auto new_p=boost::filesystem::canonical(parent_p, ec);
        if(!ec && boost::filesystem::is_directory(new_p)) {
          new_p/=p.filename();
          files.emplace_back(new_p);
        }
        else
          errors.emplace_back("Error: folder path "+parent_p.string()+" does not exist.\n");
      }
    }
  }
  activate();
  return 0;
}

void Application::on_activate() {
  add_window(Window::get());
  Window::get().show();

  std::string last_current_file;

  if(directories.empty() && files.empty()) {
    try {
      boost::property_tree::ptree pt;
      boost::property_tree::read_json((Config::get().juci_home_path()/"last_session.json").string(), pt);
      auto folder=pt.get<std::string>("folder");
      if(!folder.empty() && boost::filesystem::exists(folder) && boost::filesystem::is_directory(folder))
        directories.emplace_back(folder);
      for(auto &v: pt.get_child("files")) {
        std::string file=v.second.data();
        if(!file.empty() && boost::filesystem::exists(file) && !boost::filesystem::is_directory(file))
          files.emplace_back(file);
      }
      last_current_file=pt.get<std::string>("current_file");
      if(!boost::filesystem::exists(last_current_file) || boost::filesystem::is_directory(last_current_file))
        last_current_file.clear();
    }
    catch(const std::exception &) {}
  }

  bool first_directory=true;
  for(auto &directory: directories) {
    if(first_directory) {
      Directories::get().open(directory);
      first_directory=false;
    }
    else {
      std::string files_in_directory;
      for(auto it=files.begin();it!=files.end();) {
        if(it->generic_string().substr(0, directory.generic_string().size()+1)==directory.generic_string()+'/') {
          files_in_directory+=" "+it->string();
          it=files.erase(it);
        }
        else
          it++;
      }
      std::thread another_juci_app([this, directory, files_in_directory](){
        Terminal::get().async_print("Executing: juci "+directory.string()+files_in_directory+"\n");
        Terminal::get().process("juci "+directory.string()+files_in_directory, "", false);
      });
      another_juci_app.detach();
    }
  }

  for(auto &file: files)
    Notebook::get().open(file);

  for(auto &error: errors)
    Terminal::get().print(error, true);

  if(!last_current_file.empty())
    Notebook::get().open(last_current_file);
}

void Application::on_startup() {
  Gtk::Application::on_startup();

  Menu::get().build();

  if (!Menu::get().juci_menu || !Menu::get().window_menu) {
    std::cerr << "Menu not found." << std::endl;
  }
  else {
    set_app_menu(Menu::get().juci_menu);
    set_menubar(Menu::get().window_menu);
  }
}

Application::Application() : Gtk::Application("no.sout.juci", Gio::APPLICATION_NON_UNIQUE | Gio::APPLICATION_HANDLES_COMMAND_LINE) {
  boost::log::add_common_attributes();
  auto log_dir = Config::get().juci_home_path()/"log"/"juci.log";
  boost::log::add_file_log(boost::log::keywords::file_name = log_dir, boost::log::keywords::auto_flush = true);
  JINFO("Logging initalized");

  Glib::set_application_name("juCi++");

  //Gtk::MessageDialog without buttons caused text to be selected, this prevents that
  Gtk::Settings::get_default()->property_gtk_label_select_on_focus()=false;
}

int main(int argc, char *argv[]) {
  return Application().run(argc, argv);
}
<|endoftext|>


<commit_before>#ifndef __ERROR_HPP
#define __ERROR_HPP

#include "clay.hpp"
#include "invoketables.hpp"

namespace clay {

void error(llvm::Twine const &msg);
void error(Location const& location, llvm::Twine const &msg);

void warning(llvm::Twine const &msg);

void fmtError(const char *fmt, ...);

template <class T>
inline void error(Pointer<T> context, llvm::Twine const &msg)
{
    if (context->location.ok())
        pushLocation(context->location);
    error(msg);
}

template <class T>
inline void error(T const *context, llvm::Twine const &msg)
{
    error(context->location, msg);
}

void argumentError(size_t index, llvm::StringRef msg);

void arityError(size_t expected, size_t received);
void arityError2(size_t minExpected, size_t received);

template <class T>
inline void arityError(Pointer<T> context, size_t expected, size_t received)
{
    if (context->location.ok())
        pushLocation(context->location);
    arityError(expected, received);
}

template <class T>
inline void arityError2(Pointer<T> context, size_t minExpected, size_t received)
{
    if (context->location.ok())
        pushLocation(context->location);
    arityError2(minExpected, received);
}

void ensureArity(MultiStaticPtr args, size_t size);
void ensureArity(MultiEValuePtr args, size_t size);
void ensureArity(MultiPValuePtr args, size_t size);
void ensureArity(MultiCValuePtr args, size_t size);

template <class T>
inline void ensureArity(T const &args, size_t size)
{
    if (args.size() != size)
        arityError(size, args.size());
}

template <class T>
inline void ensureArity2(T const &args, size_t size, bool hasVarArgs)
{
    if (!hasVarArgs)
        ensureArity(args, size);
    else if (args.size() < size)
        arityError2(size, args.size());
}

void arityMismatchError(size_t leftArity, size_t rightArity, bool hasVarArg);

void typeError(llvm::StringRef expected, TypePtr receivedType);
void typeError(TypePtr expectedType, TypePtr receivedType);

void argumentTypeError(unsigned index,
                       llvm::StringRef expected,
                       TypePtr receivedType);
void argumentTypeError(unsigned index,
                       TypePtr expectedType,
                       TypePtr receivedType);

void indexRangeError(llvm::StringRef kind,
                     size_t value,
                     size_t maxValue);

void argumentIndexRangeError(unsigned index,
                             llvm::StringRef kind,
                             size_t value,
                             size_t maxValue);

extern bool shouldPrintFullMatchErrors;
extern set<pair<string,string> > logMatchSymbols;

void matchBindingError(MatchResultPtr const &result);
void matchFailureLog(MatchFailureError const &err);
void matchFailureError(MatchFailureError const &err);

class CompilerError : std::exception {
};

}

#endif // __ERROR_HPP
<commit_msg>Add noreturn attribute to some functions<commit_after>#ifndef __ERROR_HPP
#define __ERROR_HPP

#include "clay.hpp"
#include "invoketables.hpp"

#if defined(__GNUC__) || defined(__clang__)
#define CLAY_NORETURN __attribute__((noreturn))
#endif

#ifndef CLAY_NORETURN
#define CLAY_NORETURN
#endif

namespace clay {

void error(llvm::Twine const &msg) CLAY_NORETURN;
void error(Location const& location, llvm::Twine const &msg) CLAY_NORETURN;

void warning(llvm::Twine const &msg);

void fmtError(const char *fmt, ...) CLAY_NORETURN;

template <class T>
inline void error(Pointer<T> context, llvm::Twine const &msg) CLAY_NORETURN;
template <class T>
inline void error(Pointer<T> context, llvm::Twine const &msg)
{
    if (context->location.ok())
        pushLocation(context->location);
    error(msg);
}

template <class T>
inline void error(T const *context, llvm::Twine const &msg) CLAY_NORETURN;
template <class T>
inline void error(T const *context, llvm::Twine const &msg)
{
    error(context->location, msg);
}

void argumentError(size_t index, llvm::StringRef msg) CLAY_NORETURN;

void arityError(size_t expected, size_t received) CLAY_NORETURN;
void arityError2(size_t minExpected, size_t received) CLAY_NORETURN;

template <class T>
inline void arityError(Pointer<T> context, size_t expected, size_t received) CLAY_NORETURN;
template <class T>
inline void arityError(Pointer<T> context, size_t expected, size_t received)
{
    if (context->location.ok())
        pushLocation(context->location);
    arityError(expected, received);
}

template <class T>
inline void arityError2(Pointer<T> context, size_t minExpected, size_t received) CLAY_NORETURN;
template <class T>
inline void arityError2(Pointer<T> context, size_t minExpected, size_t received)
{
    if (context->location.ok())
        pushLocation(context->location);
    arityError2(minExpected, received);
}

void ensureArity(MultiStaticPtr args, size_t size);
void ensureArity(MultiEValuePtr args, size_t size);
void ensureArity(MultiPValuePtr args, size_t size);
void ensureArity(MultiCValuePtr args, size_t size);

template <class T>
inline void ensureArity(T const &args, size_t size)
{
    if (args.size() != size)
        arityError(size, args.size());
}

template <class T>
inline void ensureArity2(T const &args, size_t size, bool hasVarArgs)
{
    if (!hasVarArgs)
        ensureArity(args, size);
    else if (args.size() < size)
        arityError2(size, args.size());
}

void arityMismatchError(size_t leftArity, size_t rightArity, bool hasVarArg) CLAY_NORETURN;

void typeError(llvm::StringRef expected, TypePtr receivedType) CLAY_NORETURN;
void typeError(TypePtr expectedType, TypePtr receivedType) CLAY_NORETURN;

void argumentTypeError(unsigned index,
                       llvm::StringRef expected,
                       TypePtr receivedType) CLAY_NORETURN;
void argumentTypeError(unsigned index,
                       TypePtr expectedType,
                       TypePtr receivedType) CLAY_NORETURN;

void indexRangeError(llvm::StringRef kind,
                     size_t value,
                     size_t maxValue) CLAY_NORETURN;

void argumentIndexRangeError(unsigned index,
                             llvm::StringRef kind,
                             size_t value,
                             size_t maxValue) CLAY_NORETURN;

extern bool shouldPrintFullMatchErrors;
extern set<pair<string,string> > logMatchSymbols;

void matchBindingError(MatchResultPtr const &result) CLAY_NORETURN;
void matchFailureLog(MatchFailureError const &err);
void matchFailureError(MatchFailureError const &err) CLAY_NORETURN;

class CompilerError : std::exception {
};

}

#endif // __ERROR_HPP
<|endoftext|>


<commit_before>/*
 * File:  PPPatMatch.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "common/sedna.h"

#include "tr/executor/xqops/PPPatMatch.h"
#include "tr/strings/e_string.h"
#include "tr/strings/strings.h"

void PPPatMatch::cf_choice(void)
{
switch (pmt)
	{
	case pm_match: comp_fun = &PPPatMatch::matches;break;
	case pm_replace: comp_fun = &PPPatMatch::replace;break;
	case pm_tokenize:
		{
			comp_fun = &PPPatMatch::tokenize;break;
			tknzr=NULL;
		}
		break;
	}
}
PPPatMatch::PPPatMatch(dynamic_context *_cxt_,
						 PPOpIn _seq1_, PPOpIn _seq2_,patmatch_type _pmt_):
			PPIterator(_cxt_), seq1(_seq1_) , seq2(_seq2_),pmt(_pmt_),ch_cnt(2),tknzr(NULL)
{
	cf_choice();
}
PPPatMatch::PPPatMatch(dynamic_context *_cxt_,
						 PPOpIn _seq1_, PPOpIn _seq2_,PPOpIn _seq3_,patmatch_type _pmt_):
			PPIterator(_cxt_), seq1(_seq1_) , seq2(_seq2_), seq3(_seq3_),pmt(_pmt_),ch_cnt(3),tknzr(NULL)
{
	cf_choice();
}
PPPatMatch::PPPatMatch(dynamic_context *_cxt_,
						 PPOpIn _seq1_, PPOpIn _seq2_,PPOpIn _seq3_,PPOpIn _seq4_,patmatch_type _pmt_):
			PPIterator(_cxt_), seq1(_seq1_) , seq2(_seq2_), seq3(_seq3_), seq4(_seq4_),pmt(_pmt_),ch_cnt(4),tknzr(NULL)
{
	cf_choice();
}

PPPatMatch::~PPPatMatch()
{
	delete seq1.op;
	seq1.op = NULL;
	delete seq2.op;
	seq2.op = NULL;
	if (ch_cnt>2)
	{
		delete seq3.op;
		seq3.op = NULL;
		if (ch_cnt>3)
		{
			delete seq4.op;
			seq4.op = NULL;
		}
	}
}
void PPPatMatch::open  ()
{
    seq1.op->open();
	seq2.op->open();
	if (ch_cnt>2)
	{
		seq3.op->open();
		if (ch_cnt>3)
		{
			seq4.op->open();
		}
	}
	if (tknzr!=NULL)
	{
		delete tknzr;
		tknzr = NULL;
	}
    first_time = true;
 }
void PPPatMatch::reopen  ()
{
    seq1.op->reopen();
	seq2.op->reopen();
	if (ch_cnt>2)
	{
		seq3.op->reopen();
		if (ch_cnt>3)
		{
			seq4.op->reopen();
		}
	}
	if (tknzr!=NULL)
	{
		delete tknzr;
		tknzr = NULL;
	}
    first_time = true;
 }
void PPPatMatch::close  ()
{
    seq1.op->close();
	seq2.op->close();
	if (ch_cnt>2)
	{
		seq3.op->close();
		if (ch_cnt>3)
		{
			seq4.op->close();
		}
	}
	if (tknzr!=NULL)
	{
		delete tknzr;
		tknzr = NULL;
	}
}
bool PPPatMatch::result(PPIterator* cur, dynamic_context *cxt, void*& r)
{
 return true;
}
PPIterator* PPPatMatch::copy(dynamic_context *_cxt_)
{
	PPPatMatch *res ;
	switch (ch_cnt)
	{
	case 2:
		res = se_new PPPatMatch(_cxt_, seq1,seq2,pmt);
		res->seq1.op = seq1.op->copy(_cxt_);
		res->seq2.op = seq2.op->copy(_cxt_);
		break;
	case 3:
		res = se_new PPPatMatch(_cxt_, seq1,seq2,seq3,pmt);
		res->seq1.op = seq1.op->copy(_cxt_);
		res->seq2.op = seq2.op->copy(_cxt_);
		res->seq3.op = seq3.op->copy(_cxt_);
		break;
	case 4:
		res = se_new PPPatMatch(_cxt_, seq1,seq2,seq3,seq4,pmt);
		res->seq1.op = seq1.op->copy(_cxt_);
		res->seq2.op = seq2.op->copy(_cxt_);
		res->seq3.op = seq3.op->copy(_cxt_);
		res->seq4.op = seq4.op->copy(_cxt_);
		break;
	}
    return res;
}
void PPPatMatch::next  (tuple &t)
{
    //d_printf1("1\n");
    if (first_time)
    {

		first_time = false;
		seq1.op->next(t);

		//Preliminary node analysis
		tuple_cell t1c= t.cells[0];
		if (t.is_eos())t1c.set_eos();
		if (!t1c.is_eos())
		{
			t1c= atomize(t1c);
			if (t1c.get_atomic_type()==xs_untypedAtomic)
				t1c.set_xtype(xs_string);
			else
				if (!is_string_type(t1c.get_atomic_type()))
			throw USER_EXCEPTION(XPTY0004);
		}
		seq2.op->next(t);
		tuple_cell t2c= t.cells[0];
		if (t.is_eos())t2c.set_eos();
		if (!t2c.is_eos())
		{
			t2c= atomize(t2c);
			if (t2c.get_atomic_type()==xs_untypedAtomic)
				t2c.set_xtype(xs_string);
			else
				if (!is_string_type(t2c.get_atomic_type()))
					throw USER_EXCEPTION(XPTY0004);
		}
		tuple_cell t3c;
		tuple_cell t4c;
		if (ch_cnt>2)
		{
			seq3.op->next(t);
			t3c= t.cells[0];
			if (t.is_eos())t3c.set_eos();
			if (!t3c.is_eos())
			{
				t3c= atomize(t3c);
				if (t3c.get_atomic_type()==xs_untypedAtomic)
				t3c.set_xtype(xs_string);
				else
				if (!is_string_type(t3c.get_atomic_type()))
					throw USER_EXCEPTION(XPTY0004);
			}
			if (ch_cnt>3)
			{
				seq4.op->next(t);
				t4c= t.cells[0];
				if (t.is_eos())t4c.set_eos();
				if (!t4c.is_eos())
				{
					t4c= atomize(t4c);
					if (t4c.get_atomic_type()==xs_untypedAtomic)
						t4c.set_xtype(xs_string);
					else
						if (!is_string_type(t4c.get_atomic_type()))
							throw USER_EXCEPTION(XPTY0004);
				}
			}
		}

		//apply function
		//(this->*comp_fun)(t,&t1c,&t2c,&t3c,&t4c);

		if (!t1c.is_eos())
		{
			seq1.op->next(t);
			if (!t.is_eos())
				throw USER_EXCEPTION(XPTY0004);
		}
		if (!t2c.is_eos())
		{
			seq2.op->next(t);
			if (!t.is_eos())
				throw USER_EXCEPTION(XPTY0004);
		}
		if (!t3c.is_eos())
		{
			seq3.op->next(t);
			if (!t.is_eos())
				throw USER_EXCEPTION(XPTY0004);
		}
		if (!t4c.is_eos())
		{
			seq4.op->next(t);
			if (!t.is_eos())
				throw USER_EXCEPTION(XPTY0004);
		}
		//apply function
		(this->*comp_fun)(t,&t1c,&t2c,&t3c,&t4c);
		if (tknzr!=NULL)
		{
			tknzr->get_next_result(t);
			if (t.is_eos())
			{
				delete tknzr;
				tknzr = NULL;
				first_time = true;
			}
		}
	}
    else
    {
		if (tknzr!=NULL)
		{
			tknzr->get_next_result(t);
			if (t.is_eos())
			{
				delete tknzr;
				tknzr = NULL;
				first_time = true;
			}

		}
		else
		{
			first_time = true;
			t.set_eos();
		}
    }
}
void PPPatMatch::tokenize (tuple &t,tuple_cell *t1,tuple_cell *t2,tuple_cell *t3,tuple_cell *t4)
{
	//Preliminary work
	//1.if t1 is empty sequence

	if (t1->is_eos())
	{
		t1 = &EMPTY_STRING_TC;
	}
	//2. light atomization of second parameter
	if (t2->is_eos())
		throw USER_EXCEPTION(XPTY0004);

	tuple_cell tc=tuple_cell::make_sure_light_atomic(*t2);
	tuple_cell tflags = tuple_cell::eos();

	if (t3 != NULL && !t3->is_eos())
		tflags = tuple_cell::make_sure_light_atomic(*t3);

	//3. tokenizer
	tknzr=charset_handler->tokenize( t1, &tc, &tflags);
}
void PPPatMatch::matches (tuple &t,tuple_cell *t1,tuple_cell *t2,tuple_cell *t3,tuple_cell *t4)
{
	//Preliminary work
	//1.if t1 is empty sequence

	if (t1->is_eos())
	{
		t1 = &EMPTY_STRING_TC;
	}
	//2. light atomization of second parameter
	if (t2->is_eos())
		throw USER_EXCEPTION(XPTY0004);

	tuple_cell tc=tuple_cell::make_sure_light_atomic(*t2);
	tuple_cell tflags = tuple_cell::eos();

	if (t3 != NULL && !t3->is_eos())
		tflags = tuple_cell::make_sure_light_atomic(*t3);

	//3. matcher
	charset_handler->matches(t, t1, &tc, &tflags);
}
void PPPatMatch::replace (tuple &t,tuple_cell *t1,tuple_cell *t2,tuple_cell *t3,tuple_cell *t4)
{
	//Preliminary work
	//1.if t1 is empty sequence
	if (t1->is_eos())
	{
		t1 = &EMPTY_STRING_TC;
	}
	//2. light atomization of second parameter
	if (t2->is_eos())
		throw USER_EXCEPTION(XPTY0004);

	tuple_cell tc=tuple_cell::make_sure_light_atomic(*t2);
	tuple_cell tf=tuple_cell::make_sure_light_atomic(*t3);
	tuple_cell tflags = tuple_cell::eos();

	if (t4 != NULL && !t4->is_eos())
		tflags = tuple_cell::make_sure_light_atomic(*t4);

	charset_handler->replace(t, t1, &tc, &tf, &tflags);
}
<commit_msg>PPPatMatch bug fixes && refactoring<commit_after>/*
 * File:  PPPatMatch.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "common/sedna.h"

#include "tr/executor/xqops/PPPatMatch.h"
#include "tr/strings/e_string.h"
#include "tr/strings/strings.h"

void PPPatMatch::cf_choice(void)
{
    switch (pmt)
	{
		case pm_match:    comp_fun = &PPPatMatch::matches; break;
		case pm_replace:  comp_fun = &PPPatMatch::replace; break;
		case pm_tokenize: comp_fun = &PPPatMatch::tokenize; break;
		default: throw USER_EXCEPTION2(SE1003, "Impossible case in pattern matching choise function");
	}
}

static inline const char* get_function_name(patmatch_type pmt)
{
    switch (pmt)
	{
		case pm_match:    return "fn:matches";
		case pm_replace:  return "fn:replace";
		case pm_tokenize: return "fn:tokenize";
		default: throw USER_EXCEPTION2(SE1003, "Impossible case in pattern matching get name function");
	}
}

static inline const char* get_argument_name(int arg)
{
    switch (arg)
	{
		case 1: return "first";
		case 2: return "second";
		case 3: return "third";
		case 4: return "fourth";
		default: throw USER_EXCEPTION2(SE1003, "Impossible case in pattern matching get argument name function");
	}
}

PPPatMatch::PPPatMatch(dynamic_context *_cxt_,
                       PPOpIn _seq1_,
                       PPOpIn _seq2_,
                       patmatch_type _pmt_): PPIterator(_cxt_),
                                             seq1(_seq1_),
                                             seq2(_seq2_),
                                             pmt(_pmt_),
                                             ch_cnt(2),
                                             tknzr(NULL)
{
	cf_choice();
}

PPPatMatch::PPPatMatch(dynamic_context *_cxt_,
                       PPOpIn _seq1_,
                       PPOpIn _seq2_,
                       PPOpIn _seq3_,
                       patmatch_type _pmt_): PPIterator(_cxt_),
                                             seq1(_seq1_),
                                             seq2(_seq2_),
                                             seq3(_seq3_),
                                             pmt(_pmt_),
                                             ch_cnt(3),
                                             tknzr(NULL)
{
	cf_choice();
}

PPPatMatch::PPPatMatch(dynamic_context *_cxt_,
                       PPOpIn _seq1_,
                       PPOpIn _seq2_,
                       PPOpIn _seq3_,
                       PPOpIn _seq4_,
                       patmatch_type _pmt_): PPIterator(_cxt_),
                                             seq1(_seq1_),
                                             seq2(_seq2_),
                                             seq3(_seq3_),
                                             seq4(_seq4_),
                                             pmt(_pmt_),
                                             ch_cnt(4),
                                             tknzr(NULL)
{
	cf_choice();
}

PPPatMatch::~PPPatMatch()
{
	delete seq1.op;
	seq1.op = NULL;

	delete seq2.op;
	seq2.op = NULL;

	if (ch_cnt > 2)
	{
		delete seq3.op;
		seq3.op = NULL;
		if (ch_cnt > 3)
		{
			delete seq4.op;
			seq4.op = NULL;
		}
	}
}

void PPPatMatch::open  ()
{
    seq1.op->open();
	seq2.op->open();

	if (ch_cnt > 2)
	{
		seq3.op->open();
		if (ch_cnt > 3)
		{
			seq4.op->open();
		}
	}

	if (tknzr!=NULL)
	{
		delete tknzr;
		tknzr = NULL;
	}
    first_time = true;
}

void PPPatMatch::reopen  ()
{
    seq1.op->reopen();
	seq2.op->reopen();

	if (ch_cnt > 2)
	{
		seq3.op->reopen();
		if (ch_cnt > 3)
		{
			seq4.op->reopen();
		}
	}

	if (tknzr!=NULL)
	{
		delete tknzr;
		tknzr = NULL;
	}
    first_time = true;
}

void PPPatMatch::close  ()
{
    seq1.op->close();
	seq2.op->close();

	if (ch_cnt>2)
	{
		seq3.op->close();
		if (ch_cnt>3)
		{
			seq4.op->close();
		}
	}

	if (tknzr!=NULL)
	{
		delete tknzr;
		tknzr = NULL;
	}
}

bool PPPatMatch::result(PPIterator* cur, dynamic_context *cxt, void*& r)
{
    throw USER_EXCEPTION2(SE1002, "PPPatMatch::result");
}

PPIterator* PPPatMatch::copy(dynamic_context *_cxt_)
{
	PPPatMatch *res ;
	switch (ch_cnt)
	{
	case 2:
		res = se_new PPPatMatch(_cxt_, seq1,seq2,pmt);
		res->seq1.op = seq1.op->copy(_cxt_);
		res->seq2.op = seq2.op->copy(_cxt_);
		break;
	case 3:
		res = se_new PPPatMatch(_cxt_, seq1,seq2,seq3,pmt);
		res->seq1.op = seq1.op->copy(_cxt_);
		res->seq2.op = seq2.op->copy(_cxt_);
		res->seq3.op = seq3.op->copy(_cxt_);
		break;
	case 4:
		res = se_new PPPatMatch(_cxt_, seq1,seq2,seq3,seq4,pmt);
		res->seq1.op = seq1.op->copy(_cxt_);
		res->seq2.op = seq2.op->copy(_cxt_);
		res->seq3.op = seq3.op->copy(_cxt_);
		res->seq4.op = seq4.op->copy(_cxt_);
		break;
	}
    return res;
}

static inline tuple_cell check_string_argument(tuple &t, PPOpIn &seq, bool is_empty_allowed, patmatch_type pmt, int arg_num)
{
    seq.op->next(t);
    if(t.is_eos())
    {
        if(is_empty_allowed) return EMPTY_STRING_TC;
        else throw USER_EXCEPTION2(XPTY0004, (std::string("Invalid arity of the ") + get_argument_name(arg_num) + " of " + get_function_name(pmt) + ". Argument contains empty sequence.").c_str());
    }
    tuple_cell res = atomize(seq.get(t));
    if(!is_string_type(res.get_atomic_type()))
        throw USER_EXCEPTION2(XPTY0004, (std::string("Invalid type of the ") + get_argument_name(arg_num) + " of " + get_function_name(pmt) + " (xs_string/derived/promotable is expected).").c_str());
    seq.op->next(t);
    if(!t.is_eos())
        throw USER_EXCEPTION2(XPTY0004, (std::string("Invalid arity of the ") + get_argument_name(arg_num) + " of " + get_function_name(pmt) + ". Argument contains more than one item.").c_str());
    return res;
}

void PPPatMatch::next  (tuple &t)
{
    if (first_time)
    {
        first_time = false;

        tuple_cell t1c, t2c, t3c, t4c;

        t1c = check_string_argument(t, seq1, true,  pmt, 1);
		t2c = check_string_argument(t, seq2, false, pmt, 2);
		t3c.set_eos();
		t4c.set_eos();

		if (ch_cnt > 2)
		{
			t3c = check_string_argument(t, seq3, false,  pmt, 3);
			if (ch_cnt > 3)	t4c = check_string_argument(t, seq4, false,  pmt, 4);
		}

		(this->*comp_fun)(t, &t1c, &t2c, &t3c, &t4c);

		if (tknzr != NULL)
		{
			tknzr->get_next_result(t);
			if (t.is_eos())
			{
				delete tknzr;
				tknzr = NULL;
				first_time = true;
			}
		}
	}
    else
    {
		if (tknzr != NULL)
		{
			tknzr->get_next_result(t);
			if (t.is_eos())
			{
				delete tknzr;
				tknzr = NULL;
				first_time = true;
			}
		}
		else
		{
			first_time = true;
			t.set_eos();
		}
    }
}

void PPPatMatch::tokenize (tuple &t,tuple_cell *t1,tuple_cell *t2,tuple_cell *t3,tuple_cell *t4)
{
	tuple_cell tc=tuple_cell::make_sure_light_atomic(*t2);
	tuple_cell tflags = tuple_cell::eos();

	if(!t3->is_eos()) tflags = tuple_cell::make_sure_light_atomic(*t3);

	tknzr = charset_handler->tokenize(t1, &tc, &tflags);
}

void PPPatMatch::matches (tuple &t,tuple_cell *t1,tuple_cell *t2,tuple_cell *t3,tuple_cell *t4)
{
	tuple_cell tc=tuple_cell::make_sure_light_atomic(*t2);
	tuple_cell tflags = tuple_cell::eos();

	if (!t3->is_eos()) tflags = tuple_cell::make_sure_light_atomic(*t3);

	charset_handler->matches(t, t1, &tc, &tflags);
}

void PPPatMatch::replace (tuple &t,tuple_cell *t1,tuple_cell *t2,tuple_cell *t3,tuple_cell *t4)
{
	tuple_cell tc=tuple_cell::make_sure_light_atomic(*t2);
	tuple_cell tf=tuple_cell::make_sure_light_atomic(*t3);
	tuple_cell tflags = tuple_cell::eos();

	if (!t4->is_eos()) tflags = tuple_cell::make_sure_light_atomic(*t4);

	charset_handler->replace(t, t1, &tc, &tf, &tflags);
}
<|endoftext|>


<commit_before>/*
 * =============================================================================
 *
 *       Filename:  list.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  05/10/2018 01:58:17 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Prashant Pandey (), ppandey@cs.stonybrook.edu
 *   Organization:  Stony Brook University
 *
 * =============================================================================
 */

#include <iostream>
#include <cstring>
#include <vector>
#include <set>
#include <bitset>
#include <cassert>
#include <fstream>

#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include	<stdlib.h>

#include "clipp.h"
#include "ProgOpts.h"
#include "gqf_cpp.h"
#include "kmer.h"

/*
 * ===  FUNCTION  ==============================================================
 *         Name:  main
 *  Description:
 * =============================================================================
 */
int list_main(ListOpts& opts)
{
	struct timeval start, end;
	struct timezone tzp;
	spdlog::logger* console = opts.console.get();

	//Initialize the QF
	console->info("Reading kmers into the QF off the disk.");
	CQF<KeyObject> cqf(opts.cqf_file, LOCKS_FORBIDDEN, FREAD);

	if (!cqf.is_exact()) {
		console->error("The file is not generated using Squeakr-exact.");
		return 1;
	}

	uint64_t kmer_size = cqf.keybits() / 2;
	std::ofstream opfile(opts.output_file.c_str(), std::ofstream::out);

	CQF<KeyObject>::Iterator it = cqf.begin();
	gettimeofday(&start, &tzp);
	do {
		KeyObject k = *it;
		opfile << Kmer::int_to_str(k.key, kmer_size) << std::endl;
		++it;
	} while (!it.done());
	gettimeofday(&end, &tzp);
	print_time_elapsed("", &start, &end, console);

	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
<commit_msg>fixing list API.<commit_after>/*
 * =============================================================================
 *
 *       Filename:  list.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  05/10/2018 01:58:17 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Prashant Pandey (), ppandey@cs.stonybrook.edu
 *   Organization:  Stony Brook University
 *
 * =============================================================================
 */

#include <iostream>
#include <cstring>
#include <vector>
#include <set>
#include <bitset>
#include <cassert>
#include <fstream>

#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include	<stdlib.h>

#include "clipp.h"
#include "ProgOpts.h"
#include "gqf_cpp.h"
#include "kmer.h"

/*
 * ===  FUNCTION  ==============================================================
 *         Name:  main
 *  Description:
 * =============================================================================
 */
int list_main(ListOpts& opts)
{
	struct timeval start, end;
	struct timezone tzp;
	spdlog::logger* console = opts.console.get();

	//Initialize the QF
	console->info("Reading kmers into the QF off the disk.");
	CQF<KeyObject> cqf(opts.cqf_file, LOCKS_FORBIDDEN, FREAD);

	if (!cqf.is_exact()) {
		console->error("The file is not generated using Squeakr-exact.");
		return 1;
	}

	uint64_t kmer_size = cqf.keybits() / 2;
	std::ofstream opfile(opts.output_file.c_str(), std::ofstream::out);

	CQF<KeyObject>::Iterator it = cqf.begin();
	gettimeofday(&start, &tzp);
	do {
		KeyObject k = *it;
		opfile << Kmer::int_to_str(k.key, kmer_size) << "\t" << k.count << std::endl;
		++it;
	} while (!it.done());
	gettimeofday(&end, &tzp);
	print_time_elapsed("", &start, &end, console);

	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
<|endoftext|>


<commit_before><commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
//  This utility is designed to be used by the GCC frontend for creating
// bytecode files from it's intermediate llvm assembly.  The requirements for
// this utility are thus slightly different than that of the standard as util.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/LevelChange.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/ChangeAllocations.h"
#include "llvm/Transforms/Scalar/DCE.h"
#include "llvm/Transforms/Scalar/IndVarSimplify.h"
#include "llvm/Transforms/Scalar/InstructionCombining.h"
#include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "Support/CommandLine.h"
#include <memory>
#include <fstream>
#include <string>

cl::String InputFilename ("", "Parse <arg> file, compile to bytecode",
                          cl::Required, "");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
cl::Flag   StopAtLevelRaise("stopraise", "Stop optimization before level raise",
                            cl::Hidden);

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");

  std::auto_ptr<Module> M;
  try {
    // Parse the file now...
    M.reset(ParseAssemblyFile(InputFilename));
  } catch (const ParseException &E) {
    cerr << E.getMessage() << endl;
    return 1;
  }

  if (M.get() == 0) {
    cerr << "assembly didn't read correctly.\n";
    return 1;
  }

  if (OutputFilename == "") {   // Didn't specify an output filename?
    std::string IFN = InputFilename;
    int Len = IFN.length();
    if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
      OutputFilename = std::string(IFN.begin(), IFN.end()-2);
    } else {
      OutputFilename = IFN;   // Append a .o to it
    }
    OutputFilename += ".o";
  }

  std::ofstream Out(OutputFilename.c_str(), ios::out);
  if (!Out.good()) {
    cerr << "Error opening " << OutputFilename << "!\n";
    return 1;
  }

  // In addition to just parsing the input from GCC, we also want to spiff it up
  // a little bit.  Do this now.
  //
  PassManager Passes;
  Passes.add(createDeadInstEliminationPass());    // Remove Dead code/vars
  Passes.add(createRaiseAllocationsPass());       // call %malloc -> malloc inst
  Passes.add(createCleanupGCCOutputPass());       // Fix gccisms
  Passes.add(createIndVarSimplifyPass());         // Simplify indvars
  if (!StopAtLevelRaise) {
    Passes.add(createRaisePointerReferencesPass()); // Eliminate casts
    Passes.add(createPromoteMemoryToRegister());    // Promote alloca's to regs
    Passes.add(createConstantMergePass());          // Merge dup global consts
    Passes.add(createInstructionCombiningPass());   // Combine silly seq's
    Passes.add(createDeadCodeEliminationPass());    // Remove Dead code/vars
  }
  Passes.add(new WriteBytecodePass(&Out));        // Write bytecode to file...

  // Run our queue of passes all at once now, efficiently.
  Passes.run(M.get());
  return 0;
}

<commit_msg>The cleangcc pass is brokeninto two pieces, execute both of them.<commit_after>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
//  This utility is designed to be used by the GCC frontend for creating
// bytecode files from it's intermediate llvm assembly.  The requirements for
// this utility are thus slightly different than that of the standard as util.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/LevelChange.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/ChangeAllocations.h"
#include "llvm/Transforms/Scalar/DCE.h"
#include "llvm/Transforms/Scalar/IndVarSimplify.h"
#include "llvm/Transforms/Scalar/InstructionCombining.h"
#include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "Support/CommandLine.h"
#include <memory>
#include <fstream>
#include <string>

cl::String InputFilename ("", "Parse <arg> file, compile to bytecode",
                          cl::Required, "");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
cl::Flag   StopAtLevelRaise("stopraise", "Stop optimization before level raise",
                            cl::Hidden);

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");

  std::auto_ptr<Module> M;
  try {
    // Parse the file now...
    M.reset(ParseAssemblyFile(InputFilename));
  } catch (const ParseException &E) {
    cerr << E.getMessage() << endl;
    return 1;
  }

  if (M.get() == 0) {
    cerr << "assembly didn't read correctly.\n";
    return 1;
  }

  if (OutputFilename == "") {   // Didn't specify an output filename?
    std::string IFN = InputFilename;
    int Len = IFN.length();
    if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
      OutputFilename = std::string(IFN.begin(), IFN.end()-2);
    } else {
      OutputFilename = IFN;   // Append a .o to it
    }
    OutputFilename += ".o";
  }

  std::ofstream Out(OutputFilename.c_str(), ios::out);
  if (!Out.good()) {
    cerr << "Error opening " << OutputFilename << "!\n";
    return 1;
  }

  // In addition to just parsing the input from GCC, we also want to spiff it up
  // a little bit.  Do this now.
  //
  PassManager Passes;
  Passes.add(createFunctionResolvingPass());      // Resolve (...) functions
  Passes.add(createDeadInstEliminationPass());    // Remove Dead code/vars
  Passes.add(createRaiseAllocationsPass());       // call %malloc -> malloc inst
  Passes.add(createCleanupGCCOutputPass());       // Fix gccisms
  Passes.add(createIndVarSimplifyPass());         // Simplify indvars
  if (!StopAtLevelRaise) {
    Passes.add(createRaisePointerReferencesPass()); // Eliminate casts
    Passes.add(createPromoteMemoryToRegister());    // Promote alloca's to regs
    Passes.add(createConstantMergePass());          // Merge dup global consts
    Passes.add(createInstructionCombiningPass());   // Combine silly seq's
    Passes.add(createDeadCodeEliminationPass());    // Remove Dead code/vars
  }
  Passes.add(new WriteBytecodePass(&Out));        // Write bytecode to file...

  // Run our queue of passes all at once now, efficiently.
  Passes.run(M.get());
  return 0;
}

<|endoftext|>


<commit_before><commit_msg>Update iot_att.cpp<commit_after><|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *   Author: Pavel Kirienko <pavel.kirienko@gmail.com>
 *
 * 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. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS 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
 * COPYRIGHT OWNER OR 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.
 *
 ****************************************************************************/

#include <ch.h>
#include <hal.h>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <unistd.h>
#include <board/board.hpp>
#include <board/led.hpp>
#include <console.hpp>
#include <pwm_input.hpp>
#include <temperature_sensor.hpp>
#include <motor/motor.h>
#include <uavcan_node/uavcan_node.hpp>

namespace
{

static constexpr unsigned WATCHDOG_TIMEOUT = 10000;

board::LEDOverlay led_ctl;

os::watchdog::Timer init()
{
	auto wdt = board::init(WATCHDOG_TIMEOUT);

	led_ctl.set(board::LEDColor::PALE_WHITE);

	// Temperature sensor
	int res = temperature_sensor::init();
	if (res < 0) {
		os::lowsyslog("Failed to init temperature sensor\n");
		board::die(res);
	}

	// Motor control (must be initialized earlier than communicaton interfaces)
	res = motor_init();
	if (res < 0) {
		board::die(res);
	}

	// PWM input
	pwm_input_init();

	// UAVCAN node
	res = uavcan_node::init();
	if (res < 0) {
		board::die(res);
	}

	// Self test
	res = motor_test_hardware();
	if (res != 0) {
		board::die(res);
	}

	if (motor_test_motor()) {
		os::lowsyslog("Motor is not connected or damaged\n");
	}

	// Initializing console after delay to ensure that CLI is flushed
	usleep(300000);
	console_init();

	return wdt;
}

void do_startup_beep()
{
	motor_beep(1000, 100);
	::usleep(200 * 1000);
	motor_beep(1000, 100);
}

}

namespace os
{

void applicationHaltHook()
{
	motor_emergency();
	board::led_emergency_override(board::LEDColor::RED);
}

}

int main()
{
	auto wdt = init();

	chThdSetPriority(LOWPRIO);

	do_startup_beep();

	motor_confirm_initialization();

	uavcan_node::set_node_status_ok();

	/*
	 * Here we run some high-level self diagnostics, indicating the system health via UAVCAN and LED.
	 * TODO: Refactor.
	 * TODO: Report status flags via vendor-specific status field.
	 */
	auto config_modifications = os::config::getModificationCounter();

	while (!os::isRebootRequested()) {
		wdt.reset();

		if (motor_is_blocked() || !temperature_sensor::is_ok()) {
			led_ctl.set(board::LEDColor::YELLOW);
			uavcan_node::set_node_status_critical();
		} else {
			led_ctl.set(board::LEDColor::DARK_GREEN);
			uavcan_node::set_node_status_ok();
		}

		const auto new_config_modifications = os::config::getModificationCounter();
		if ((new_config_modifications != config_modifications) && motor_is_idle())
		{
			config_modifications = new_config_modifications;
			os::lowsyslog("Saving configuration... ");
			const int res = ::configSave();		// TODO use C++ API
			os::lowsyslog("Done [%d]\n", res);
		}

		::usleep(10 * 1000);
	}

	::usleep(100 * 1000);
	motor_stop();
	board::reboot();

	return 0;
}
<commit_msg>Compiler version check<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *   Author: Pavel Kirienko <pavel.kirienko@gmail.com>
 *
 * 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. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS 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
 * COPYRIGHT OWNER OR 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.
 *
 ****************************************************************************/

#include <ch.h>
#include <hal.h>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <unistd.h>
#include <board/board.hpp>
#include <board/led.hpp>
#include <console.hpp>
#include <pwm_input.hpp>
#include <temperature_sensor.hpp>
#include <motor/motor.h>
#include <uavcan_node/uavcan_node.hpp>

namespace
{

static constexpr unsigned WATCHDOG_TIMEOUT = 10000;

board::LEDOverlay led_ctl;

os::watchdog::Timer init()
{
	auto wdt = board::init(WATCHDOG_TIMEOUT);

	led_ctl.set(board::LEDColor::PALE_WHITE);

	// Temperature sensor
	int res = temperature_sensor::init();
	if (res < 0) {
		os::lowsyslog("Failed to init temperature sensor\n");
		board::die(res);
	}

	// Motor control (must be initialized earlier than communicaton interfaces)
	res = motor_init();
	if (res < 0) {
		board::die(res);
	}

	// PWM input
	pwm_input_init();

	// UAVCAN node
	res = uavcan_node::init();
	if (res < 0) {
		board::die(res);
	}

	// Self test
	res = motor_test_hardware();
	if (res != 0) {
		board::die(res);
	}

	if (motor_test_motor()) {
		os::lowsyslog("Motor is not connected or damaged\n");
	}

	// Initializing console after delay to ensure that CLI is flushed
	usleep(300000);
	console_init();

	return wdt;
}

void do_startup_beep()
{
	motor_beep(1000, 100);
	::usleep(200 * 1000);
	motor_beep(1000, 100);
}

}

namespace os
{

void applicationHaltHook()
{
	motor_emergency();
	board::led_emergency_override(board::LEDColor::RED);
}

}

int main()
{
	auto wdt = init();

	chThdSetPriority(LOWPRIO);

	do_startup_beep();

	motor_confirm_initialization();

	uavcan_node::set_node_status_ok();

	/*
	 * Here we run some high-level self diagnostics, indicating the system health via UAVCAN and LED.
	 * TODO: Refactor.
	 * TODO: Report status flags via vendor-specific status field.
	 */
	auto config_modifications = os::config::getModificationCounter();

	while (!os::isRebootRequested()) {
		wdt.reset();

		if (motor_is_blocked() || !temperature_sensor::is_ok()) {
			led_ctl.set(board::LEDColor::YELLOW);
			uavcan_node::set_node_status_critical();
		} else {
			led_ctl.set(board::LEDColor::DARK_GREEN);
			uavcan_node::set_node_status_ok();
		}

		const auto new_config_modifications = os::config::getModificationCounter();
		if ((new_config_modifications != config_modifications) && motor_is_idle())
		{
			config_modifications = new_config_modifications;
			os::lowsyslog("Saving configuration... ");
			const int res = ::configSave();		// TODO use C++ API
			os::lowsyslog("Done [%d]\n", res);
		}

		::usleep(10 * 1000);
	}

	::usleep(100 * 1000);
	motor_stop();
	board::reboot();

	return 0;
}

#define MATCH_GCC_VERSION(major, minor)  \
    ((__GNUC__ == (major)) && (__GNUC_MINOR__ == (minor)))

#if !MATCH_GCC_VERSION(4, 9)
# error "This compiler is not supported"
#endif
<|endoftext|>


<commit_before>#include <math.h>

#include "fixed_control_car.h"
#include "logging.h"
#include "utils.h"

fixed_control_car::fixed_control_car(display &display, world &world, double x, double y, double dir, double speed)
    : car(display,world,x,y,dir,speed)
{
}

fixed_control_car::~fixed_control_car()
{
}

void fixed_control_car::update_controls(double microsecs)
{
    unsigned char front_view[200*200];
    world &w = get_world();

    // get front_view
    w.get_view(get_x(), get_y(), get_dir(), 200, 200, reinterpret_cast<unsigned char *>(front_view));

    //set_steer_ctl(get_dir() < 90 ? 10 : 0);
    //set_speed_ctl(get_speed() < 20 ? 10 : 0);
}

<commit_msg>simplify fixed_control_car.cpp<commit_after>#include "fixed_control_car.h"
#include "logging.h"
#include "utils.h"

fixed_control_car::fixed_control_car(display &display, world &world, double x, double y, double dir, double speed)
    : car(display,world,x,y,dir,speed)
{
}

fixed_control_car::~fixed_control_car()
{
}

void fixed_control_car::update_controls(double microsecs)
{
    // get front_view, this is done to just get an idea of the processing time
    unsigned char front_view[200*200];
    world &w = get_world();
    w.get_view(get_x(), get_y(), get_dir(), 200, 200, reinterpret_cast<unsigned char *>(front_view));
}

<|endoftext|>


<commit_before>/*
 * File:   Scene.cpp
 * Author: iMer
 *
 * Created on 3. Juli 2014, 01:01
 */

#include "Scene.hpp"
#include "Game.hpp"
#include "Light.hpp"
#include <iostream>
#include <mutex>
#include "Light.hpp"
#include "Engine/Factory.hpp"
namespace engine {
    b2Vec2 Scene::default_gravity(0, 0);

    SceneContactListener::SceneContactListener(Scene* scene) : m_scene(scene) {

    }

    void SceneContactListener::BeginContact(b2Contact* contact) {
        m_scene->OnContact.Fire(contact, true);
    }

    void SceneContactListener::EndContact(b2Contact* contact) {
        m_scene->OnContact.Fire(contact, false);
    }
    void SceneContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse){
        m_scene->OnContactPostSolve.Fire(contact, impulse);
    }

    Scene::Scene(Game* game) : Node(this), m_game(game), m_pixToM(80.0f), m_debugDraw(this), m_lightSystem(this), m_debug(false), m_ui(nullptr), m_contactListener(this) {
        m_world = new b2World(default_gravity);
        m_world->SetContactListener(&m_contactListener);
        m_world->SetDebugDraw(&m_debugDraw);
        m_debugDraw.SetFlags(b2Draw::e_shapeBit);
    }

    LightSystem* Scene::GetLightSystem() {
        return &m_lightSystem;
    }

    void Scene::SetDebug(bool debug) {
        m_debug = debug;
    }

    bool Scene::IsDebug() const {
        return m_debug;
    }

    Scene::~Scene() {
        while (m_children.size()) {
            delete m_children.front();
        }
        m_children.clear();
        delete m_world;
        m_world = nullptr;
    }

    void Scene::SetGame(Game* game) {
        m_game = game;
    }

    Game* Scene::GetGame() const {
        return m_game;
    }

    b2World* Scene::GetWorld() {
        return m_world;
    }

    float Scene::MeterToPixel(float m) {
        return m_pixToM*m;
    }

    float Scene::GetPixelMeterRatio() const {
        return m_pixToM;
    }

    void Scene::PostDraw(sf::RenderTarget& target, sf::RenderStates states, float delta) {
        if (m_debug) {
            m_mutexDebug.lock();
            if (m_debugDraw.IsInitialized()) {
                m_debugDraw.draw(target, states);
            }
            m_mutexDebug.unlock();
        }
        m_lightSystem.draw(target, states);
        // Keep UI in the screen
        // Keep UI in the screen
        auto view = m_scene->GetGame()->GetWindow()->getView();
		if (m_ui){
			m_ui->SetPosition(view.getCenter().x - (view.getSize().x / 2), view.getCenter().y - (view.getSize().y / 2));
			m_ui->draw(target, states, delta);
		}
    }

    void Scene::OnUpdate(sf::Time interval) {
        m_world->Step(interval.asSeconds(), 8, 3); // TODO: tweakable iterations? currently the box2d recommended ones
        if (m_debug) {
            m_mutexDebug.lock();
            m_debugDraw.Begin();
            m_world->DrawDebugData();
            m_debugDraw.End();
            m_mutexDebug.unlock();
        }
        m_lightSystem.update(interval);
        if (m_ui) {
			m_ui->update(interval);
		}
    }

    uint8_t Scene::GetType() const {
        return NT_SCENE;
    }

    bool Scene::initialize(Json::Value& root) {
        if (root.isMember("size")) {
            auto size = root["size"];
            if (size.isArray()) {
                m_size.x = size.get(0u, 0).asFloat();
                m_size.y = size.get(1u, 0).asFloat();
            } else {
                m_size.x = size.get("x", 0).asFloat();
                m_size.y = size.get("y", 0).asFloat();
            }
        }
        if (root["gravity"].isArray()) {
            m_world->SetGravity(b2Vec2(root["gravity"].get(0u, 0).asFloat(), root["gravity"].get(1u, 0).asFloat()));
        } else if (root["gravity"].isObject()) {
            m_world->SetGravity(b2Vec2(root["gravity"].get("x", 0).asFloat(), root["gravity"].get("y", 0).asFloat()));
        }
        m_pixToM = root.get("pixelToMeter", 80).asFloat();
        m_debug = root.get("debug", false).asBool();
        auto light = root["light"];
        if (!light.empty() && !light.isNull()) {
            m_lightSystem.SetEnabled(light.get("enabled", true).asBool());
            if (light["ambient"].isArray()) {
                m_lightSystem.SetAmbientColor(sf::Color(light["ambient"].get(0u, 255).asInt(), light["ambient"].get(1u, 255).asInt(), light["ambient"].get(2u, 255).asInt(), light["ambient"].get(3u, 255).asInt()));
            } else if (light["ambient"].isInt()) {
                unsigned int lc = light["ambient"].asInt();
                m_lightSystem.SetAmbientColor(sf::Color(lc & 0xFF0000, lc & 0xFF00, lc & 0xFF, lc & 0xFF000000));
            }
        }
		// Easy way to fill the ui layer
		auto ui = root["ui"];
		if (ui.isArray()) {
			m_ui = new Node(this);
			Factory::MakeChildren(ui, m_ui);
		}
        return true;
    }
}

<commit_msg>Only create new m_ui node when needed<commit_after>/*
 * File:   Scene.cpp
 * Author: iMer
 *
 * Created on 3. Juli 2014, 01:01
 */

#include "Scene.hpp"
#include "Game.hpp"
#include "Light.hpp"
#include <iostream>
#include <mutex>
#include "Light.hpp"
#include "Engine/Factory.hpp"
namespace engine {
    b2Vec2 Scene::default_gravity(0, 0);

    SceneContactListener::SceneContactListener(Scene* scene) : m_scene(scene) {

    }

    void SceneContactListener::BeginContact(b2Contact* contact) {
        m_scene->OnContact.Fire(contact, true);
    }

    void SceneContactListener::EndContact(b2Contact* contact) {
        m_scene->OnContact.Fire(contact, false);
    }
    void SceneContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse){
        m_scene->OnContactPostSolve.Fire(contact, impulse);
    }

    Scene::Scene(Game* game) : Node(this), m_game(game), m_pixToM(80.0f), m_debugDraw(this), m_lightSystem(this), m_debug(false), m_ui(nullptr), m_contactListener(this) {
        m_world = new b2World(default_gravity);
        m_world->SetContactListener(&m_contactListener);
        m_world->SetDebugDraw(&m_debugDraw);
        m_debugDraw.SetFlags(b2Draw::e_shapeBit);
    }

    LightSystem* Scene::GetLightSystem() {
        return &m_lightSystem;
    }

    void Scene::SetDebug(bool debug) {
        m_debug = debug;
    }

    bool Scene::IsDebug() const {
        return m_debug;
    }

    Scene::~Scene() {
        while (m_children.size()) {
            delete m_children.front();
        }
        m_children.clear();
        delete m_world;
        m_world = nullptr;
    }

    void Scene::SetGame(Game* game) {
        m_game = game;
    }

    Game* Scene::GetGame() const {
        return m_game;
    }

    b2World* Scene::GetWorld() {
        return m_world;
    }

    float Scene::MeterToPixel(float m) {
        return m_pixToM*m;
    }

    float Scene::GetPixelMeterRatio() const {
        return m_pixToM;
    }

    void Scene::PostDraw(sf::RenderTarget& target, sf::RenderStates states, float delta) {
        if (m_debug) {
            m_mutexDebug.lock();
            if (m_debugDraw.IsInitialized()) {
                m_debugDraw.draw(target, states);
            }
            m_mutexDebug.unlock();
        }
        m_lightSystem.draw(target, states);
        // Keep UI in the screen
        // Keep UI in the screen
        auto view = m_scene->GetGame()->GetWindow()->getView();
		if (m_ui){
			m_ui->SetPosition(view.getCenter().x - (view.getSize().x / 2), view.getCenter().y - (view.getSize().y / 2));
			m_ui->draw(target, states, delta);
		}
    }

    void Scene::OnUpdate(sf::Time interval) {
        m_world->Step(interval.asSeconds(), 8, 3); // TODO: tweakable iterations? currently the box2d recommended ones
        if (m_debug) {
            m_mutexDebug.lock();
            m_debugDraw.Begin();
            m_world->DrawDebugData();
            m_debugDraw.End();
            m_mutexDebug.unlock();
        }
        m_lightSystem.update(interval);
        if (m_ui) {
			m_ui->update(interval);
		}
    }

    uint8_t Scene::GetType() const {
        return NT_SCENE;
    }

    bool Scene::initialize(Json::Value& root) {
        if (root.isMember("size")) {
            auto size = root["size"];
            if (size.isArray()) {
                m_size.x = size.get(0u, 0).asFloat();
                m_size.y = size.get(1u, 0).asFloat();
            } else {
                m_size.x = size.get("x", 0).asFloat();
                m_size.y = size.get("y", 0).asFloat();
            }
        }
        if (root["gravity"].isArray()) {
            m_world->SetGravity(b2Vec2(root["gravity"].get(0u, 0).asFloat(), root["gravity"].get(1u, 0).asFloat()));
        } else if (root["gravity"].isObject()) {
            m_world->SetGravity(b2Vec2(root["gravity"].get("x", 0).asFloat(), root["gravity"].get("y", 0).asFloat()));
        }
        m_pixToM = root.get("pixelToMeter", 80).asFloat();
        m_debug = root.get("debug", false).asBool();
        auto light = root["light"];
        if (!light.empty() && !light.isNull()) {
            m_lightSystem.SetEnabled(light.get("enabled", true).asBool());
            if (light["ambient"].isArray()) {
                m_lightSystem.SetAmbientColor(sf::Color(light["ambient"].get(0u, 255).asInt(), light["ambient"].get(1u, 255).asInt(), light["ambient"].get(2u, 255).asInt(), light["ambient"].get(3u, 255).asInt()));
            } else if (light["ambient"].isInt()) {
                unsigned int lc = light["ambient"].asInt();
                m_lightSystem.SetAmbientColor(sf::Color(lc & 0xFF0000, lc & 0xFF00, lc & 0xFF, lc & 0xFF000000));
            }
        }
		// Easy way to fill the ui layer
		auto ui = root["ui"];
		if (ui.isArray()) {
			if (!m_ui) {
				m_ui = new Node(this);
			}
			Factory::MakeChildren(ui, m_ui);
		}
        return true;
    }
}

<|endoftext|>


<commit_before>#include <string>
#include <cstdlib>
#include "Scope.h"
using namespace std;

char randChar() {
	return (rand() % ('z' - 'a')) + 'a';
}

void Scope::addVar(string type, string name) {
	names.insert(name);
	types[type].push_back(name);
}

string Scope::newVar(string type) {
	string name;
	name += randChar();

	while (names.count(name))
		name += randChar();

	addVar(type, name);
	return name;
}

string Scope::newVar(string type, string name) {
	// add a number to the end of the proposed name
	int counter = 1;
	string newName = name;
	while (names.count(newName))
		newName = name + to_string(counter++);
	addVar(type, newName);
	return newName;
}

string Scope::getVar(string type) {
	if (types[type].empty())
		throw runtime_error("Scope has no variables of type " + type);

	int random = rand() % types[type].size();
	return types[type][random];
}
<commit_msg>Change Scope's random generator to one we created<commit_after>#include <string>
#include <cstdlib>

#include "Scope.h"
#include "Random.h"

using namespace std;

Random randGen;

char randChar() {
	return randGen.drawNumber('a', 'z');
}

void Scope::addVar(string type, string name) {
	names.insert(name);
	types[type].push_back(name);
}

string Scope::newVar(string type) {
	string name;
	name += randChar();

	while (names.count(name))
		name += randChar();

	addVar(type, name);
	return name;
}

string Scope::newVar(string type, string name) {
	// add a number to the end of the proposed name
	int counter = 1;
	string newName = name;
	while (names.count(newName))
		newName = name + to_string(counter++);
	addVar(type, newName);
	return newName;
}

string Scope::getVar(string type) {
	if (types[type].empty())
		throw runtime_error("Scope has no variables of type " + type);

	int random = rand() % types[type].size();
	return types[type][random];
}
<|endoftext|>