<commit_before>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include "BundleInfoInternal.h"

namespace OIC
{
    namespace Service
    {

        BundleInfoInternal::BundleInfoInternal()
        {
            m_activator = nullptr;
            m_deactivator = nullptr;
            m_resourceCreator = nullptr;
            m_resourceDestroyer = nullptr;
            m_bundleHandle = nullptr;
            m_so_bundle = nullptr;

            m_loaded = false;
            m_activated = false;
            m_java_bundle = false;
            m_id = 0;
        }

        BundleInfoInternal::~BundleInfoInternal()
        {
            m_activator = nullptr;
            m_deactivator = nullptr;
            m_resourceCreator = nullptr;
            m_resourceDestroyer = nullptr;
            m_bundleHandle = nullptr;
        }

        void BundleInfoInternal::setID(const std::string &id)
        {
            m_ID = id;
        }

        const std::string &BundleInfoInternal::getID()
        {
            return m_ID;
        }

        void BundleInfoInternal::setPath( const std::string &path)
        {
            m_path = path;
        }
        const std::string &BundleInfoInternal::getPath()
        {
            return m_path;
        }

        void BundleInfoInternal::setVersion( const std::string &version)
        {
            m_version = version;
        }

        const std::string &BundleInfoInternal::getVersion()
        {
            return m_version;
        }

        void BundleInfoInternal::setLoaded(bool loaded)
        {
            m_loaded = loaded;
        }

        bool BundleInfoInternal::isLoaded()
        {
            return m_loaded;
        }

        void BundleInfoInternal::setActivated(bool activated)
        {
            m_activated = activated;
        }

        bool BundleInfoInternal::isActivated()
        {
            return m_activated;
        }

        void BundleInfoInternal::setBundleActivator(activator_t *activator)
        {
            m_activator = activator;
        }

        activator_t *BundleInfoInternal::getBundleActivator()
        {
            return m_activator;
        }

        void BundleInfoInternal::setBundleDeactivator(deactivator_t *deactivator)
        {
            m_deactivator = deactivator;
        }

        deactivator_t *BundleInfoInternal::getBundleDeactivator()
        {
            return m_deactivator;
        }

        void BundleInfoInternal::setResourceCreator(resourceCreator_t *resourceCreator)
        {
            m_resourceCreator = resourceCreator;
        }

        resourceCreator_t *BundleInfoInternal::getResourceCreator()
        {
            return m_resourceCreator;
        }

        void BundleInfoInternal::setResourceDestroyer(resourceDestroyer_t *resourceDestroyer)
        {
            m_resourceDestroyer = resourceDestroyer;
        }

        resourceDestroyer_t *BundleInfoInternal::getResourceDestroyer()
        {
            return m_resourceDestroyer;
        }

        void BundleInfoInternal::setBundleHandle(void *handle)
        {
            m_bundleHandle = handle;
        }

        void *BundleInfoInternal::getBundleHandle()
        {
            return m_bundleHandle;
        }

        void BundleInfoInternal::setJavaBundle(bool javaBundle)
        {
            m_java_bundle = javaBundle;
        }

        bool BundleInfoInternal::getJavaBundle()
        {
            return m_java_bundle;
        }

        void BundleInfoInternal::setSoBundle(bool soBundle)
        {
            m_so_bundle = soBundle;
        }

        bool BundleInfoInternal::getSoBundle()
        {
            return m_so_bundle;
        }

        void BundleInfoInternal::setActivatorName( const std::string &activatorName)
        {
            m_activator_name = activatorName;
        }

        const std::string &BundleInfoInternal::getActivatorName()
        {
            return m_activator_name;
        }

        void BundleInfoInternal::setLibraryPath( const std::string &libpath)
        {
            m_library_path = libpath;
        }

        const std::string &BundleInfoInternal::getLibraryPath()
        {
            return m_library_path;
        }

#if (JAVA_SUPPORT)
        void BundleInfoInternal::setJavaBundleActivatorMethod(jmethodID javaBundleActivator)
        {
            m_java_activator = javaBundleActivator;
        }

        jmethodID BundleInfoInternal::getJavaBundleActivatorMethod()
        {
            return m_java_activator;
        }

        void BundleInfoInternal::setJavaBundleDeactivatorMethod(jmethodID javaBundleActivator)
        {
            m_java_deactivator = javaBundleActivator;
        }

        jmethodID BundleInfoInternal::getJavaBundleDeactivatorMethod()
        {
            return m_java_deactivator;
        }

        void BundleInfoInternal::setJavaBundleActivatorObject(jobject activator_object)
        {
            m_java_activator_object = activator_object;
        }

        jobject BundleInfoInternal::getJavaBundleActivatorObject()
        {
            return m_java_activator_object;
        }
#endif

        void BundleInfoInternal::setBundleInfo(shared_ptr<RCSBundleInfo> bundleInfo)
        {
            shared_ptr<BundleInfoInternal> source =
                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);

            m_ID = source->getID();
            m_path = source->getPath();
            m_version = source->getVersion();
            m_loaded = source->isLoaded();
            m_activated = source->isActivated();
            m_java_bundle = source->getJavaBundle();
            m_activator = source->getBundleActivator();
            m_bundleHandle = source->getBundleHandle();
            m_activator_name = source->getActivatorName();
        }
    }
}
<commit_msg>Build update, now builds on F23<commit_after>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include "BundleInfoInternal.h"

namespace OIC
{
    namespace Service
    {

        BundleInfoInternal::BundleInfoInternal()
        {
            m_activator = nullptr;
            m_deactivator = nullptr;
            m_resourceCreator = nullptr;
            m_resourceDestroyer = nullptr;
            m_bundleHandle = nullptr;

            m_so_bundle = false;
            m_loaded = false;
            m_activated = false;
            m_java_bundle = false;
            m_id = 0;
        }

        BundleInfoInternal::~BundleInfoInternal()
        {
            m_activator = nullptr;
            m_deactivator = nullptr;
            m_resourceCreator = nullptr;
            m_resourceDestroyer = nullptr;
            m_bundleHandle = nullptr;
        }

        void BundleInfoInternal::setID(const std::string &id)
        {
            m_ID = id;
        }

        const std::string &BundleInfoInternal::getID()
        {
            return m_ID;
        }

        void BundleInfoInternal::setPath( const std::string &path)
        {
            m_path = path;
        }
        const std::string &BundleInfoInternal::getPath()
        {
            return m_path;
        }

        void BundleInfoInternal::setVersion( const std::string &version)
        {
            m_version = version;
        }

        const std::string &BundleInfoInternal::getVersion()
        {
            return m_version;
        }

        void BundleInfoInternal::setLoaded(bool loaded)
        {
            m_loaded = loaded;
        }

        bool BundleInfoInternal::isLoaded()
        {
            return m_loaded;
        }

        void BundleInfoInternal::setActivated(bool activated)
        {
            m_activated = activated;
        }

        bool BundleInfoInternal::isActivated()
        {
            return m_activated;
        }

        void BundleInfoInternal::setBundleActivator(activator_t *activator)
        {
            m_activator = activator;
        }

        activator_t *BundleInfoInternal::getBundleActivator()
        {
            return m_activator;
        }

        void BundleInfoInternal::setBundleDeactivator(deactivator_t *deactivator)
        {
            m_deactivator = deactivator;
        }

        deactivator_t *BundleInfoInternal::getBundleDeactivator()
        {
            return m_deactivator;
        }

        void BundleInfoInternal::setResourceCreator(resourceCreator_t *resourceCreator)
        {
            m_resourceCreator = resourceCreator;
        }

        resourceCreator_t *BundleInfoInternal::getResourceCreator()
        {
            return m_resourceCreator;
        }

        void BundleInfoInternal::setResourceDestroyer(resourceDestroyer_t *resourceDestroyer)
        {
            m_resourceDestroyer = resourceDestroyer;
        }

        resourceDestroyer_t *BundleInfoInternal::getResourceDestroyer()
        {
            return m_resourceDestroyer;
        }

        void BundleInfoInternal::setBundleHandle(void *handle)
        {
            m_bundleHandle = handle;
        }

        void *BundleInfoInternal::getBundleHandle()
        {
            return m_bundleHandle;
        }

        void BundleInfoInternal::setJavaBundle(bool javaBundle)
        {
            m_java_bundle = javaBundle;
        }

        bool BundleInfoInternal::getJavaBundle()
        {
            return m_java_bundle;
        }

        void BundleInfoInternal::setSoBundle(bool soBundle)
        {
            m_so_bundle = soBundle;
        }

        bool BundleInfoInternal::getSoBundle()
        {
            return m_so_bundle;
        }

        void BundleInfoInternal::setActivatorName( const std::string &activatorName)
        {
            m_activator_name = activatorName;
        }

        const std::string &BundleInfoInternal::getActivatorName()
        {
            return m_activator_name;
        }

        void BundleInfoInternal::setLibraryPath( const std::string &libpath)
        {
            m_library_path = libpath;
        }

        const std::string &BundleInfoInternal::getLibraryPath()
        {
            return m_library_path;
        }

#if (JAVA_SUPPORT)
        void BundleInfoInternal::setJavaBundleActivatorMethod(jmethodID javaBundleActivator)
        {
            m_java_activator = javaBundleActivator;
        }

        jmethodID BundleInfoInternal::getJavaBundleActivatorMethod()
        {
            return m_java_activator;
        }

        void BundleInfoInternal::setJavaBundleDeactivatorMethod(jmethodID javaBundleActivator)
        {
            m_java_deactivator = javaBundleActivator;
        }

        jmethodID BundleInfoInternal::getJavaBundleDeactivatorMethod()
        {
            return m_java_deactivator;
        }

        void BundleInfoInternal::setJavaBundleActivatorObject(jobject activator_object)
        {
            m_java_activator_object = activator_object;
        }

        jobject BundleInfoInternal::getJavaBundleActivatorObject()
        {
            return m_java_activator_object;
        }
#endif

        void BundleInfoInternal::setBundleInfo(shared_ptr<RCSBundleInfo> bundleInfo)
        {
            shared_ptr<BundleInfoInternal> source =
                                std::static_pointer_cast<BundleInfoInternal>(bundleInfo);

            m_ID = source->getID();
            m_path = source->getPath();
            m_version = source->getVersion();
            m_loaded = source->isLoaded();
            m_activated = source->isActivated();
            m_java_bundle = source->getJavaBundle();
            m_activator = source->getBundleActivator();
            m_bundleHandle = source->getBundleHandle();
            m_activator_name = source->getActivatorName();
        }
    }
}
<|endoftext|>


<commit_before>#include "APICamera.hpp"

// Messages
#include "camera_application/InitializeCameraService.h"
#include "camera_application/PictureSendingActivation.h"
#include "camera_application/CalibrateCamera.h"

#include <string>
#include <stdexcept>

using namespace kitrokopter;

/**
 * Constructs an APICamera.
 *
 * @param newId the cameras id
 */
APICamera::APICamera(uint32_t newId) :
    calibrated(false),
    calibration(NULL),
    position(Vector()),
    hardwareId(0)
{
    this->id = newId;
}

/**
 * Destructs an APICamera.
 */
APICamera::~APICamera()
{
    if (calibration)
	delete calibration;
}

uint32_t APICamera::getId()
{
    return this->id;
}

void APICamera::listen()
{
    ros::NodeHandle nh;
    pictureSubscriber = nh.subscribe("Picture", 1, &APICamera::handlePicture, this);
    pictureSendingActivationPublisher = nh.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 1);
}

/**
 * Sets the camera's position.
 */
void APICamera::setPosition(double x, double y, double z)
{
    position = Vector(x, y, z);
}

/**
 * Sets calibration data.
 *
 * @param data The calibration data to set.
 */
void APICamera::setCalibrationData(APICalibrationData data)
{
    if (calibration)
	*calibration = data;
    else
	calibration = new APICalibrationData(data);
    /**
     * TODO: Can we do this now? Is there a hardware id?
     */
}

/**
 * @return The calibration data.
 */
APICalibrationData* const APICamera::getCalibrationData()
{
    return calibration;
}

/**
 * Add an calibration image. This will not send this image to the control_application.
 *
 * @param image the image to add
 */
void APICamera::addCalibrationImage(cv::Mat image) {
    this->calibrationImages.push_back(image);
}

/**
 * Get all calibration images
 *
 * @return all images which were used for calibration
 */
std::vector<cv::Mat> APICamera::getAllCalibrationImages() {
    return this->calibrationImages;
}

/**
 * @return Whether the camera is calibrated.
 */
bool APICamera::isCalibrated()
{
    return calibrated;
}

/**
 * Deletes this camera's calibration.
 */
void APICamera::deleteCalibration()
{
    calibrated = false;

    /**
     * TODO: Is there something to send to the camera?
     */
}

/**
 * Adds an image listener.
 *
 * The image listener will receive images this camera takes.
 *
 * @param listener A pointer to the listener.
 */
void APICamera::addImageListener(APIImageListener *listener)
{
    imageListeners.push_back(listener);
}

/**
 * Adds an camera listener.
 *
 * @param listener A pointer to the listener.
 */
void APICamera::addCameraListener(APICameraListener *listener)
{
    cameraListeners.push_back(listener);
}

template <typename T>
void removeListener(std::vector<T*> from, T *listener)
{
    for (typename std::vector<T*>::iterator it = from.begin(); it != from.end(); ++it) {
	if (*it == listener) {
	    from.erase(it);
	    return;
	}
    }
}

/**
 * Removes an image listener.
 *
 * Remember to free it!
 *
 * @param listener A pointer to the listener.
 */
void APICamera::removeImageListener(APIImageListener *listener)
{
    removeListener(imageListeners, listener);
}

/**
 * Removes an camera listener.
 *
 * Remember to free it!
 *
 * @param listener A pointer to the listener.
 */
void APICamera::removeCameraListener(APICameraListener *listener)
{
    removeListener(cameraListeners, listener);
}

/**
 * Sends a message requesting pictures to be or not to be sent.
 *
 * @param active `true` will enable image sending, `false` will disable.
 */
void APICamera::sendPictureSendingActivation(bool active)
{
    camera_application::PictureSendingActivation msg;
    msg.ID = this->id;
    msg.active = active;
    pictureSendingActivationPublisher.publish(msg);
}

cv::Mat* msgToMat(camera_application::Picture::_image_type data)
{
    /*
     * TODO: Is there a possibility to make the size of the image variable?
     * this hardcoded thing is pretty ugly...
     */
    cv::Mat *mat = new cv::Mat(cv::Size(640, 480), CV_8UC3);
    //640 * 480 * 3 = 921600
    for (size_t i = 0; i < (921600); i++) {
	mat->data[i] = data[i];
    }
    return mat;
}

/**
 * Handles incoming pictures.
 */
void APICamera::handlePicture(const camera_application::Picture::Ptr &msg)
{
    if (msg->ID != this->id) return;
    cv::Mat* image = msgToMat(msg->image);
    this->lastImage = *image;
    //call the listeners
    for (std::vector<APIImageListener*>::iterator it = imageListeners.begin(); it != imageListeners.end(); ++it) {
       (*it)->imageReceived(*image);
    }
    delete image;
}

Vector APICamera::getPosition()
{
	return position;
}
<commit_msg>Added all=false when sending picture sending activation<commit_after>#include "APICamera.hpp"

// Messages
#include "camera_application/InitializeCameraService.h"
#include "camera_application/PictureSendingActivation.h"
#include "camera_application/CalibrateCamera.h"

#include <string>
#include <stdexcept>

using namespace kitrokopter;

/**
 * Constructs an APICamera.
 *
 * @param newId the cameras id
 */
APICamera::APICamera(uint32_t newId) :
    calibrated(false),
    calibration(NULL),
    position(Vector()),
    hardwareId(0)
{
    this->id = newId;
}

/**
 * Destructs an APICamera.
 */
APICamera::~APICamera()
{
    if (calibration)
	delete calibration;
}

uint32_t APICamera::getId()
{
    return this->id;
}

void APICamera::listen()
{
    ros::NodeHandle nh;
    pictureSubscriber = nh.subscribe("Picture", 1, &APICamera::handlePicture, this);
    pictureSendingActivationPublisher = nh.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 1);
}

/**
 * Sets the camera's position.
 */
void APICamera::setPosition(double x, double y, double z)
{
    position = Vector(x, y, z);
}

/**
 * Sets calibration data.
 *
 * @param data The calibration data to set.
 */
void APICamera::setCalibrationData(APICalibrationData data)
{
    if (calibration)
	*calibration = data;
    else
	calibration = new APICalibrationData(data);
    /**
     * TODO: Can we do this now? Is there a hardware id?
     */
}

/**
 * @return The calibration data.
 */
APICalibrationData* const APICamera::getCalibrationData()
{
    return calibration;
}

/**
 * Add an calibration image. This will not send this image to the control_application.
 *
 * @param image the image to add
 */
void APICamera::addCalibrationImage(cv::Mat image) {
    this->calibrationImages.push_back(image);
}

/**
 * Get all calibration images
 *
 * @return all images which were used for calibration
 */
std::vector<cv::Mat> APICamera::getAllCalibrationImages() {
    return this->calibrationImages;
}

/**
 * @return Whether the camera is calibrated.
 */
bool APICamera::isCalibrated()
{
    return calibrated;
}

/**
 * Deletes this camera's calibration.
 */
void APICamera::deleteCalibration()
{
    calibrated = false;

    /**
     * TODO: Is there something to send to the camera?
     */
}

/**
 * Adds an image listener.
 *
 * The image listener will receive images this camera takes.
 *
 * @param listener A pointer to the listener.
 */
void APICamera::addImageListener(APIImageListener *listener)
{
    imageListeners.push_back(listener);
}

/**
 * Adds an camera listener.
 *
 * @param listener A pointer to the listener.
 */
void APICamera::addCameraListener(APICameraListener *listener)
{
    cameraListeners.push_back(listener);
}

template <typename T>
void removeListener(std::vector<T*> from, T *listener)
{
    for (typename std::vector<T*>::iterator it = from.begin(); it != from.end(); ++it) {
	if (*it == listener) {
	    from.erase(it);
	    return;
	}
    }
}

/**
 * Removes an image listener.
 *
 * Remember to free it!
 *
 * @param listener A pointer to the listener.
 */
void APICamera::removeImageListener(APIImageListener *listener)
{
    removeListener(imageListeners, listener);
}

/**
 * Removes an camera listener.
 *
 * Remember to free it!
 *
 * @param listener A pointer to the listener.
 */
void APICamera::removeCameraListener(APICameraListener *listener)
{
    removeListener(cameraListeners, listener);
}

/**
 * Sends a message requesting pictures to be or not to be sent.
 *
 * @param active `true` will enable image sending, `false` will disable.
 */
void APICamera::sendPictureSendingActivation(bool active)
{
    camera_application::PictureSendingActivation msg;
    msg.ID = this->id;
    msg.active = active;
    msg.all = false;
    pictureSendingActivationPublisher.publish(msg);
}

cv::Mat* msgToMat(camera_application::Picture::_image_type data)
{
    /*
     * TODO: Is there a possibility to make the size of the image variable?
     * this hardcoded thing is pretty ugly...
     */
    cv::Mat *mat = new cv::Mat(cv::Size(640, 480), CV_8UC3);
    //640 * 480 * 3 = 921600
    for (size_t i = 0; i < (921600); i++) {
	mat->data[i] = data[i];
    }
    return mat;
}

/**
 * Handles incoming pictures.
 */
void APICamera::handlePicture(const camera_application::Picture::Ptr &msg)
{
    if (msg->ID != this->id) return;
    cv::Mat* image = msgToMat(msg->image);
    this->lastImage = *image;
    //call the listeners
    for (std::vector<APIImageListener*>::iterator it = imageListeners.begin(); it != imageListeners.end(); ++it) {
       (*it)->imageReceived(*image);
    }
    delete image;
}

Vector APICamera::getPosition()
{
	return position;
}
<|endoftext|>


<commit_before>#include "diagram.h"
#include "classes/type.h"
#include "classes/enumType.h"
#include "classes/nodeType.h"
#include "classes/edgeType.h"
#include "editor.h"

#include <QDebug>

using namespace qReal;
using namespace qrmc;

Diagram::Diagram(const qReal::Id &id,  qrRepo::LogicalRepoApi *api, Editor *editor)
	: mId(id), mApi(api), mEditor(editor)
{
	mDiagramName = mApi->name(id);
	mDiagramDisplayedName = mApi->stringProperty(id, "displayedName");
	mDiagramNodeName  = mApi->stringProperty(id, "nodeName");
}

Diagram::~Diagram()
{
	foreach(Type *type, mTypes.values())
		if (type)
			delete type;
}

bool Diagram::init()
{
	foreach(Id id, mApi->children(mId)) {
		if (!mApi->isLogicalElement(id))
			continue;

		if (id.element() == metaEntityNode) {
			Type *nodeType = new NodeType(this, mApi, id);
			if (!nodeType->init(mDiagramName)) {
				delete nodeType;
				qDebug() << "can't load node";
				return false;
			}
			mTypes[nodeType->name()] = nodeType;
		} else if (id.element() == metaEntityEdge) {
			Type *edgeType = new EdgeType(this, mApi, id);
			if (!edgeType->init(mDiagramName)) {
				delete edgeType;
				qDebug() << "can't load edge";
				return false;
			}
			mTypes[edgeType->name()] = edgeType;
		} else if (id.element() == metaEntityImport) {
			ImportSpecification import = {
				mApi->stringProperty(id, "importedFrom") + "::" + mApi->stringProperty(id, "as"),
				mApi->stringProperty(id, "as"),
				mApi->stringProperty(id, "displayedName"),
			};
			mImports.append(import);
		} else if (id.element() == metaEntityEnum) {
			Type *enumType = new EnumType(this, mApi, id);
			if (!enumType->init(mDiagramName))
			{
				delete enumType;
				qDebug() << "can't load enum";
				return false;
			}
			mTypes[enumType->name()] = enumType;
		} else {
			qDebug() << "ERROR: unknown type" << id.element();
			return false;
		}
	}
	return true;
}

bool Diagram::resolve()
{
	foreach (ImportSpecification import, mImports) {
		Type *importedType = mEditor->findType(import.name);
		if (importedType == nullptr) {
			qDebug() << "ERROR: imported type" << import.name << "not found, skipping";
			continue;
		}
		Type *copiedType = importedType->clone();
		copiedType->setName(import.as);
		copiedType->setDisplayedName(import.displayedName);
		copiedType->setDiagram(this);
		copiedType->setContext(mDiagramName);
		mTypes.insert(copiedType->qualifiedName(), copiedType);
	}

	foreach(Type *type, mTypes.values())
		if (!type->resolve()) {
			qDebug() << "ERROR: can't resolve type" << type->name();
			return false;
		}

	return true;
}

Editor* Diagram::editor() const
{
	return mEditor;
}

Type* Diagram::findType(QString name)
{
	if (mTypes.contains(name))
		return mTypes[name];

	return mEditor->findType(name);
}

QMap<QString, Type*> Diagram::types() const
{
	return mTypes;
}

QString Diagram::name() const
{
	return mDiagramName;
}

QString Diagram::nodeName() const
{
	return mDiagramNodeName;
}

QString Diagram::displayedName() const
{
	return mDiagramDisplayedName;
}

void Diagram::print()
{
	qDebug() << "elements:" << mTypes.size();
//	foreach(Type *type, mTypes)
//		type->print();
}

class Diagram::MapMethodGenerator {
public:
	virtual ~MapMethodGenerator() {}
	virtual QString generate(Type *type, const QString &lineTemplate) const = 0;
};

class Diagram::NamesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateNames(lineTemplate);
	}
};

class Diagram::MouseGesturesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateMouseGestures(lineTemplate);
	}
};

class Diagram::PropertyNamesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateProperties(lineTemplate);
	}
};

class Diagram::PropertyDefaultsGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePropertyDefaults(lineTemplate);
	}
};

class Diagram::PropertyDisplayedNamesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePropertyDisplayedNames(lineTemplate);
	}
};

class Diagram::ElementDescriptonGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateElementDescription(lineTemplate);
	}
};

class Diagram::ParentsMapGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateParents(lineTemplate);
	}
};

class Diagram::NodesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateNodeClass(lineTemplate);
	}
};

class Diagram::EdgesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateEdgeClass(lineTemplate);
	}
};

class Diagram::ResourceGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateResourceLine(lineTemplate);
	}
};

QString Diagram::generateMapMethod(const QString& lineTemplate, const MapMethodGenerator &generator) const
{
	QString result;
	foreach(Type* type, mTypes) {
		QString line = generator.generate(type, lineTemplate);
		if (!line.isEmpty())
			result += line + endline;
	}
	return result;
}

QString Diagram::generateNamesMap(const QString& lineTemplate) const
{
	return generateMapMethod(lineTemplate, NamesGenerator());
}

QString Diagram::generateMouseGesturesMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, MouseGesturesGenerator());
}

QString Diagram::generatePropertiesMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, PropertyNamesGenerator());
}

QString Diagram::generatePropertyDefaultsMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, PropertyDefaultsGenerator());
}

QString Diagram::generatePropertyDisplayedNamesMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, PropertyDisplayedNamesGenerator());
}

QString Diagram::generateElementDescriptionMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, ElementDescriptonGenerator());
}

QString Diagram::generateParentsMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, ParentsMapGenerator());
}

class Diagram::ListMethodGenerator {
public:
	virtual ~ListMethodGenerator() {}
	virtual QString generate(Type *type, const QString &lineTemplate) const = 0;
};

class Diagram::UsagesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateUsages(lineTemplate);
	}
};

class Diagram::ContainersGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateContainers(lineTemplate);
	}
};

class Diagram::ReferencePropertiesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateReferenceProperties(lineTemplate);
	}
};

class Diagram::PortTypesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePortTypes(lineTemplate);
	}
};

class Diagram::PropertyNameGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePropertyName(lineTemplate);
	}
};

class Diagram::ConnectionsGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateConnections(lineTemplate);
	}
};

class Diagram::FactoryGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateFactory(lineTemplate);
	}
};

class Diagram::IsNodeOrEdgeGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateIsNodeOrEdge(lineTemplate);
	}
};

class Diagram::EnumsGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateEnums(lineTemplate);
	}
};

class Diagram::PossibleEdgesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePossibleEdges(lineTemplate);
	}
};

QString Diagram::generateUsages(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, UsagesGenerator());
}

QString Diagram::generateConnections(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, ConnectionsGenerator());
}

QString Diagram::generateReferenceProperties(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, ReferencePropertiesGenerator());
}

QString Diagram::generatePortTypes(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, PortTypesGenerator());
}

QString Diagram::generatePropertyName(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, PropertyNameGenerator());
}

QString Diagram::generateContainers(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, ContainersGenerator());
}

QString Diagram::generateFactory(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, FactoryGenerator());
}

QString Diagram::generateIsNodeOrEdge(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, IsNodeOrEdgeGenerator());
}

QString Diagram::generatePossibleEdges(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, PossibleEdgesGenerator());
}

QString Diagram::generateListMethod(const QString &lineTemplate, const ListMethodGenerator &generator) const
{
	QString result;
	bool isFirstLine = true;
	foreach(Type* type, mTypes) {
		QString line = generator.generate(type, lineTemplate);
		if (line.isEmpty())
			continue;
		if (!isFirstLine)
			line.replace("if ", "else if ");
		isFirstLine = false;
		result += line + endline;
	}
	if (result.isEmpty())
		return "	Q_UNUSED(element)" + endline;
	return result;
}

QString Diagram::generateEnums(const QString &lineTemplate) const
{
	EnumsGenerator generator;
	QString result;
	bool isFirstLine = true;

	foreach (EnumType *type, mEditor->getAllEnumTypes()) {
		QString line = generator.generate(type, lineTemplate);
		if (line.isEmpty())
			continue;
		if (!isFirstLine)
			line.replace("if ", "else if ");
		isFirstLine = false;
		result += line + endline;
	}
	return result;
}

QString Diagram::generateNodeClasses(const QString &nodeTemplate) const
{
	return generateMapMethod(nodeTemplate, NodesGenerator());
}

QString Diagram::generateEdgeClasses(const QString &edgeTemplate) const
{
	return generateMapMethod(edgeTemplate, EdgesGenerator());
}

QString Diagram::generateResourceFile(const QString &resourceTemplate) const
{
	return generateMapMethod(resourceTemplate, ResourceGenerator());
}
<commit_msg>- fix for generation without enums<commit_after>#include "diagram.h"
#include "classes/type.h"
#include "classes/enumType.h"
#include "classes/nodeType.h"
#include "classes/edgeType.h"
#include "editor.h"

#include <QDebug>

using namespace qReal;
using namespace qrmc;

Diagram::Diagram(const qReal::Id &id,  qrRepo::LogicalRepoApi *api, Editor *editor)
	: mId(id), mApi(api), mEditor(editor)
{
	mDiagramName = mApi->name(id);
	mDiagramDisplayedName = mApi->stringProperty(id, "displayedName");
	mDiagramNodeName  = mApi->stringProperty(id, "nodeName");
}

Diagram::~Diagram()
{
	foreach(Type *type, mTypes.values())
		if (type)
			delete type;
}

bool Diagram::init()
{
	foreach(Id id, mApi->children(mId)) {
		if (!mApi->isLogicalElement(id))
			continue;

		if (id.element() == metaEntityNode) {
			Type *nodeType = new NodeType(this, mApi, id);
			if (!nodeType->init(mDiagramName)) {
				delete nodeType;
				qDebug() << "can't load node";
				return false;
			}
			mTypes[nodeType->name()] = nodeType;
		} else if (id.element() == metaEntityEdge) {
			Type *edgeType = new EdgeType(this, mApi, id);
			if (!edgeType->init(mDiagramName)) {
				delete edgeType;
				qDebug() << "can't load edge";
				return false;
			}
			mTypes[edgeType->name()] = edgeType;
		} else if (id.element() == metaEntityImport) {
			ImportSpecification import = {
				mApi->stringProperty(id, "importedFrom") + "::" + mApi->stringProperty(id, "as"),
				mApi->stringProperty(id, "as"),
				mApi->stringProperty(id, "displayedName"),
			};
			mImports.append(import);
		} else if (id.element() == metaEntityEnum) {
			Type *enumType = new EnumType(this, mApi, id);
			if (!enumType->init(mDiagramName))
			{
				delete enumType;
				qDebug() << "can't load enum";
				return false;
			}
			mTypes[enumType->name()] = enumType;
		} else {
			qDebug() << "ERROR: unknown type" << id.element();
			return false;
		}
	}
	return true;
}

bool Diagram::resolve()
{
	foreach (ImportSpecification import, mImports) {
		Type *importedType = mEditor->findType(import.name);
		if (importedType == nullptr) {
			qDebug() << "ERROR: imported type" << import.name << "not found, skipping";
			continue;
		}
		Type *copiedType = importedType->clone();
		copiedType->setName(import.as);
		copiedType->setDisplayedName(import.displayedName);
		copiedType->setDiagram(this);
		copiedType->setContext(mDiagramName);
		mTypes.insert(copiedType->qualifiedName(), copiedType);
	}

	foreach(Type *type, mTypes.values())
		if (!type->resolve()) {
			qDebug() << "ERROR: can't resolve type" << type->name();
			return false;
		}

	return true;
}

Editor* Diagram::editor() const
{
	return mEditor;
}

Type* Diagram::findType(QString name)
{
	if (mTypes.contains(name))
		return mTypes[name];

	return mEditor->findType(name);
}

QMap<QString, Type*> Diagram::types() const
{
	return mTypes;
}

QString Diagram::name() const
{
	return mDiagramName;
}

QString Diagram::nodeName() const
{
	return mDiagramNodeName;
}

QString Diagram::displayedName() const
{
	return mDiagramDisplayedName;
}

void Diagram::print()
{
	qDebug() << "elements:" << mTypes.size();
//	foreach(Type *type, mTypes)
//		type->print();
}

class Diagram::MapMethodGenerator {
public:
	virtual ~MapMethodGenerator() {}
	virtual QString generate(Type *type, const QString &lineTemplate) const = 0;
};

class Diagram::NamesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateNames(lineTemplate);
	}
};

class Diagram::MouseGesturesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateMouseGestures(lineTemplate);
	}
};

class Diagram::PropertyNamesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateProperties(lineTemplate);
	}
};

class Diagram::PropertyDefaultsGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePropertyDefaults(lineTemplate);
	}
};

class Diagram::PropertyDisplayedNamesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePropertyDisplayedNames(lineTemplate);
	}
};

class Diagram::ElementDescriptonGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateElementDescription(lineTemplate);
	}
};

class Diagram::ParentsMapGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateParents(lineTemplate);
	}
};

class Diagram::NodesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateNodeClass(lineTemplate);
	}
};

class Diagram::EdgesGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateEdgeClass(lineTemplate);
	}
};

class Diagram::ResourceGenerator: public Diagram::MapMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateResourceLine(lineTemplate);
	}
};

QString Diagram::generateMapMethod(const QString& lineTemplate, const MapMethodGenerator &generator) const
{
	QString result;
	foreach(Type* type, mTypes) {
		QString line = generator.generate(type, lineTemplate);
		if (!line.isEmpty())
			result += line + endline;
	}
	return result;
}

QString Diagram::generateNamesMap(const QString& lineTemplate) const
{
	return generateMapMethod(lineTemplate, NamesGenerator());
}

QString Diagram::generateMouseGesturesMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, MouseGesturesGenerator());
}

QString Diagram::generatePropertiesMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, PropertyNamesGenerator());
}

QString Diagram::generatePropertyDefaultsMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, PropertyDefaultsGenerator());
}

QString Diagram::generatePropertyDisplayedNamesMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, PropertyDisplayedNamesGenerator());
}

QString Diagram::generateElementDescriptionMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, ElementDescriptonGenerator());
}

QString Diagram::generateParentsMap(const QString &lineTemplate) const
{
	return generateMapMethod(lineTemplate, ParentsMapGenerator());
}

class Diagram::ListMethodGenerator {
public:
	virtual ~ListMethodGenerator() {}
	virtual QString generate(Type *type, const QString &lineTemplate) const = 0;
};

class Diagram::UsagesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateUsages(lineTemplate);
	}
};

class Diagram::ContainersGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateContainers(lineTemplate);
	}
};

class Diagram::ReferencePropertiesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateReferenceProperties(lineTemplate);
	}
};

class Diagram::PortTypesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePortTypes(lineTemplate);
	}
};

class Diagram::PropertyNameGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePropertyName(lineTemplate);
	}
};

class Diagram::ConnectionsGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateConnections(lineTemplate);
	}
};

class Diagram::FactoryGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateFactory(lineTemplate);
	}
};

class Diagram::IsNodeOrEdgeGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateIsNodeOrEdge(lineTemplate);
	}
};

class Diagram::EnumsGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generateEnums(lineTemplate);
	}
};

class Diagram::PossibleEdgesGenerator: public Diagram::ListMethodGenerator {
public:
	virtual QString generate(Type *type, const QString &lineTemplate) const {
		return type->generatePossibleEdges(lineTemplate);
	}
};

QString Diagram::generateUsages(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, UsagesGenerator());
}

QString Diagram::generateConnections(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, ConnectionsGenerator());
}

QString Diagram::generateReferenceProperties(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, ReferencePropertiesGenerator());
}

QString Diagram::generatePortTypes(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, PortTypesGenerator());
}

QString Diagram::generatePropertyName(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, PropertyNameGenerator());
}

QString Diagram::generateContainers(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, ContainersGenerator());
}

QString Diagram::generateFactory(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, FactoryGenerator());
}

QString Diagram::generateIsNodeOrEdge(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, IsNodeOrEdgeGenerator());
}

QString Diagram::generatePossibleEdges(const QString &lineTemplate) const
{
	return generateListMethod(lineTemplate, PossibleEdgesGenerator());
}

QString Diagram::generateListMethod(const QString &lineTemplate, const ListMethodGenerator &generator) const
{
	QString result;
	bool isFirstLine = true;
	foreach(Type* type, mTypes) {
		QString line = generator.generate(type, lineTemplate);
		if (line.isEmpty())
			continue;
		if (!isFirstLine)
			line.replace("if ", "else if ");
		isFirstLine = false;
		result += line + endline;
	}
	if (result.isEmpty())
		return "	Q_UNUSED(element)" + endline;
	return result;
}

QString Diagram::generateEnums(const QString &lineTemplate) const
{
	EnumsGenerator generator;
	QString result;
	bool isFirstLine = true;

	foreach (EnumType *type, mEditor->getAllEnumTypes()) {
		QString line = generator.generate(type, lineTemplate);
		if (line.isEmpty())
			continue;
		if (!isFirstLine)
			line.replace("if ", "else if ");
		isFirstLine = false;
		result += line + endline;
	}

	if (result.isEmpty())
		return "	Q_UNUSED(name);";

	return result;
}

QString Diagram::generateNodeClasses(const QString &nodeTemplate) const
{
	return generateMapMethod(nodeTemplate, NodesGenerator());
}

QString Diagram::generateEdgeClasses(const QString &edgeTemplate) const
{
	return generateMapMethod(edgeTemplate, EdgesGenerator());
}

QString Diagram::generateResourceFile(const QString &resourceTemplate) const
{
	return generateMapMethod(resourceTemplate, ResourceGenerator());
}
<|endoftext|>


<commit_before>#include "Cartridge.h"
#include "MemoryMap.h"
#include "Stream.h"
#include <vector>

namespace {
    std::vector<uint8_t> ReadStreamUntil(FileStream& fs, uint8_t delim) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value) && value != delim)
            result.push_back(value);
        if (value != delim)
            FAIL("Failed to find delim");
        return result;
    }

    std::vector<uint8_t> ReadStreamUntilEnd(FileStream& fs) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value))
            result.push_back(value);
        return result;
    }
} // namespace

void Cartridge::Init(MemoryBus& memoryBus) {
    memoryBus.ConnectDevice(*this, MemoryMap::Cartridge.range);
    m_data.resize(MemoryMap::Cartridge.physicalSize, 0);
}

void Cartridge::LoadRom(const char* file) {
    FileStream fs(file, "rb");

    std::string requiredCopyright = "g GCE";
    auto copyright = ReadStreamUntil(fs, 0x80);
    if (copyright.size() < requiredCopyright.size() ||
        memcmp(copyright.data(), requiredCopyright.data(), sizeof(requiredCopyright) != 0))
        FAIL("Invalid ROM");

    // Location of music from ROM
    //@TODO: Byte-swap on little endian!
    uint16_t musicLocation;
    fs.ReadValue(musicLocation);

    uint8_t height, width, relY, relX;
    fs.ReadValue(height);
    fs.ReadValue(width);
    fs.ReadValue(relY);
    fs.ReadValue(relX);

    auto titleBytes = ReadStreamUntil(fs, 0x80);
    std::string title(titleBytes.begin(), titleBytes.end());

    uint8_t headerEnd;
    fs.ReadValue(headerEnd);
    if (headerEnd != 0)
        FAIL("Invalid ROM");

    m_data = ReadStreamUntilEnd(fs);
}

uint8_t Cartridge::Read(uint16_t address) const {
    return m_data.at(MemoryMap::Cartridge.MapAddress(address));
}

void Cartridge::Write(uint16_t /*address*/, uint8_t /*value*/) {
    assert(false && "Writes to ROM not allowed");
}
<commit_msg>Support loading roms with multiline titles<commit_after>#include "Cartridge.h"
#include "MemoryMap.h"
#include "Stream.h"
#include <vector>

namespace {
    std::vector<uint8_t> ReadStreamUntil(FileStream& fs, uint8_t delim) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value) && value != delim)
            result.push_back(value);
        if (value != delim)
            FAIL("Failed to find delim");
        return result;
    }

    std::vector<uint8_t> ReadStreamUntilEnd(FileStream& fs) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value))
            result.push_back(value);
        return result;
    }
} // namespace

void Cartridge::Init(MemoryBus& memoryBus) {
    memoryBus.ConnectDevice(*this, MemoryMap::Cartridge.range);
    m_data.resize(MemoryMap::Cartridge.physicalSize, 0);
}

void Cartridge::LoadRom(const char* file) {
    FileStream fs(file, "rb");

    std::string requiredCopyright = "g GCE";
    auto copyright = ReadStreamUntil(fs, 0x80);
    if (copyright.size() < requiredCopyright.size() ||
        memcmp(copyright.data(), requiredCopyright.data(), sizeof(requiredCopyright) != 0))
        FAIL("Invalid ROM");

    // Location of music from ROM
    //@TODO: Byte-swap on little endian!
    uint16_t musicLocation;
    fs.ReadValue(musicLocation);

    // Title of game is a multiline string of position, string, 0x80 as newline marker.
    std::string title;
    while (true) {
        uint8_t height, width, relY, relX;
        fs.ReadValue(height);
        // If first byte is 0, we're done
        if (height == 0)
            break;
        fs.ReadValue(width);
        fs.ReadValue(relY);
        fs.ReadValue(relX);

        auto titleBytes = ReadStreamUntil(fs, 0x80);
        title += {titleBytes.begin(), titleBytes.end()};
        title += " ";
    }

    m_data = ReadStreamUntilEnd(fs);
}

uint8_t Cartridge::Read(uint16_t address) const {
    return m_data.at(MemoryMap::Cartridge.MapAddress(address));
}

void Cartridge::Write(uint16_t /*address*/, uint8_t /*value*/) {
    assert(false && "Writes to ROM not allowed");
}
<|endoftext|>


<commit_before>#include "Cartridge.h"
#include "MemoryMap.h"
#include "Stream.h"
#include <vector>

namespace {
    std::vector<uint8_t> ReadStreamUntil(FileStream& fs, uint8_t delim) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value) && value != delim)
            result.push_back(value);
        if (value != delim)
            FAIL("Failed to find delim");
        return result;
    }

    std::vector<uint8_t> ReadStreamUntilEnd(FileStream& fs) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value))
            result.push_back(value);
        return result;
    }
} // namespace

void Cartridge::Init(MemoryBus& memoryBus) {
    memoryBus.ConnectDevice(*this, MemoryMap::Cartridge.range);
    // Need to allocate 1 byte at address 0 so that BIOS can check that no cartridge is loaded.
    m_data.push_back(0);
}

void Cartridge::LoadRom(const char* file) {
    FileStream fs(file, "rb");

    std::string requiredCopyright = "g GCE";
    auto copyright = ReadStreamUntil(fs, 0x80);
    if (copyright.size() < requiredCopyright.size() ||
        memcmp(copyright.data(), requiredCopyright.data(), sizeof(requiredCopyright) != 0))
        FAIL("Invalid ROM");

    // Location of music from ROM
    //@TODO: Byte-swap on little endian!
    uint16_t musicLocation;
    fs.ReadValue(musicLocation);

    uint8_t height, width, relY, relX;
    fs.ReadValue(height);
    fs.ReadValue(width);
    fs.ReadValue(relY);
    fs.ReadValue(relX);

    auto titleBytes = ReadStreamUntil(fs, 0x80);
    std::string title(titleBytes.begin(), titleBytes.end());

    uint8_t headerEnd;
    fs.ReadValue(headerEnd);
    if (headerEnd != 0)
        FAIL("Invalid ROM");

    m_data = ReadStreamUntilEnd(fs);
}

uint8_t Cartridge::Read(uint16_t address) const {
    return m_data.at(MemoryMap::Cartridge.MapAddress(address));
}

void Cartridge::Write(uint16_t /*address*/, uint8_t /*value*/) {
    assert(false && "Writes to ROM not allowed");
}
<commit_msg>Cartridge: allocate buffer for the entire 32K address space if no cart is loaded<commit_after>#include "Cartridge.h"
#include "MemoryMap.h"
#include "Stream.h"
#include <vector>

namespace {
    std::vector<uint8_t> ReadStreamUntil(FileStream& fs, uint8_t delim) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value) && value != delim)
            result.push_back(value);
        if (value != delim)
            FAIL("Failed to find delim");
        return result;
    }

    std::vector<uint8_t> ReadStreamUntilEnd(FileStream& fs) {
        std::vector<uint8_t> result;
        uint8_t value;
        while (fs.ReadValue(value))
            result.push_back(value);
        return result;
    }
} // namespace

void Cartridge::Init(MemoryBus& memoryBus) {
    memoryBus.ConnectDevice(*this, MemoryMap::Cartridge.range);
    m_data.resize(MemoryMap::Cartridge.physicalSize, 0);
}

void Cartridge::LoadRom(const char* file) {
    FileStream fs(file, "rb");

    std::string requiredCopyright = "g GCE";
    auto copyright = ReadStreamUntil(fs, 0x80);
    if (copyright.size() < requiredCopyright.size() ||
        memcmp(copyright.data(), requiredCopyright.data(), sizeof(requiredCopyright) != 0))
        FAIL("Invalid ROM");

    // Location of music from ROM
    //@TODO: Byte-swap on little endian!
    uint16_t musicLocation;
    fs.ReadValue(musicLocation);

    uint8_t height, width, relY, relX;
    fs.ReadValue(height);
    fs.ReadValue(width);
    fs.ReadValue(relY);
    fs.ReadValue(relX);

    auto titleBytes = ReadStreamUntil(fs, 0x80);
    std::string title(titleBytes.begin(), titleBytes.end());

    uint8_t headerEnd;
    fs.ReadValue(headerEnd);
    if (headerEnd != 0)
        FAIL("Invalid ROM");

    m_data = ReadStreamUntilEnd(fs);
}

uint8_t Cartridge::Read(uint16_t address) const {
    return m_data.at(MemoryMap::Cartridge.MapAddress(address));
}

void Cartridge::Write(uint16_t /*address*/, uint8_t /*value*/) {
    assert(false && "Writes to ROM not allowed");
}
<|endoftext|>


<commit_before>#include "ChartUtil.h"

namespace rparser
{

void NoteSelection::SelectNote(Note* n)
{
	auto it = std::lower_bound(m_vNotes.begin(), m_vNotes.end(), n, nptr_less_row());
	m_vNotes.insert(it, n);
}
void NoteSelection::UnSelectNote(const Note* n)
{
	for (int i = 0; i < m_vNotes.size(); i++)
	{
		if (*m_vNotes[i] == *n)
		{
			m_vNotes.erase(i + m_vNotes.begin());
			break;
		}
	}
}
std::vector<Note*>& NoteSelection::GetSelection()
{
	return m_vNotes;
}
std::vector<Note*>::iterator NoteSelection::begin()
{
	return m_vNotes.begin();
}
std::vector<Note*>::iterator NoteSelection::end()
{
	return m_vNotes.end();
}
void NoteSelection::Clear()
{
	m_vNotes.clear();
}

void NoteData::TrackMapping(int *trackmap, int s, int e)
{
  // only map for TAPNOTE
  for (auto &n : m_Track)
  {
    if (n.nType != NoteType::NOTE_TAP) continue;
    if (n.x < s || n.x >= e) continue;
    n.x = trackmap[n.x - s] + s;
  }
}

void NoteData::TrackSRandom(int side, int key, bool bHrandom)
{
  ASSERT(key < 10 && key > 0 && side >= 0 && side < 2);
  int vShuffle[10] = {
    0,1,2,3,4,5,6,7,8,9
  };
  float curr_LN_length[10];   // LN length in beat
  for (int i = 0; i < 10; i++) curr_LN_length[i] = 0;

  float curr_beat = -100;		// current lane's beat
  int curr_side = 0;			// current note's lane side
  int curr_shuffle_idx = 0;	// shuffling index
  int curr_note_cnt = 0;		// note count of current beat
  for (auto &n : m_Track) {
    if (n.nType != NoteType::NOTE_TAP) continue;
    curr_side = n.x / 10;
    if (curr_side != side) continue;
    if (curr_beat != n.fBeat)
    {
      // new beat? then shuffle value.
      // (no HRANDOM)
      if (!bHrandom)
      {
        std::random_shuffle(vShuffle, vShuffle + key);
        curr_shuffle_idx = 0;
      }
      float delta_beat = n.fBeat - curr_beat;
      curr_beat = n.fBeat;
      // check longnote ends
      for (int i = 0; i < key; i++)
      {
        curr_LN_length[i] -= delta_beat;
        if (curr_LN_length[i] < 0) curr_LN_length[i] = 0;
      }
      curr_note_cnt = 0;
    }
    // prevent duplication with LN
    while (curr_LN_length[vShuffle[curr_shuffle_idx]] > 0
      && curr_shuffle_idx < key)
    {
      curr_shuffle_idx++;
      curr_note_cnt++;
    }
    if (curr_shuffle_idx >= key)
    {
      // this part will work in case of H-RANDOM
      // prevent note jackhammering by minimizing note shuffling
      // COMMENT:
      // If current lane contains 2 Notes (in 9 keys),
      // Then shuffle 7 note backward and 2 note for forward
      // to minimize note hammering.
      std::random_shuffle(vShuffle, vShuffle + curr_note_cnt);
      std::random_shuffle(vShuffle + curr_note_cnt, vShuffle + key - curr_note_cnt);
      curr_shuffle_idx = 0;
    }
    n.x = vShuffle[curr_shuffle_idx] + curr_side * 10;
    curr_shuffle_idx++;
    curr_note_cnt++;
    // if current note is LN, then remember
    if (n.subType == NoteTapType::TAPNOTE_CHARGE)
    {
      curr_LN_length[vShuffle[curr_shuffle_idx]] = n.fBeatLength;
    }
  }
}

void LaneRandom(int side, int key)
{
  ASSERT(side >= 0 && key >= 0 && key < 10);
  int vShuffle[10] = { 0,1,2,3,4,5,6,7,8,9 };
  std::random_shuffle(vShuffle, vShuffle + key);
  TrackMapping(vShuffle, side * 10, side * 10 + key);
}

void FixImpossibleNote()
{

}

void NoteData::TrackRRandom(int side, int key)
{
  ASSERT(side >= 0 && key >= 0 && key < 10);
  int vShuffle[10] = { 0,1,2,3,4,5,6,7,8,9 };
  int iMoveVal = rand()*key;
  for (int i = 0; i < key; i++)
  {
    vShuffle[i] -= iMoveVal;
    if (vShuffle[i] < 0) vShuffle[i] += key;
  }
  TrackMapping(vShuffle, side * 10, side * 10 + key);
}

void NoteData::TrackMirror(int side, int key)
{
  ASSERT(side >= 0 && key >= 0 && key < 10);
  int vTrackmap[10];
  for (int i = 0; i < key; i++)
  {
    vTrackmap[i] = key - i - 1;
  }
  TrackMapping(vTrackmap, side * 10, side * 10 + key);
}

void NoteData::TrackAllSC(int side)
{
  float curr_beat = -100;		// current beat (to detect beat changing)
  int curr_sc = 0;			// current row has SC?
  std::vector<Note*> vNotes_sc_candidate;
  for (auto &n : m_Track)
  {
    if (n.fBeat != curr_beat)
    {
      // select one note and make it SC
      if (curr_sc == 0)
      {
        Note* n_sc_candidate = vNotes_sc_candidate[vNotes_sc_candidate.size() * rand()];
        n_sc_candidate->x = 0;
      }
      // prepare for next
      curr_sc = 0;
      curr_beat = n.fBeat;
      vNotes_sc_candidate.clear();
    }
    else if (curr_sc) {
      continue;
    }
    // SC channel : 0
    if (n.x == 0)
    {
      curr_sc = 1;
      continue;
    }
    vNotes_sc_candidate.push_back(&n);
  }
}

}
<commit_msg>FiixInvalidNote implementation<commit_after>#include "ChartUtil.h"

namespace rparser
{

void NoteSelection::SelectNote(Note* n)
{
	auto it = std::lower_bound(m_vNotes.begin(), m_vNotes.end(), n, nptr_less_row());
	m_vNotes.insert(it, n);
}
void NoteSelection::UnSelectNote(const Note* n)
{
	for (int i = 0; i < m_vNotes.size(); i++)
	{
		if (*m_vNotes[i] == *n)
		{
			m_vNotes.erase(i + m_vNotes.begin());
			break;
		}
	}
}
std::vector<Note*>& NoteSelection::GetSelection()
{
	return m_vNotes;
}
std::vector<Note*>::iterator NoteSelection::begin()
{
	return m_vNotes.begin();
}
std::vector<Note*>::iterator NoteSelection::end()
{
	return m_vNotes.end();
}
void NoteSelection::Clear()
{
	m_vNotes.clear();
}

void NoteData::TrackMapping(int *trackmap, int s, int e)
{
  // only map for TAPNOTE
  for (auto &n : m_Track)
  {
    if (n.nType != NoteType::NOTE_TAP) continue;
    if (n.x < s || n.x >= e) continue;
    n.x = trackmap[n.x - s] + s;
  }
}

void NoteData::TrackSRandom(int side, int key, bool bHrandom)
{
  ASSERT(key < 10 && key > 0 && side >= 0 && side < 2);
  int vShuffle[10] = {
    0,1,2,3,4,5,6,7,8,9
  };
  float curr_LN_length[10];   // LN length in beat
  for (int i = 0; i < 10; i++) curr_LN_length[i] = 0;

  float curr_beat = -100;		// current lane's beat
  int curr_side = 0;			// current note's lane side
  int curr_shuffle_idx = 0;	// shuffling index
  int curr_note_cnt = 0;		// note count of current beat
  for (auto &n : m_Track) {
    if (n.nType != NoteType::NOTE_TAP) continue;
    curr_side = n.x / 10;
    if (curr_side != side) continue;
    if (curr_beat != n.fBeat)
    {
      // new beat? then shuffle value.
      // (no HRANDOM)
      if (!bHrandom)
      {
        std::random_shuffle(vShuffle, vShuffle + key);
        curr_shuffle_idx = 0;
      }
      float delta_beat = n.fBeat - curr_beat;
      curr_beat = n.fBeat;
      // check longnote ends
      for (int i = 0; i < key; i++)
      {
        curr_LN_length[i] -= delta_beat;
        if (curr_LN_length[i] < 0) curr_LN_length[i] = 0;
      }
      curr_note_cnt = 0;
    }
    // prevent duplication with LN
    while (curr_LN_length[vShuffle[curr_shuffle_idx]] > 0
      && curr_shuffle_idx < key)
    {
      curr_shuffle_idx++;
      curr_note_cnt++;
    }
    if (curr_shuffle_idx >= key)
    {
      // this part will work in case of H-RANDOM
      // prevent note jackhammering by minimizing note shuffling
      // COMMENT:
      // If current lane contains 2 Notes (in 9 keys),
      // Then shuffle 7 note backward and 2 note for forward
      // to minimize note hammering.
      std::random_shuffle(vShuffle, vShuffle + curr_note_cnt);
      std::random_shuffle(vShuffle + curr_note_cnt, vShuffle + key - curr_note_cnt);
      curr_shuffle_idx = 0;
    }
    n.x = vShuffle[curr_shuffle_idx] + curr_side * 10;
    curr_shuffle_idx++;
    curr_note_cnt++;
    // if current note is LN, then remember
    if (n.subType == NoteTapType::TAPNOTE_CHARGE)
    {
      curr_LN_length[vShuffle[curr_shuffle_idx]] = n.fBeatLength;
    }
  }
}

void LaneRandom(int side, int key)
{
  ASSERT(side >= 0 && key >= 0 && key < 10);
  int vShuffle[10] = { 0,1,2,3,4,5,6,7,8,9 };
  std::random_shuffle(vShuffle, vShuffle + key);
  TrackMapping(vShuffle, side * 10, side * 10 + key);
}

void FixInvalidNote(Chart &c, bool delete_invalid_note)
{
  // TODO: currently for note type.
  //       in case of pos type ...?
  unsigned int player_count = c.GetMetaData().player_count;
  unsigned int track_column_count = c.GetMetaData().track_column_count;
  double current_beat = -1;
  Note* note_using_lane[5][256];
  int current_lane;
  int current_player;

  ASSERT(player_count < 5);
  ASSERT(track_column_count < 128);

  // must sorted first
  c.GetNoteData().SortByBeat();

  memset(note_using_lane, 0, sizeof(note_using_lane));

  for (auto& note: c.GetNoteData())
  {
    current_lane = note.track.channel.note.lane;
    current_player = note.track.channel.note.player;
    if (note.track.type != NoteTypes::kNote)
      continue;
    if (note.track.subtype != NoteTypes::kNote)
      continue;
    // if beat change, invalidate all marked note status
    if (note.pos.beat != current_beat)
    {
      current_beat = note.pos.beat;
      for (int pi=0 ; pi<player_count ; pi++)
      {
        for (int i=0 ; i<track_column_count ; i++)
        {
          Note** ncl = &note_using_lane[pi][i];
          if (!(*ncl)->next)
          {
            // not longnote (or end of longnote), instantly clear.
            (*ncl) = 0;
          }
          else
          {
            // in case of longnote, renew longnote object.
            if ((*ncl)->pos.beat < current_beat)
              (*ncl) = (*ncl)->next;
          }
        }
      }
    }
    // attempt to put note in empty lane.
    // if lane used, then attempt to next (right) lane.
    // if proper lane not found, then note won't edited. (stay in incorrect one)
    for (int i=0; i<track_column_count; i++)
    {
      int new_lane = (current_lane + i) % track_column_count;
      if (!note_using_lane[current_player][new_lane])
      {
        note.track.channel.note.lane = new_lane;
        note_using_lane[current_player][new_lane] = &note;
        break;
      }
    }
  }
}

void NoteData::TrackRRandom(int side, int key)
{
  ASSERT(side >= 0 && key >= 0 && key < 10);
  int vShuffle[10] = { 0,1,2,3,4,5,6,7,8,9 };
  int iMoveVal = rand()*key;
  for (int i = 0; i < key; i++)
  {
    vShuffle[i] -= iMoveVal;
    if (vShuffle[i] < 0) vShuffle[i] += key;
  }
  TrackMapping(vShuffle, side * 10, side * 10 + key);
}

void NoteData::TrackMirror(int side, int key)
{
  ASSERT(side >= 0 && key >= 0 && key < 10);
  int vTrackmap[10];
  for (int i = 0; i < key; i++)
  {
    vTrackmap[i] = key - i - 1;
  }
  TrackMapping(vTrackmap, side * 10, side * 10 + key);
}

void NoteData::TrackAllSC(int side)
{
  float curr_beat = -100;		// current beat (to detect beat changing)
  int curr_sc = 0;			// current row has SC?
  std::vector<Note*> vNotes_sc_candidate;
  for (auto &n : m_Track)
  {
    if (n.fBeat != curr_beat)
    {
      // select one note and make it SC
      if (curr_sc == 0)
      {
        Note* n_sc_candidate = vNotes_sc_candidate[vNotes_sc_candidate.size() * rand()];
        n_sc_candidate->x = 0;
      }
      // prepare for next
      curr_sc = 0;
      curr_beat = n.fBeat;
      vNotes_sc_candidate.clear();
    }
    else if (curr_sc) {
      continue;
    }
    // SC channel : 0
    if (n.x == 0)
    {
      curr_sc = 1;
      continue;
    }
    vNotes_sc_candidate.push_back(&n);
  }
}

}
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Implementation of GPIOv1 functions for STM32F1
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/STM32-GPIOv1.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void configurePin(const Pin pin, const PinConfiguration configuration, const bool initialState)
{
	const auto decodedPin = decodePin(pin);
	auto& port = *decodedPin.first;
	const auto pinNumber = decodedPin.second;
	auto& cr = pinNumber < 8 ? port.CRL : port.CRH;
	const auto invertedMask = ~((GPIO_CRL_CNF0 | GPIO_CRL_MODE0) << ((pinNumber * 4) % 32));
	const auto configurationValue = static_cast<uint32_t>(configuration) << ((pinNumber * 4) % 32);

	(initialState == false ? port.BRR : port.BSRR) = 1 << pinNumber;

	architecture::InterruptMaskingLock interruptMaskingLock;

	cr = (cr & invertedMask) | configurationValue;
}

}	// namespace chip

}	// namespace distortos
<commit_msg>Simplify code of configurePin() for GPIOv1 in STM32<commit_after>/**
 * \file
 * \brief Implementation of GPIOv1 functions for STM32F1
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/STM32-GPIOv1.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void configurePin(const Pin pin, const PinConfiguration configuration, const bool initialState)
{
	const auto decodedPin = decodePin(pin);
	auto& port = *decodedPin.first;
	const auto pinNumber = decodedPin.second;
	auto& cr = pinNumber < 8 ? port.CRL : port.CRH;
	const auto invertedMask = ~((GPIO_CRL_CNF0 | GPIO_CRL_MODE0) << ((pinNumber * 4) % 32));
	const auto configurationValue = static_cast<uint32_t>(configuration) << ((pinNumber * 4) % 32);

	port.BSRR = 1 << (pinNumber + (initialState == false ? 16 : 0));

	architecture::InterruptMaskingLock interruptMaskingLock;

	cr = (cr & invertedMask) | configurationValue;
}

}	// namespace chip

}	// namespace distortos
<|endoftext|>


<commit_before>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// 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 HOLDER 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 "function_object.hh"
#include "fun_compiler.hh"

namespace tadpole {

int FunCompiler::resolve_local(const Token& name, const ErrorFn& errfn) {
  for (int i = locals_count() - 1; i >= 0; --i) {
    auto& local = locals_[i];
    if (local.name == name) {
      if (local.depth == -1)
        errfn(from_fmt("cannot load local variable `%s` in its own initializer", name.as_cstring()));
      return i;
    }
  }
  return -1;
}

int FunCompiler::add_upvalue(u8_t index, bool is_local) {
  for (int i = 0; i < fn_->upvalues_count(); ++i) {
    if (upvalues_[i].is_equal(index, is_local))
      return i;
  }

  upvalues_.push_back(Upvalue(index, is_local));
  return as_type<int>(fn_->inc_upvalues_count());
}

int FunCompiler::resolve_upvalue(const Token& name, const ErrorFn& errfn) {
  return 0;
}

void FunCompiler::declare_localvar(const Token& name, const ErrorFn& errfn) {
}

}
<commit_msg>:construction: chore(upvalue): add implementation of resolving upvalue<commit_after>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// 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 HOLDER 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 "function_object.hh"
#include "fun_compiler.hh"

namespace tadpole {

int FunCompiler::resolve_local(const Token& name, const ErrorFn& errfn) {
  for (int i = locals_count() - 1; i >= 0; --i) {
    auto& local = locals_[i];
    if (local.name == name) {
      if (local.depth == -1)
        errfn(from_fmt("cannot load local variable `%s` in its own initializer", name.as_cstring()));
      return i;
    }
  }
  return -1;
}

int FunCompiler::add_upvalue(u8_t index, bool is_local) {
  for (int i = 0; i < fn_->upvalues_count(); ++i) {
    if (upvalues_[i].is_equal(index, is_local))
      return i;
  }

  upvalues_.push_back(Upvalue(index, is_local));
  return as_type<int>(fn_->inc_upvalues_count());
}

int FunCompiler::resolve_upvalue(const Token& name, const ErrorFn& errfn) {
  if (enclosing_ == nullptr)
    return -1;

  if (int local = enclosing_->resolve_local(name, errfn); local != -1) {
    enclosing_->locals_[local].is_upvalue = true;
    return add_upvalue(as_type<u8_t>(local), true);
  }
  if (int upvalue = enclosing_->resolve_upvalue(name, errfn); upvalue != -1)
    return add_upvalue(as_type<u8_t>(upvalue), false);

  return -1;
}

void FunCompiler::declare_localvar(const Token& name, const ErrorFn& errfn) {
}

}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}
<commit_msg>CPP: Add missing license in cpp/test/phonenumbers/run_tests.cc.<commit_after>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <gtest/gtest.h>

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before><commit_msg>sc/qa/unit: recover xDocSh->DoClose()<commit_after><|endoftext|>